From 53ec84e187083bcd0ab684a361c8ad3510e670fa Mon Sep 17 00:00:00 2001 From: Michal Dybizbanski Date: Tue, 24 Sep 2024 17:29:21 +0200 Subject: [PATCH 1/2] XCD-159 Optionally globalize GLTF's entityId --- src/plugins/GLTFLoaderPlugin/GLTFLoaderPlugin.js | 1 + src/plugins/GLTFLoaderPlugin/GLTFSceneModelLoader.js | 8 +++++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/plugins/GLTFLoaderPlugin/GLTFLoaderPlugin.js b/src/plugins/GLTFLoaderPlugin/GLTFLoaderPlugin.js index 3658874f6..361eee877 100644 --- a/src/plugins/GLTFLoaderPlugin/GLTFLoaderPlugin.js +++ b/src/plugins/GLTFLoaderPlugin/GLTFLoaderPlugin.js @@ -322,6 +322,7 @@ class GLTFLoaderPlugin extends Plugin { * to non-textured triangle meshes, and that VBOs are always used for meshes that have textures, line segments, or point * primitives. Only works while {@link DTX#enabled} is also ````true````. * @param {Boolean} [params.autoMetaModel] When supplied, creates a default MetaModel with a single MetaObject. + * @param {Boolean} [params.globalizeObjectIds=false] Indicates whether to globalize each {@link Entity#id} and {@link MetaObject#id}, in case you need to prevent ID clashes with other models. * @returns {Entity} Entity representing the model, which will have {@link Entity#isModel} set ````true```` and will be registered by {@link Entity#id} in {@link Scene#models} */ load(params = {}) { diff --git a/src/plugins/GLTFLoaderPlugin/GLTFSceneModelLoader.js b/src/plugins/GLTFLoaderPlugin/GLTFSceneModelLoader.js index 8a6f07c20..94ace8c24 100644 --- a/src/plugins/GLTFLoaderPlugin/GLTFSceneModelLoader.js +++ b/src/plugins/GLTFLoaderPlugin/GLTFSceneModelLoader.js @@ -109,6 +109,7 @@ function parseGLTF(plugin, src, gltf, metaModelJSON, options, sceneModel, ok) { entityId: options.entityId, metaModelJSON, autoMetaModel: options.autoMetaModel, + globalizeObjectIds: options.globalizeObjectIds, metaObjects: [], loadBuffer: options.loadBuffer, basePath: options.basePath, @@ -444,16 +445,17 @@ function loadDefaultScene(ctx) { if (entityId) { if (meshIds.length > 0) { + const globalId = ctx.globalizeObjectIds ? math.globalizeObjectId(ctx.sceneModel.id, entityId) : entityId; ctx.sceneModel.createEntity({ - id: entityId, + id: globalId, meshIds: meshIds, isObject: true }); if (ctx.autoMetaModel) { ctx.metaObjects.push({ - id: entityId, + id: globalId, type: "Default", - name: entityId, + name: globalId, parent: ctx.sceneModel.id }); } From 480c0e29e425cefe8146963b81435ba291931fe9 Mon Sep 17 00:00:00 2001 From: Michal Dybizbanski Date: Tue, 24 Sep 2024 17:30:38 +0200 Subject: [PATCH 2/2] Rebuild --- dist/xeokit-sdk.cjs.js | 18 +++++++++++++----- dist/xeokit-sdk.es.js | 18 +++++++++++++----- dist/xeokit-sdk.es5.js | 14 +++++++++----- dist/xeokit-sdk.min.cjs.js | 8 ++++---- dist/xeokit-sdk.min.es.js | 8 ++++---- dist/xeokit-sdk.min.es5.js | 2 +- 6 files changed, 44 insertions(+), 24 deletions(-) diff --git a/dist/xeokit-sdk.cjs.js b/dist/xeokit-sdk.cjs.js index 639efcfa6..e6eb413ee 100644 --- a/dist/xeokit-sdk.cjs.js +++ b/dist/xeokit-sdk.cjs.js @@ -110476,10 +110476,14 @@ class Viewer { for (let i = 0, len = pluginContainerElements.length; i < len; i++) { const containerElement = pluginContainerElements[i]; + //only calculate the scale for first plugin + //for all others keep the scale 1 otherwise it will keep multiplying the scale with the base scale of canvas + //resulting in increase/decreased size for the the canvas that is being overlapped + const scale = i == 0 ? snapshotCanvas.width / containerElement.clientWidth : 1; await html2canvas(containerElement, { canvas: snapshotCanvas, backgroundColor: null, - scale: snapshotCanvas.width / containerElement.clientWidth + scale }); } if (!params.includeGizmos) { @@ -117990,6 +117994,7 @@ function parseGLTF(plugin, src, gltf, metaModelJSON, options, sceneModel, ok) { entityId: options.entityId, metaModelJSON, autoMetaModel: options.autoMetaModel, + globalizeObjectIds: options.globalizeObjectIds, metaObjects: [], loadBuffer: options.loadBuffer, basePath: options.basePath, @@ -118318,16 +118323,17 @@ function loadDefaultScene(ctx) { if (entityId) { if (meshIds.length > 0) { + const globalId = ctx.globalizeObjectIds ? math.globalizeObjectId(ctx.sceneModel.id, entityId) : entityId; ctx.sceneModel.createEntity({ - id: entityId, + id: globalId, meshIds: meshIds, isObject: true }); if (ctx.autoMetaModel) { ctx.metaObjects.push({ - id: entityId, + id: globalId, type: "Default", - name: entityId, + name: globalId, parent: ctx.sceneModel.id }); } @@ -118810,6 +118816,7 @@ class GLTFLoaderPlugin extends Plugin { * to non-textured triangle meshes, and that VBOs are always used for meshes that have textures, line segments, or point * primitives. Only works while {@link DTX#enabled} is also ````true````. * @param {Boolean} [params.autoMetaModel] When supplied, creates a default MetaModel with a single MetaObject. + * @param {Boolean} [params.globalizeObjectIds=false] Indicates whether to globalize each {@link Entity#id} and {@link MetaObject#id}, in case you need to prevent ID clashes with other models. * @returns {Entity} Entity representing the model, which will have {@link Entity#isModel} set ````true```` and will be registered by {@link Entity#id} in {@link Scene#models} */ load(params = {}) { @@ -140178,7 +140185,8 @@ class DotBIMLoaderPlugin extends Plugin { } metaModelData.propertySets.push({ id: objectId, - properties + name: "Properties", + properties: properties }); metaModelData.metaObjects.push({ diff --git a/dist/xeokit-sdk.es.js b/dist/xeokit-sdk.es.js index f023aaa7c..6887a2e90 100644 --- a/dist/xeokit-sdk.es.js +++ b/dist/xeokit-sdk.es.js @@ -110472,10 +110472,14 @@ class Viewer { for (let i = 0, len = pluginContainerElements.length; i < len; i++) { const containerElement = pluginContainerElements[i]; + //only calculate the scale for first plugin + //for all others keep the scale 1 otherwise it will keep multiplying the scale with the base scale of canvas + //resulting in increase/decreased size for the the canvas that is being overlapped + const scale = i == 0 ? snapshotCanvas.width / containerElement.clientWidth : 1; await html2canvas(containerElement, { canvas: snapshotCanvas, backgroundColor: null, - scale: snapshotCanvas.width / containerElement.clientWidth + scale }); } if (!params.includeGizmos) { @@ -117986,6 +117990,7 @@ function parseGLTF(plugin, src, gltf, metaModelJSON, options, sceneModel, ok) { entityId: options.entityId, metaModelJSON, autoMetaModel: options.autoMetaModel, + globalizeObjectIds: options.globalizeObjectIds, metaObjects: [], loadBuffer: options.loadBuffer, basePath: options.basePath, @@ -118314,16 +118319,17 @@ function loadDefaultScene(ctx) { if (entityId) { if (meshIds.length > 0) { + const globalId = ctx.globalizeObjectIds ? math.globalizeObjectId(ctx.sceneModel.id, entityId) : entityId; ctx.sceneModel.createEntity({ - id: entityId, + id: globalId, meshIds: meshIds, isObject: true }); if (ctx.autoMetaModel) { ctx.metaObjects.push({ - id: entityId, + id: globalId, type: "Default", - name: entityId, + name: globalId, parent: ctx.sceneModel.id }); } @@ -118806,6 +118812,7 @@ class GLTFLoaderPlugin extends Plugin { * to non-textured triangle meshes, and that VBOs are always used for meshes that have textures, line segments, or point * primitives. Only works while {@link DTX#enabled} is also ````true````. * @param {Boolean} [params.autoMetaModel] When supplied, creates a default MetaModel with a single MetaObject. + * @param {Boolean} [params.globalizeObjectIds=false] Indicates whether to globalize each {@link Entity#id} and {@link MetaObject#id}, in case you need to prevent ID clashes with other models. * @returns {Entity} Entity representing the model, which will have {@link Entity#isModel} set ````true```` and will be registered by {@link Entity#id} in {@link Scene#models} */ load(params = {}) { @@ -140174,7 +140181,8 @@ class DotBIMLoaderPlugin extends Plugin { } metaModelData.propertySets.push({ id: objectId, - properties + name: "Properties", + properties: properties }); metaModelData.metaObjects.push({ diff --git a/dist/xeokit-sdk.es5.js b/dist/xeokit-sdk.es5.js index 564ad2aec..dec938bf0 100644 --- a/dist/xeokit-sdk.es5.js +++ b/dist/xeokit-sdk.es5.js @@ -25060,7 +25060,7 @@ this.scene.fire("rendering",{},true);this.scene._renderer.renderSnapshot();var i * @param {String} [params.format="jpeg"] Desired format; "jpeg", "png" or "bmp". * @param {Boolean} [params.includeGizmos=false] When true, will include gizmos like {@link SectionPlane} in the snapshot. * @returns {Promise} Promise which returns a string-encoded image data URI. - */},{key:"getSnapshotWithPlugins",value:function(){var _getSnapshotWithPlugins=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(){var params,needFinishSnapshot,resize,canvas,saveWidth,saveHeight,snapshotWidth,snapshotHeight,snapshotCanvas,pluginToCapture,pluginContainerElements,_i508,len,plugin,containerElement,_i509,_len103,_containerElement,format,_args=arguments;return _regeneratorRuntime().wrap(function _callee$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:params=_args.length>0&&_args[0]!==undefined?_args[0]:{};// We use gl.readPixels to get the WebGL canvas snapshot in a new + */},{key:"getSnapshotWithPlugins",value:function(){var _getSnapshotWithPlugins=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(){var params,needFinishSnapshot,resize,canvas,saveWidth,saveHeight,snapshotWidth,snapshotHeight,snapshotCanvas,pluginToCapture,pluginContainerElements,_i508,len,plugin,containerElement,_i509,_len103,_containerElement,_scale6,format,_args=arguments;return _regeneratorRuntime().wrap(function _callee$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:params=_args.length>0&&_args[0]!==undefined?_args[0]:{};// We use gl.readPixels to get the WebGL canvas snapshot in a new // HTMLCanvas element, scaled to the target snapshot size, then // use html2canvas to render each plugin's container element into // that HTMLCanvas. Finally, we save the HTMLCanvas to a bitmap. @@ -25071,7 +25071,10 @@ this.scene.fire("rendering",{},true);this.scene._renderer.renderSnapshot();var i // right amount of pixels, for a sharper image. needFinishSnapshot=!this._snapshotBegun;resize=params.width!==undefined&¶ms.height!==undefined;canvas=this.scene.canvas.canvas;saveWidth=canvas.clientWidth;saveHeight=canvas.clientHeight;snapshotWidth=params.width?Math.floor(params.width):canvas.width;snapshotHeight=params.height?Math.floor(params.height):canvas.height;if(resize){canvas.width=snapshotWidth;canvas.height=snapshotHeight;}if(!this._snapshotBegun){this.beginSnapshot();}if(!params.includeGizmos){this.sendToPlugins("snapshotStarting");// Tells plugins to hide things that shouldn't be in snapshot }this.scene._renderer.renderSnapshot();snapshotCanvas=this.scene._renderer.readSnapshotAsCanvas();if(resize){canvas.width=saveWidth;canvas.height=saveHeight;this.scene.glRedraw();}pluginToCapture={};pluginContainerElements=[];for(_i508=0,len=this._plugins.length;_i5080){ctx.sceneModel.createEntity({id:entityId,meshIds:meshIds,isObject:true});if(ctx.autoMetaModel){ctx.metaObjects.push({id:entityId,type:"Default",name:entityId,parent:ctx.sceneModel.id});}}meshIds=meshIdsStack.pop();}});})(nodes,0,null);}/** +var meshIdsStack=[];var meshIds=null;(function createSceneMeshesAndEntities(nodes,depth,parentMatrix){nodes.forEach(function(node){var nodeName=node.name;var entityId=nodeName!==undefined&&nodeName!==null&&nodeName||depth===0&&"entity-"+ctx.nextId++;if(entityId){while(ctx.sceneModel.objects[entityId]){entityId="entity-"+ctx.nextId++;}meshIdsStack.push(meshIds);meshIds=[];}var matrix=parseNodeMatrix(node,parentMatrix);if(node.mesh){parseNodeMesh(node,ctx,matrix,meshIds);}if(node.children){createSceneMeshesAndEntities(node.children,depth+1,matrix);}if(entityId){if(meshIds.length>0){var globalId=ctx.globalizeObjectIds?math.globalizeObjectId(ctx.sceneModel.id,entityId):entityId;ctx.sceneModel.createEntity({id:globalId,meshIds:meshIds,isObject:true});if(ctx.autoMetaModel){ctx.metaObjects.push({id:globalId,type:"Default",name:globalId,parent:ctx.sceneModel.id});}}meshIds=meshIdsStack.pop();}});})(nodes,0,null);}/** * Parses transform at the given glTF node. * * @param node the glTF node @@ -25403,6 +25406,7 @@ if(rtcNeeded){meshCfg.origin=origin;}ctx.sceneModel.createMesh(meshCfg);meshIds. * to non-textured triangle meshes, and that VBOs are always used for meshes that have textures, line segments, or point * primitives. Only works while {@link DTX#enabled} is also ````true````. * @param {Boolean} [params.autoMetaModel] When supplied, creates a default MetaModel with a single MetaObject. + * @param {Boolean} [params.globalizeObjectIds=false] Indicates whether to globalize each {@link Entity#id} and {@link MetaObject#id}, in case you need to prevent ID clashes with other models. * @returns {Entity} Entity representing the model, which will have {@link Entity#isModel} set ````true```` and will be registered by {@link Entity#id} in {@link Scene#models} */,set:function set(value){this._objectDefaults=value||IFCObjectDefaults;}},{key:"load",value:function load(){var _this132=this;var params=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};if(params.id&&this.viewer.scene.components[params.id]){this.error("Component with this ID already exists in viewer: "+params.id+" - will autogenerate this ID");delete params.id;}var sceneModel=new SceneModel(this.viewer.scene,utils.apply(params,{isModel:true,dtxEnabled:params.dtxEnabled}));var modelId=sceneModel.id;// In case ID was auto-generated if(!params.src&&!params.gltf){this.error("load() param expected: src or gltf");return sceneModel;// Return new empty model @@ -30384,7 +30388,7 @@ var pList=[];for(var k=0;k0&&arguments[0]!==undefined?arguments[0]:{};if(params.id&&this.viewer.scene.components[params.id]){this.error("Component with this ID already exists in viewer: "+params.id+" - will autogenerate this ID");delete params.id;}var sceneModel=new SceneModel(this.viewer.scene,utils.apply(params,{isModel:true,backfaces:params.backfaces,dtxEnabled:params.dtxEnabled,rotation:params.rotation,origin:params.origin}));var modelId=sceneModel.id;// In case ID was auto-generated if(!params.src&&!params.dotBIM){this.error("load() param expected: src or dotBIM");return sceneModel;// Return new empty model -}var objectDefaults=params.objectDefaults||this._objectDefaults||IFCObjectDefaults;var includeTypes;if(params.includeTypes){includeTypes={};for(var _i603=0,len=params.includeTypes.length;_i603o,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new n(e||2),vec3:e=>new n(e||3),vec4:e=>new n(e||4),mat3:e=>new n(e||9),mat3ToMat4:(e,t=new n(16))=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t),mat4:e=>new n(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,i){const s=new n(2);for(let r=0,o=e.length;r{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,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(ee[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i),addVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i),addVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i),addVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i),subVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i),subVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i),subVec2:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i),geometricMeanVec2(...e){const t=new n(e[0]);for(let i=1;i(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i),subScalarVec4:(e,t,i)=>(i||(i=e),i[0]=t-e[0],i[1]=t-e[1],i[2]=t-e[2],i[3]=t-e[3],i),mulVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]*t[0],i[1]=e[1]*t[1],i[2]=e[2]*t[2],i[3]=e[3]*t[3],i),mulVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i),mulVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i),mulVec2Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i),divVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i),divVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i[3]=e[3]/t[3],i),divScalarVec3:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i),divVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i),divVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i[3]=e[3]/t,i),divScalarVec4:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i[3]=e/t[3],i),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const i=e[0],s=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[s*a-r*n,r*o-i*a,i*n-s*o,0]},cross3Vec3(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return i[0]=r*l-o*a,i[1]=o*n-s*l,i[2]=s*a-r*n,i},sqLenVec4:e=>c.dotVec4(e,e),lenVec4:e=>Math.sqrt(c.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=>c.dotVec3(e,e),sqLenVec2:e=>c.dotVec2(e,e),lenVec3:e=>Math.sqrt(c.sqLenVec3(e)),distVec3:(()=>{const e=new n(3);return(t,i)=>c.lenVec3(c.subVec3(t,i,e))})(),lenVec2:e=>Math.sqrt(c.sqLenVec2(e)),distVec2:(()=>{const e=new n(2);return(t,i)=>c.lenVec2(c.subVec2(t,i,e))})(),rcpVec3:(e,t)=>c.divScalarVec3(1,e,t),normalizeVec4(e,t){const i=1/c.lenVec4(e);return c.mulVec4Scalar(e,i,t)},normalizeVec3(e,t){const i=1/c.lenVec3(e);return c.mulVec3Scalar(e,i,t)},normalizeVec2(e,t){const i=1/c.lenVec2(e);return c.mulVec2Scalar(e,i,t)},angleVec3(e,t){let i=c.dotVec3(e,t)/Math.sqrt(c.sqLenVec3(e)*c.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:(()=>{const e=new n(3);return(t,i)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=c.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=c.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=c.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({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||c.vec3())[0]=e.x,t[1]=e.y,t[2]=e.z,t),dupMat4:e=>e.slice(0,16),mat4To3:e=>[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]],m4s:e=>[e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e],setMat4ToZeroes:()=>c.m4s(0),setMat4ToOnes:()=>c.m4s(1),diagonalMat4v:e=>new n([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,i,s)=>c.diagonalMat4v([e,t,i,s]),diagonalMat4s:e=>c.diagonalMat4c(e,e,e,e),identityMat4:(e=new n(16))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e),identityMat3:(e=new n(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i),addMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i),addScalarMat4:(e,t,i)=>c.addMat4Scalar(t,e,i),subMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i),subMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i),subScalarMat4:(e,t,i)=>(i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i),mulMat4(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],A=e[6],h=e[7],c=e[8],u=e[9],d=e[10],p=e[11],f=e[12],g=e[13],m=e[14],_=e[15],v=t[0],b=t[1],y=t[2],x=t[3],B=t[4],w=t[5],P=t[6],C=t[7],M=t[8],E=t[9],F=t[10],I=t[11],D=t[12],S=t[13],T=t[14],R=t[15];return i[0]=v*s+b*a+y*c+x*f,i[1]=v*r+b*l+y*u+x*g,i[2]=v*o+b*A+y*d+x*m,i[3]=v*n+b*h+y*p+x*_,i[4]=B*s+w*a+P*c+C*f,i[5]=B*r+w*l+P*u+C*g,i[6]=B*o+w*A+P*d+C*m,i[7]=B*n+w*h+P*p+C*_,i[8]=M*s+E*a+F*c+I*f,i[9]=M*r+E*l+F*u+I*g,i[10]=M*o+E*A+F*d+I*m,i[11]=M*n+E*h+F*p+I*_,i[12]=D*s+S*a+T*c+R*f,i[13]=D*r+S*l+T*u+R*g,i[14]=D*o+S*A+T*d+R*m,i[15]=D*n+S*h+T*p+R*_,i},mulMat3(e,t,i){i||(i=new n(9));const s=e[0],r=e[3],o=e[6],a=e[1],l=e[4],A=e[7],h=e[2],c=e[5],u=e[8],d=t[0],p=t[3],f=t[6],g=t[1],m=t[4],_=t[7],v=t[2],b=t[5],y=t[8];return i[0]=s*d+r*g+o*v,i[3]=s*p+r*m+o*b,i[6]=s*f+r*_+o*y,i[1]=a*d+l*g+A*v,i[4]=a*p+l*m+A*b,i[7]=a*f+l*_+A*y,i[2]=h*d+c*g+u*v,i[5]=h*p+c*m+u*b,i[8]=h*f+c*_+u*y,i},mulMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i),mulMat4v4(e,t,i=c.vec4()){const s=t[0],r=t[1],o=t[2],n=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*n,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*n,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*n,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*n,i},transposeMat4(e,t){const i=e[4],s=e[14],r=e[8],o=e[13],n=e[12],a=e[9];if(!t||e===t){const t=e[1],l=e[2],A=e[3],h=e[6],c=e[7],u=e[11];return e[1]=i,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=h,e[11]=s,e[12]=A,e[13]=c,e[14]=u,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=n,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=o,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4(e){const t=e[0],i=e[1],s=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],A=e[8],h=e[9],c=e[10],u=e[11],d=e[12],p=e[13],f=e[14],g=e[15];return d*h*a*r-A*p*a*r-d*n*c*r+o*p*c*r+A*n*f*r-o*h*f*r-d*h*s*l+A*p*s*l+d*i*c*l-t*p*c*l-A*i*f*l+t*h*f*l+d*n*s*u-o*p*s*u-d*i*a*u+t*p*a*u+o*i*f*u-t*n*f*u-A*n*s*g+o*h*s*g+A*i*a*g-t*h*a*g-o*i*c*g+t*n*c*g},inverseMat4(e,t){t||(t=e);const i=e[0],s=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],A=e[7],h=e[8],c=e[9],u=e[10],d=e[11],p=e[12],f=e[13],g=e[14],m=e[15],_=i*a-s*n,v=i*l-r*n,b=i*A-o*n,y=s*l-r*a,x=s*A-o*a,B=r*A-o*l,w=h*f-c*p,P=h*g-u*p,C=h*m-d*p,M=c*g-u*f,E=c*m-d*f,F=u*m-d*g,I=1/(_*F-v*E+b*M+y*C-x*P+B*w);return t[0]=(a*F-l*E+A*M)*I,t[1]=(-s*F+r*E-o*M)*I,t[2]=(f*B-g*x+m*y)*I,t[3]=(-c*B+u*x-d*y)*I,t[4]=(-n*F+l*C-A*P)*I,t[5]=(i*F-r*C+o*P)*I,t[6]=(-p*B+g*b-m*v)*I,t[7]=(h*B-u*b+d*v)*I,t[8]=(n*E-a*C+A*w)*I,t[9]=(-i*E+s*C-o*w)*I,t[10]=(p*x-f*b+m*_)*I,t[11]=(-h*x+c*b-d*_)*I,t[12]=(-n*M+a*P-l*w)*I,t[13]=(i*M-s*P+r*w)*I,t[14]=(-p*y+f*v-g*_)*I,t[15]=(h*y-c*v+u*_)*I,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const i=t||c.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v(e,t){const i=t||c.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(()=>{const e=new n(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,c.translationMat4v(e,r))})(),translationMat4s:(e,t)=>c.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>c.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,i,s){const r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;const o=s[7];s[4]+=o*e,s[5]+=o*t,s[6]+=o*i;const n=s[11];s[8]+=n*e,s[9]+=n*t,s[10]+=n*i;const a=s[15];return s[12]+=a*e,s[13]+=a*t,s[14]+=a*i,s},setMat4Translation:(e,t,i)=>(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i),rotationMat4v(e,t,i){const s=c.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=s[0],l=s[1],A=s[2];let h,u,d,p,f,g;return h=a*l,u=l*A,d=A*a,p=a*r,f=l*r,g=A*r,(i=i||c.mat4())[0]=n*a*a+o,i[1]=n*h+g,i[2]=n*d-f,i[3]=0,i[4]=n*h-g,i[5]=n*l*l+o,i[6]=n*u+p,i[7]=0,i[8]=n*d+f,i[9]=n*u-p,i[10]=n*A*A+o,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:(e,t,i,s,r)=>c.rotationMat4v(e,[t,i,s],r),scalingMat4v:(e,t=c.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=c.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new n(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,c.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=>c.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,i=c.mat4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=s+s,l=r+r,A=o+o,h=s*a,u=s*l,d=s*A,p=r*l,f=r*A,g=o*A,m=n*a,_=n*l,v=n*A;return i[0]=1-(p+g),i[1]=u+v,i[2]=d-_,i[3]=0,i[4]=u-v,i[5]=1-(h+g),i[6]=f+m,i[7]=0,i[8]=d+_,i[9]=f-m,i[10]=1-(h+p),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler(e,t,i=c.vec4()){const s=c.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],A=e[9],h=e[2],u=e[6],d=e[10];return"XYZ"===t?(i[1]=Math.asin(s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(-A,d),i[2]=Math.atan2(-o,r)):(i[0]=Math.atan2(u,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(A,-1,1)),Math.abs(A)<.99999?(i[1]=Math.atan2(n,d),i[2]=Math.atan2(a,l)):(i[1]=Math.atan2(-h,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(u,-1,1)),Math.abs(u)<.99999?(i[1]=Math.atan2(-h,d),i[2]=Math.atan2(-o,l)):(i[1]=0,i[2]=Math.atan2(a,r))):"ZYX"===t?(i[1]=Math.asin(-s(h,-1,1)),Math.abs(h)<.99999?(i[0]=Math.atan2(u,d),i[2]=Math.atan2(a,r)):(i[0]=0,i[2]=Math.atan2(-o,l))):"YZX"===t?(i[2]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-A,l),i[1]=Math.atan2(-h,r)):(i[0]=0,i[1]=Math.atan2(n,d))):"XZY"===t&&(i[2]=Math.asin(-s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(u,l),i[1]=Math.atan2(n,r)):(i[0]=Math.atan2(-A,d),i[1]=0)),i},composeMat4:(e,t,i,s=c.mat4())=>(c.quaternionToRotationMat4(t,s),c.scaleMat4v(i,s),c.translateMat4v(e,s),s),decomposeMat4:(()=>{const e=new n(3),t=new n(16);return function(i,s,r,o){e[0]=i[0],e[1]=i[1],e[2]=i[2];let n=c.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];const a=c.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];const l=c.lenVec3(e);c.determinantMat4(i)<0&&(n=-n),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);const A=1/n,h=1/a,u=1/l;return t[0]*=A,t[1]*=A,t[2]*=A,t[4]*=h,t[5]*=h,t[6]*=h,t[8]*=u,t[9]*=u,t[10]*=u,c.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v(e,t,i,s){s||(s=c.mat4());const r=e[0],o=e[1],n=e[2],a=i[0],l=i[1],A=i[2],h=t[0],u=t[1],d=t[2];if(r===h&&o===u&&n===d)return c.identityMat4();let p,f,g,m,_,v,b,y,x,B;return p=r-h,f=o-u,g=n-d,B=1/Math.sqrt(p*p+f*f+g*g),p*=B,f*=B,g*=B,m=l*g-A*f,_=A*p-a*g,v=a*f-l*p,B=Math.sqrt(m*m+_*_+v*v),B?(B=1/B,m*=B,_*=B,v*=B):(m=0,_=0,v=0),b=f*v-g*_,y=g*m-p*v,x=p*_-f*m,B=Math.sqrt(b*b+y*y+x*x),B?(B=1/B,b*=B,y*=B,x*=B):(b=0,y=0,x=0),s[0]=m,s[1]=b,s[2]=p,s[3]=0,s[4]=_,s[5]=y,s[6]=f,s[7]=0,s[8]=v,s[9]=x,s[10]=g,s[11]=0,s[12]=-(m*r+_*o+v*n),s[13]=-(b*r+y*o+x*n),s[14]=-(p*r+f*o+g*n),s[15]=1,s},lookAtMat4c:(e,t,i,s,r,o,n,a,l)=>c.lookAtMat4v([e,t,i],[s,r,o],[n,a,l],[]),orthoMat4c(e,t,i,s,r,o,n){n||(n=c.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2/l,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=-2/A,n[11]=0,n[12]=-(e+t)/a,n[13]=-(s+i)/l,n[14]=-(o+r)/A,n[15]=1,n},frustumMat4v(e,t,i){i||(i=c.mat4());const s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];c.addVec4(r,s,l),c.subVec4(r,s,A);const o=2*s[2],n=A[0],a=A[1],h=A[2];return i[0]=o/n,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=o/a,i[6]=0,i[7]=0,i[8]=l[0]/n,i[9]=l[1]/a,i[10]=-l[2]/h,i[11]=-1,i[12]=0,i[13]=0,i[14]=-o*r[2]/h,i[15]=0,i},frustumMat4(e,t,i,s,r,o,n){n||(n=c.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2*r/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2*r/l,n[6]=0,n[7]=0,n[8]=(t+e)/a,n[9]=(s+i)/l,n[10]=-(o+r)/A,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/A,n[15]=0,n},perspectiveMat4(e,t,i,s,r){const o=[],n=[];return o[2]=i,n[2]=s,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],c.frustumMat4v(o,n,r)},compareMat4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15],transformPoint3(e,t,i=c.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=c.vec4())=>(i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i),transformPoints3(e,t,i){const s=i||[],r=t.length;let o,n,a,l;const A=e[0],h=e[1],c=e[2],u=e[3],d=e[4],p=e[5],f=e[6],g=e[7],m=e[8],_=e[9],v=e[10],b=e[11],y=e[12],x=e[13],B=e[14],w=e[15];let P;for(let e=0;e{const e=new n(16),t=new n(16),i=new n(16);return function(s,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),i),s,n)}})(),lerpVec3(e,t,i,s,r,o){const n=o||c.vec3(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n},lerpMat4(e,t,i,s,r,o){const n=o||c.mat4(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n[3]=s[3]+a*(r[3]-s[3]),n[4]=s[4]+a*(r[4]-s[4]),n[5]=s[5]+a*(r[5]-s[5]),n[6]=s[6]+a*(r[6]-s[6]),n[7]=s[7]+a*(r[7]-s[7]),n[8]=s[8]+a*(r[8]-s[8]),n[9]=s[9]+a*(r[9]-s[9]),n[10]=s[10]+a*(r[10]-s[10]),n[11]=s[11]+a*(r[11]-s[11]),n[12]=s[12]+a*(r[12]-s[12]),n[13]=s[13]+a*(r[13]-s[13]),n[14]=s[14]+a*(r[14]-s[14]),n[15]=s[15]+a*(r[15]-s[15]),n},flatten(e){const t=[];let i,s,r,o,n;for(i=0,s=e.length;i(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,i=c.vec4()){const s=e[0]*c.DEGTORAD/2,r=e[1]*c.DEGTORAD/2,o=e[2]*c.DEGTORAD/2,n=Math.cos(s),a=Math.cos(r),l=Math.cos(o),A=Math.sin(s),h=Math.sin(r),u=Math.sin(o);return"XYZ"===t?(i[0]=A*a*l+n*h*u,i[1]=n*h*l-A*a*u,i[2]=n*a*u+A*h*l,i[3]=n*a*l-A*h*u):"YXZ"===t?(i[0]=A*a*l+n*h*u,i[1]=n*h*l-A*a*u,i[2]=n*a*u-A*h*l,i[3]=n*a*l+A*h*u):"ZXY"===t?(i[0]=A*a*l-n*h*u,i[1]=n*h*l+A*a*u,i[2]=n*a*u+A*h*l,i[3]=n*a*l-A*h*u):"ZYX"===t?(i[0]=A*a*l-n*h*u,i[1]=n*h*l+A*a*u,i[2]=n*a*u-A*h*l,i[3]=n*a*l+A*h*u):"YZX"===t?(i[0]=A*a*l+n*h*u,i[1]=n*h*l+A*a*u,i[2]=n*a*u-A*h*l,i[3]=n*a*l-A*h*u):"XZY"===t&&(i[0]=A*a*l-n*h*u,i[1]=n*h*l-A*a*u,i[2]=n*a*u+A*h*l,i[3]=n*a*l+A*h*u),i},mat4ToQuaternion(e,t=c.vec4()){const i=e[0],s=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],A=e[6],h=e[10];let u;const d=i+n+h;return d>0?(u=.5/Math.sqrt(d+1),t[3]=.25/u,t[0]=(A-a)*u,t[1]=(r-l)*u,t[2]=(o-s)*u):i>n&&i>h?(u=2*Math.sqrt(1+i-n-h),t[3]=(A-a)/u,t[0]=.25*u,t[1]=(s+o)/u,t[2]=(r+l)/u):n>h?(u=2*Math.sqrt(1+n-i-h),t[3]=(r-l)/u,t[0]=(s+o)/u,t[1]=.25*u,t[2]=(a+A)/u):(u=2*Math.sqrt(1+h-i-n),t[3]=(o-s)/u,t[0]=(r+l)/u,t[1]=(a+A)/u,t[2]=.25*u),t},vec3PairToQuaternion(e,t,i=c.vec4()){const s=Math.sqrt(c.dotVec3(e,e)*c.dotVec3(t,t));let r=s+c.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])):c.cross3Vec3(e,t,i),i[3]=r,c.normalizeQuaternion(i)},angleAxisToQuaternion(e,t=c.vec4()){const i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:(()=>{const e=new n(16);return(t,i,s)=>(s=s||c.vec3(),c.quaternionToRotationMat4(t,e),c.mat4ToEuler(e,i,s),s)})(),mulQuaternions(e,t,i=c.vec4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],A=t[2],h=t[3];return i[0]=n*a+s*h+r*A-o*l,i[1]=n*l+r*h+o*a-s*A,i[2]=n*A+o*h+s*l-r*a,i[3]=n*h-s*a-r*l-o*A,i},vec3ApplyQuaternion(e,t,i=c.vec3()){const s=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],A=e[3],h=A*s+a*o-l*r,u=A*r+l*s-n*o,d=A*o+n*r-a*s,p=-n*s-a*r-l*o;return i[0]=h*A+p*-n+u*-l-d*-a,i[1]=u*A+p*-a+d*-n-h*-l,i[2]=d*A+p*-l+h*-a-u*-n,i},quaternionToMat4(e,t){t=c.identityMat4(t);const i=e[0],s=e[1],r=e[2],o=e[3],n=2*i,a=2*s,l=2*r,A=n*o,h=a*o,u=l*o,d=n*i,p=a*i,f=l*i,g=a*s,m=l*s,_=l*r;return t[0]=1-(g+_),t[1]=p+u,t[2]=f-h,t[4]=p-u,t[5]=1-(d+_),t[6]=m+A,t[8]=f+h,t[9]=m-A,t[10]=1-(d+g),t},quaternionToRotationMat4(e,t){const i=e[0],s=e[1],r=e[2],o=e[3],n=i+i,a=s+s,l=r+r,A=i*n,h=i*a,c=i*l,u=s*a,d=s*l,p=r*l,f=o*n,g=o*a,m=o*l;return t[0]=1-(u+p),t[4]=h-m,t[8]=c+g,t[1]=h+m,t[5]=1-(A+p),t[9]=d-f,t[2]=c-g,t[6]=d+f,t[10]=1-(A+u),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const i=c.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)=>c.normalizeQuaternion(c.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=c.vec4()){const i=(e=c.normalizeQuaternion(e,h))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:e=>new n(e||6),AABB2:e=>new n(e||4),OBB3:e=>new n(e||32),OBB2:e=>new n(e||16),Sphere3:(e,t,i,s)=>new n([e,t,i,s]),transformOBB3(e,t,i=t){let s;const r=t.length;let o,n,a;const l=e[0],A=e[1],h=e[2],c=e[3],u=e[4],d=e[5],p=e[6],f=e[7],g=e[8],m=e[9],_=e[10],v=e[11],b=e[12],y=e[13],x=e[14],B=e[15];for(s=0;s{const e=new n(3),t=new n(3),i=new n(3);return s=>(e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5],c.subVec3(t,e,i),Math.abs(c.lenVec3(i)))})(),getAABB3DiagPoint:(()=>{const e=new n(3),t=new n(3),i=new n(3);return(s,r)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5];const o=c.subVec3(t,e,i),n=r[0]-s[0],a=s[3]-r[0],l=r[1]-s[1],A=s[4]-r[1],h=r[2]-s[2],u=s[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>A?l:A,o[2]+=h>u?h:u,Math.abs(c.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const i=t||c.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||c.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:(e=c.AABB3())=>(e[0]=c.MAX_DOUBLE,e[1]=c.MAX_DOUBLE,e[2]=c.MAX_DOUBLE,e[3]=c.MIN_DOUBLE,e[4]=c.MIN_DOUBLE,e[5]=c.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=c.OBB3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t),positions3ToAABB3:(()=>{const e=new n(3);return(t,i,s)=>{i=i||c.AABB3();let r,o,n,a=c.MAX_DOUBLE,l=c.MAX_DOUBLE,A=c.MAX_DOUBLE,h=c.MIN_DOUBLE,u=c.MIN_DOUBLE,d=c.MIN_DOUBLE;for(let i=0,p=t.length;ih&&(h=r),o>u&&(u=o),n>d&&(d=n);return i[0]=a,i[1]=l,i[2]=A,i[3]=h,i[4]=u,i[5]=d,i}})(),OBB3ToAABB3(e,t=c.AABB3()){let i,s,r,o=c.MAX_DOUBLE,n=c.MAX_DOUBLE,a=c.MAX_DOUBLE,l=c.MIN_DOUBLE,A=c.MIN_DOUBLE,h=c.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToAABB3(e,t=c.AABB3()){let i,s,r,o=c.MAX_DOUBLE,n=c.MAX_DOUBLE,a=c.MAX_DOUBLE,l=c.MIN_DOUBLE,A=c.MIN_DOUBLE,h=c.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToSphere3:(()=>{const e=new n(3);return(t,i)=>{i=i||c.vec4();let s,r=0,o=0,n=0;const a=t.length;for(s=0;sA&&(A=l);return i[3]=A,i}})(),positions3ToSphere3:(()=>{const e=new n(3),t=new n(3);return(i,s)=>{s=s||c.vec4();let r,o=0,n=0,a=0;const l=i.length;let A=0;for(r=0;rA&&(A=u);return s[3]=A,s}})(),OBB3ToSphere3:(()=>{const e=new n(3),t=new n(3);return(i,s)=>{s=s||c.vec4();let r,o=0,n=0,a=0;const l=i.length,A=l/4;for(r=0;ru&&(u=h);return s[3]=u,s}})(),getSphere3Center:(e,t=c.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=c.vec3()){let i=0,s=0,r=0;for(var o=0,n=e.length;o(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3](e[0]=c.MAX_DOUBLE,e[1]=c.MAX_DOUBLE,e[2]=c.MIN_DOUBLE,e[3]=c.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]e[0]<=t[0]&&e[3]>=t[0]&&e[1]<=t[1]&&e[4]>=t[1]&&e[2]<=t[2]&&e[5]>=t[2],planeAABB3Intersect(e,t,i){let s,r;e[0]>0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]);if(s<=-t&&r<=-t)return-1;return s>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=c.AABB2()){let i,s,r,o,n=c.MAX_DOUBLE,a=c.MAX_DOUBLE,l=c.MIN_DOUBLE,A=c.MIN_DOUBLE;for(let t=0,h=e.length;tl&&(l=i),s>A&&(A=s);return t[0]=n,t[1]=a,t[2]=l,t[3]=A,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]2*(1-e)*(i-t)+2*e*(s-i),tangentQuadraticBezier3:(e,t,i,s,r)=>-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r,tangentSpline:e=>6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e),catmullRomInterpolate(e,t,i,s,r){const o=.5*(i-e),n=.5*(s-t),a=r*r;return(2*t-2*i+o+n)*(r*a)+(-3*t+3*i-2*o-n)*a+o*r+t},b2p0(e,t){const i=1-e;return i*i*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0(e,t){const i=1-e;return i*i*i*t},b3p1(e,t){const i=1-e;return 3*i*i*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal(e,t,i,s=c.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=i[0]-e[0],l=i[1]-e[1],A=i[2]-e[2],h=o*A-n*l,u=n*a-r*A,d=r*l-o*a,p=Math.sqrt(h*h+u*u+d*d);return 0===p?(s[0]=0,s[1]=0,s[2]=0):(s[0]=h/p,s[1]=u/p,s[2]=d/p),s},rayTriangleIntersect:(()=>{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3);return(o,n,a,l,A,h)=>{h=h||c.vec3();const u=c.subVec3(l,a,e),d=c.subVec3(A,a,t),p=c.cross3Vec3(n,d,i),f=c.dotVec3(u,p);if(f<1e-6)return null;const g=c.subVec3(o,a,s),m=c.dotVec3(g,p);if(m<0||m>f)return null;const _=c.cross3Vec3(g,u,r),v=c.dotVec3(n,_);if(v<0||m+v>f)return null;const b=c.dotVec3(d,_)/f;return h[0]=o[0]+b*n[0],h[1]=o[1]+b*n[1],h[2]=o[2]+b*n[2],h}})(),rayPlaneIntersect:(()=>{const e=new n(3),t=new n(3),i=new n(3),s=new n(3);return(r,o,n,a,l,A)=>{A=A||c.vec3(),o=c.normalizeVec3(o,e);const h=c.subVec3(a,n,t),u=c.subVec3(l,n,i),d=c.cross3Vec3(h,u,s);c.normalizeVec3(d,d);const p=-c.dotVec3(n,d),f=-(c.dotVec3(r,d)+p)/c.dotVec3(o,d);return A[0]=r[0]+f*o[0],A[1]=r[1]+f*o[1],A[2]=r[2]+f*o[2],A}})(),cartesianToBarycentric:(()=>{const e=new n(3),t=new n(3),i=new n(3);return(s,r,o,n,a)=>{const l=c.subVec3(n,r,e),A=c.subVec3(o,r,t),h=c.subVec3(s,r,i),u=c.dotVec3(l,l),d=c.dotVec3(l,A),p=c.dotVec3(l,h),f=c.dotVec3(A,A),g=c.dotVec3(A,h),m=u*f-d*d;if(0===m)return null;const _=1/m,v=(f*p-d*g)*_,b=(u*g-d*p)*_;return a[0]=1-v-b,a[1]=b,a[2]=v,a}})(),barycentricInsideTriangle(e){const t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian(e,t,i,s,r=c.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+i[0]*n+s[0]*a,r[1]=t[1]*o+i[1]*n+s[1]*a,r[2]=t[2]*o+i[2]*n+s[2]*a,r},mergeVertices(e,t,i,s){const r={},o=[],n=[],a=t?[]:null,l=i?[]:null,A=[];let h,c,u,d;const p=1e4;let f,g,m=0;for(f=0,g=e.length;f{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3),o=new n(3);return(n,a,l)=>{let A,h;const u=new Array(n.length/3);let d,p,f,g,m,_,v;for(A=0,h=a.length;A{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3),o=new n(3),a=new n(3);return(n,l,A)=>{const h=new Float32Array(n.length);for(let u=0;u>24&255,h=u>>16&255,A=u>>8&255,l=255&u,a=t[i],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+1],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+2],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,i={}){const s=i.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,A,h,u;const d=1e4;let p,f,g,m,_,v;for(f=0,m=e.length;f{const e=new n(4),t=new n(4);return(i,s,r,o,n)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=1,c.transformVec4(i,e,t),o[0]=t[0],o[1]=t[1],o[2]=t[2],e[0]=r[0],e[1]=r[1],e[2]=r[2],c.transformVec3(i,e,t),c.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new n(16),t=new n(4),i=new n(4),s=(t,i,s,r,o)=>{o[0]=t,o[1]=i,o[2]=s,o[3]=1,c.transformVec4(e,o,o),r||c.mulVec4Scalar(o,1/o[3])};return(r,o,n,a,l,A,h)=>{const u="ortho"===a;c.mulMat4(n,o,e),c.inverseMat4(e,e);const d=2*l[0]/r.width-1,p=1-2*l[1]/r.height;s(d,p,-1,u,t),s(d,p,1,u,i),A[0]=t[0],A[1]=t[1],A[2]=t[2],c.subVec3(i,t,h),c.normalizeVec3(h)}})(),canvasPosToLocalRay:(()=>{const e=new n(3),t=new n(3);return(i,s,r,o,n,a,l,A)=>{c.canvasPosToWorldRay(i,s,r,o,a,e,t),c.worldRayToLocalRay(n,e,t,l,A)}})(),worldRayToLocalRay:(()=>{const e=new n(16),t=new n(4),i=new n(4);return(s,r,o,n,a)=>{const l=c.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,c.transformVec4(l,t,i),n[0]=i[0],n[1]=i[1],n[2]=i[2],c.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(i,s,r,o){const a=new n(6),l={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:a};let A,h;for(a[0]=a[1]=a[2]=Number.POSITIVE_INFINITY,a[3]=a[4]=a[5]=Number.NEGATIVE_INFINITY,A=0,h=i.length;Aa[3]&&(a[3]=r[t]),r[t+1]a[4]&&(a[4]=r[t+1]),r[t+2]a[5]&&(a[5]=r[t+2])}}if(i.length<20||o>10)return l.triangles=i,l.leaf=!0,l;e[0]=a[3]-a[0],e[1]=a[4]-a[1],e[2]=a[5]-a[2];let u=0;e[1]>e[u]&&(u=1),e[2]>e[u]&&(u=2),l.splitDim=u;const d=(a[u]+a[u+3])/2,p=new Array(i.length);let f=0;const g=new Array(i.length);let m=0;for(A=0,h=i.length;A{const s=e.length/3,r=new Array(s);for(let e=0;e=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=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t}};c.buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=c.vec3(),h=c.vec3(),u=c.vec3(),d=c.vec3(),p=c.vec3(),f=c.vec3(),g=c.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;ux)||(T=i[F.index1],R=i[F.index2],(!L&&T>65535||R>65535)&&(L=!0),y.push(T),y.push(R));return L?new Uint32Array(y):new Uint16Array(y)}}(),c.planeClipsPositions3=function(e,t,i,s=3){for(let r=0,o=i.length;r=this._headLength){const e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}const e=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,e}push(e){return this._length++,this._tail.push(e),this}unshift(e){return this._head[--this._index]=e,this._length++,this}}const p={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var f=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r{};t=t||s,i=i||s;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var s=e.target.response;if(200===this.status){var r;try{r=JSON.parse(s)}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}t(r)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(s))}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else i(e)}),!1),r.addEventListener("error",(function(e){i(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,i){var s=e=>{};t=t||s,i=i||s;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const e=!!r[2];var o=r[3];o=window.decodeURIComponent(o),e&&(o=window.atob(o));try{const e=new ArrayBuffer(o.length),i=new Uint8Array(e);for(var n=0;n{t(e)}))}catch(e){M.scheduleTask((()=>{i(e)}))}}else{const s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i("loadArrayBuffer error : "+s.response))},s.send(null)}},queryString:m,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"==typeof e&&"number"==typeof e.length},isString:function(e){return"string"==typeof e||e instanceof String},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},isID:function(e){return _.isString(e)||_.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(_.isNumeric(e)||_.isString(e)?`${e}`:e.id)===(_.isNumeric(t)||_.isString(t)?`${t}`:t.id)},isFunction:function(e){return"function"==typeof e},isObject:function(e){const t={}.constructor;return!!e&&e.constructor===t},copy:function(e){return _.apply(e,{})},apply:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t},apply2:function(e,t){for(const i in e)e.hasOwnProperty(i)&&void 0!==e[i]&&null!==e[i]&&(t[i]=e[i]);return t},applyIf:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(void 0!==t[i]&&null!==t[i]||(t[i]=e[i]));return t},isEmptyObject:function(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return _.isNumeric(e)?`${e}`:`'${e}'`},concat:function(e,t){const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},flattenParentChildHierarchy:function(e){var t=[];return function e(i){i.id=i.uuid,delete i.oid,t.push(i);var s=i.children;if(s)for(var r=0,o=s.length;r{b.removeItem(e.id),delete M.scenes[e.id],delete v[e.id],p.components.scenes--}))},this.clear=function(){let e;for(const t in M.scenes)M.scenes.hasOwnProperty(t)&&(e=M.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete M.scenes[e.id]))},this.scheduleTask=function(e,t=null){y.push(e),y.push(t)},this.runTasks=function(e=-1){let t,i,s=(new Date).getTime(),r=0;for(;y.length>0&&(e<0||s0&&w>0){var t=1e3/w;C+=t,B.push(t),B.length>=30&&(C-=B.shift()),p.frame.fps=Math.round(C/B.length)}for(let e in M.scenes)M.scenes[e].compile();I(e),P=e};!function(e,t){let i=Date.now()+t;(function s(){const r=Date.now()-i;e(),i+=t,setTimeout(s,Math.max(0,t-r))})()}((()=>{E()}),100);const F=function(){let e=Date.now();if(w=e-P,P>0&&w>0){var t=1e3/w;C+=t,B.push(t),B.length>=30&&(C-=B.shift()),p.frame.fps=Math.round(C/B.length)}I(e),function(e){for(var t in x.time=e,M.scenes)if(M.scenes.hasOwnProperty(t)){var i=M.scenes[t];x.sceneId=t,x.startTime=i.startTime,x.deltaTime=null!=x.prevTime?x.time-x.prevTime:0,i.fire("tick",x,!0)}x.prevTime=e}(e),function(){const e=M.scenes,t=!1;let i,s,r,o,n;for(n in e)e.hasOwnProperty(n)&&(i=e[n],s=v[n],s||(s=v[n]={}),r=i.ticksPerOcclusionTest,s.ticksPerOcclusionTest!==r&&(s.ticksPerOcclusionTest=r,s.renderCountdown=r),--i.occlusionTestCountdown<=0&&(i.doOcclusionTest(),i.occlusionTestCountdown=r),o=i.ticksPerRender,s.ticksPerRender!==o&&(s.ticksPerRender=o,s.renderCountdown=o),0==--s.renderCountdown&&(i.render(t),s.renderCountdown=o))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(E):requestAnimationFrame(F)};function I(e){const t=M.runTasks(e+10),i=M.getNumTasks();p.frame.tasksRun=t,p.frame.tasksScheduled=i,p.frame.tasksBudget=10}F();class D{get type(){return"Component"}get isComponent(){return!0}constructor(e=null,t={}){if(this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=t.viewer;else{if("Scene"===e.type)this.scene=e;else{if(!(e instanceof D))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+_.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let i=e.component;const s=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(i&&(_.isNumeric(i)||_.isString(i))){const e=i;if(i=this.scene.components[e],!i)return void this.error("Component not found: "+_.inQuotes(e))}if(!i)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){i=e[t];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&(i=this.scene[t],!i))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+_.inQuotes(i.id));if(o&&!i.isType(o))return void this.error("Expected a "+o+" type or subtype: "+i.type+" "+_.inQuotes(i.id))}this._attachments||(this._attachments={});const l=this._attached[t];let A,h,c;if(l){if(i&&l.id===i.id)return;const e=this._attachments[l.id];for(A=e.subs,h=0,c=A.length;h{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():M.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}scheduleTask(e){M.scheduleTask(e,null)}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,i,s,r,o;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(t=this._attachments[e],i=t.component,s=t.subs,r=0,o=s.length;r=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class U{constructor(){this.planes=[new L,new L,new L,new L,new L,new L]}}function k(e,t,i){const s=c.mulMat4(i,t,R),r=s[0],o=s[1],n=s[2],a=s[3],l=s[4],A=s[5],h=s[6],u=s[7],d=s[8],p=s[9],f=s[10],g=s[11],m=s[12],_=s[13],v=s[14],b=s[15];e.planes[0].set(a-r,u-l,g-d,b-m),e.planes[1].set(a+r,u+l,g+d,b+m),e.planes[2].set(a-o,u-A,g-p,b-_),e.planes[3].set(a+o,u+A,g+p,b+_),e.planes[4].set(a-n,u-h,g-f,b-v),e.planes[5].set(a+n,u+h,g+f,b+v)}function O(e,t){let i=U.INSIDE;const s=S,r=T;s[0]=t[0],s[1]=t[1],s[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[s,r];for(let t=0;t<6;++t){const s=e.planes[t];if(s.normal[0]*o[s.testVertex[0]][0]+s.normal[1]*o[s.testVertex[1]][1]+s.normal[2]*o[s.testVertex[2]][2]+s.offset<0)return U.OUTSIDE;s.normal[0]*o[1-s.testVertex[0]][0]+s.normal[1]*o[1-s.testVertex[1]][1]+s.normal[2]*o[1-s.testVertex[2]][2]+s.offset<0&&(i=U.INTERSECT)}return i}U.INSIDE=0,U.INTERSECT=1,U.OUTSIDE=2;class N extends D{constructor(e={}){if(!e.viewer)throw"[MarqueePicker] Missing config: viewer";if(!e.objectsKdTree3)throw"[MarqueePicker] Missing config: objectsKdTree3";super(e.viewer.scene,e),this.viewer=e.viewer,this._objectsKdTree3=e.objectsKdTree3,this._canvasMarqueeCorner1=c.vec2(),this._canvasMarqueeCorner2=c.vec2(),this._canvasMarquee=c.AABB2(),this._marqueeFrustum=new U,this._marqueeFrustumProjMat=c.mat4(),this._pickMode=!1,this._marqueeElement=document.createElement("div"),document.body.appendChild(this._marqueeElement),this._marqueeElement.style.position="absolute",this._marqueeElement.style["z-index"]="40000005",this._marqueeElement.style.width="8px",this._marqueeElement.style.height="8px",this._marqueeElement.style.visibility="hidden",this._marqueeElement.style.top="0px",this._marqueeElement.style.left="0px",this._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",this._marqueeElement.style.opacity=1,this._marqueeElement.style["pointer-events"]="none"}setMarqueeCorner1(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarqueeCorner2(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarquee(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}setMarqueeVisible(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}getMarqueeVisible(){return this._marqueVisible}setPickMode(e){if(e!==N.PICK_MODE_INSIDE&&e!==N.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===N.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}getPickMode(){return this._pickMode}clear(){this.fire("clear",{})}pick(){this._updateMarquee(),this._buildMarqueeFrustum();const e=[],t=(i,s=U.INTERSECT)=>{if(s===U.INTERSECT&&(s=O(this._marqueeFrustum,i.aabb)),s!==U.OUTSIDE){if(i.entities){const t=i.entities;for(let i=0,s=t.length;i3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&t(this._objectsKdTree3.root),this.fire("picked",e),e}_updateMarquee(){this._canvasMarquee[0]=Math.min(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[1]=Math.min(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._canvasMarquee[2]=Math.max(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[3]=Math.max(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._marqueeElement.style.width=this._canvasMarquee[2]-this._canvasMarquee[0]+"px",this._marqueeElement.style.height=this._canvasMarquee[3]-this._canvasMarquee[1]+"px",this._marqueeElement.style.left=`${this._canvasMarquee[0]}px`,this._marqueeElement.style.top=`${this._canvasMarquee[1]}px`}_buildMarqueeFrustum(){const e=this.viewer.scene.canvas.canvas,t=e.clientWidth,i=e.clientHeight,s=e.clientLeft,r=e.clientTop,o=2/t,n=2/i,a=e.clientHeight/e.clientWidth,l=(this._canvasMarquee[0]-s)*o-1,A=(this._canvasMarquee[2]-s)*o-1,h=-(this._canvasMarquee[3]-r)*n+1,u=-(this._canvasMarquee[1]-r)*n+1,d=this.viewer.scene.camera.frustum.near*(17*a);c.frustumMat4(l,A,h*a,u*a,d,1e4,this._marqueeFrustumProjMat),k(this._marqueeFrustum,this.viewer.scene.camera.viewMatrix,this._marqueeFrustumProjMat)}destroy(){super.destroy(),this._marqueeElement.parentElement&&(this._marqueeElement.parentElement.removeChild(this._marqueeElement),this._marqueeElement=null,this._objectsKdTree3=null)}}N.PICK_MODE_INTERSECTS=0,N.PICK_MODE_INSIDE=1;class Q{constructor(e,t={}){this.viewer=e,this.scene=this.viewer.scene,this._circleDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._circleDiv,this.viewer.scene.canvas.canvas),this._circleDiv.style.backgroundColor="transparent",this._circleDiv.style.border="2px solid green",this._circleDiv.style.borderRadius="50px",this._circleDiv.style.width="50px",this._circleDiv.style.height="50px",this._circleDiv.style.margin="-200px -200px",this._circleDiv.style.zIndex="100000",this._circleDiv.style.position="absolute",this._circleDiv.style.pointerEvents="none",this._circlePos=null,this._circleMaxRadius=200,this._circleMinRadius=2,this._active=!1!==t.active,this._visible=!1,this._running=!1,this._destroyed=!1}start(e){if(this._destroyed)return;this._circlePos=e,this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius=`${this._circleRadius}px`,this._circleDiv.style.marginLeft=this._circlePos[0]-this._circleRadius+"px",this._circleDiv.style.marginTop=this._circlePos[1]-this._circleRadius+"px";const t=this._circleMaxRadius;let i;const s=e=>{if(!this._running)return;i||(i=e);const r=e-i,o=Math.min(r/300,1),n=t+(2-t)*o;this._circleRadius=n,this._circleDiv.style.width=`${this._circleRadius}px`,this._circleDiv.style.height=`${this._circleRadius}px`,this._circleDiv.style.marginLeft=this._circlePos[0]-this._circleRadius/2+"px",this._circleDiv.style.marginTop=this._circlePos[1]-this._circleRadius/2+"px",o<1&&requestAnimationFrame(s)};this._running=!0,requestAnimationFrame(s),this._circleDiv.style.visibility="visible"}stop(){this._destroyed||(this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius=`${this._circleRadius}px`,this._circleDiv.style.visibility="hidden")}set durationMs(e){this.stop(),this._durationMs=e}get durationMs(){return this._durationMs}destroy(){this._destroyed||(this.stop(),this._circleDiv.parentElement.removeChild(this._circleDiv),this._destroyed=!0)}}class V{constructor(e,t,i){this.id=i&&i.id?i.id:e,this.viewer=t,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,t.addPlugin(this)}scheduleTask(e){M.scheduleTask(e,null)}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}const H={isIphoneSafari(){const e=window.navigator.userAgent,t=/iPhone/i.test(e),i=/Safari/i.test(e)&&!/Chrome/i.test(e);return t&&i}};class j{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!1!==t.visible,this._culled=!1;var i=this._dot,s=i.style;s["border-radius"]="25px",s.border="solid 2px white",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,s.width="8px",s.height="8px",s.visibility=this._visible?"visible":"hidden",s.top="0px",s.left="0px",s["box-shadow"]="0 2px 5px 0 #182A3D;",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._dotClickable,o=r.style;o["border-radius"]="35px",o.border="solid 10px white",o.position="absolute",o["z-index"]=void 0===t.zIndex?"40000007":t.zIndex+1,o.width="8px",o.height="8px",o.visibility="visible",o.top="0px",o.left="0px",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),r.addEventListener("click",(t=>{e.dispatchEvent(new MouseEvent("mouseover",t))})),t.onMouseOver&&r.addEventListener("mouseover",(i=>{t.onMouseOver(i,this),e.dispatchEvent(new MouseEvent("mouseover",i))})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onTouchstart&&r.addEventListener("touchstart",(e=>{t.onTouchstart(e,this)})),t.onTouchmove&&r.addEventListener("touchmove",(e=>{t.onTouchmove(e,this)})),t.onTouchend&&r.addEventListener("touchend",(e=>{t.onTouchend(e,this)})),t.onContextMenu&&(H.isIphoneSafari()?(r.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),r.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):r.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")}))),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.borderColor)}setPos(e,t){this._x=e,this._y=t;var i=this._dot.style;i.left=Math.round(e)-4+"px",i.top=Math.round(t)-4+"px";var s=this._dotClickable.style;s.left=Math.round(e)-9+"px",s.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}const G=c.vec3(),z=function(){const e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,o){return o=o||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,c.transformVec4(s,t,i),c.setMat4Translation(s,i,o),o.slice()}}();function W(e,t,i){const s=Float32Array.from([e[0]])[0],r=e[0]-s,o=Float32Array.from([e[1]])[0],n=e[1]-o,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=s,t[1]=o,t[2]=a,i[0]=r,i[1]=n,i[2]=l}function K(e,t,i,s=1e3){const r=c.getPositionsCenter(e,G),o=Math.round(r[0]/s)*s,n=Math.round(r[1]/s)*s,a=Math.round(r[2]/s)*s;i[0]=o,i[1]=n,i[2]=a;const l=0!==i[0]||0!==i[1]||0!==i[2];if(l)for(let i=0,s=e.length;i0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,i=this.meshes[0]._colorize[3];let s=255;if(t){if(e<0?e=0:e>1&&(e=1),s=Math.floor(255*e),i===s)return}else if(s=255,i===s)return;for(let e=0,t=this.meshes.length;e=0&&(e+=i)}return e>0?e:-1}_getFlag(e){return!!(this._flags&e)}_finalize(){const e=this.model.scene;this._isObject&&(this.visible&&e._objectVisibilityUpdated(this),this.highlighted&&e._objectHighlightedUpdated(this),this.xrayed&&e._objectXRayedUpdated(this),this.selected&&e._objectSelectedUpdated(this));for(let e=0,t=this.meshes.length;e{this._viewPosDirty=!0,this._needUpdate()})),this._onCameraProjMatrix=this.scene.camera.on("projMatrix",(()=>{this._canvasPosDirty=!0,this._needUpdate()})),this._onEntityDestroyed=null,this._onEntityModelDestroyed=null,this._renderer.addMarker(this),this.entity=t.entity,this.worldPos=t.worldPos,this.occludable=t.occludable}_update(){if(this._viewPosDirty&&(c.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){ae.set(this._viewPos),ae[3]=1,c.transformPoint4(this.scene.camera.projMatrix,ae,le);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+le[0]/le[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-le[1]/le[3])*e[3]/2),this._canvasPosDirty=!1,this.fire("canvasPos",this._canvasPos)}}_setVisible(e){this._visible,this._visible=e,this.fire("visible",this._visible)}set entity(e){if(this._entity){if(this._entity===e)return;null!==this._onEntityDestroyed&&(this._entity.model?this._entity.model.off(this._onEntityDestroyed):this._entity.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model&&this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null)}this._entity=e,this._entity&&(this._entity instanceof ne?this._onEntityModelDestroyed=this._entity.model.on("destroyed",(()=>{this._entity=null,this._onEntityModelDestroyed=null})):this._onEntityDestroyed=this._entity.on("destroyed",(()=>{this._entity=null,this._onEntityDestroyed=null}))),this.fire("entity",this._entity,!0)}get entity(){return this._entity}set occludable(e){(e=!!e)!==this._occludable&&(this._occludable=e,this._occludable&&this._renderer.markerWorldPosUpdated(this))}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),W(this._worldPos,this._origin,this._rtcPos),this._occludable&&this._renderer.markerWorldPosUpdated(this),this._viewPosDirty=!0,this.fire("worldPos",this._worldPos),this._needUpdate()}get worldPos(){return this._worldPos}get origin(){return this._origin}get rtcPos(){return this._rtcPos}get viewPos(){return this._update(),this._viewPos}get canvasPos(){return this._update(),this._canvasPos}get visible(){return!!this._visible}destroy(){this.fire("destroyed",!0),this.scene.camera.off(this._onCameraViewMatrix),this.scene.camera.off(this._onCameraProjMatrix),this._entity&&(null!==this._onEntityDestroyed&&this._entity.model.off(this._onEntityDestroyed),null!==this._onEntityModelDestroyed&&this._entity.model.off(this._onEntityModelDestroyed)),this._renderer.removeMarker(this),super.destroy()}}const he=()=>{};function ce(e,t,i){const s=e.getBoundingClientRect(),r=t.getBoundingClientRect();i[0]+=s.left-r.left,i[1]+=s.top-r.top}class ue extends Ae{constructor(e,t,i,s={}){super(e,t);const r=(e,t)=>i=>{e&&e(i),this.fire(t,i,!0)};this._dot=new j(i,{fillColor:s.fillColor,zIndex:s.zIndex,onMouseOver:r(s.onMouseOver,"mouseover"),onMouseLeave:r(s.onMouseLeave,"mouseleave"),onMouseWheel:r(s.onMouseWheel,"wheel"),onMouseDown:r(s.onMouseDown,"mousedown"),onMouseUp:r(s.onMouseUp,"mouseup"),onMouseMove:r(s.onMouseMove,"mousemove"),onTouchstart:r(s.onTouchstart,"touchstart"),onTouchmove:r(s.onTouchmove,"touchmove"),onTouchend:r(s.onTouchend,"touchend"),onContextMenu:r(s.onContextMenu,"contextmenu")});const o=()=>{const t=this.canvasPos.slice();ce(e.canvas.canvas,i,t),this._dot.setPos(t[0],t[1])};this.on("worldPos",o);const n=e.camera.on("viewMatrix",o),a=e.camera.on("projMatrix",o);this._cleanup=()=>{e.camera.off(n),e.camera.off(a),this._dot.destroy()}}setClickable(e){this._dot.setClickable(e)}setCulled(e){this._dot.setCulled(e)}setFillColor(e){this._dot.setFillColor(e)}setHighlighted(e){this._dot.setHighlighted(e)}setOpacity(e){this._dot.setOpacity(e)}setVisible(e){this._dot.setVisible(e)}destroy(){this._cleanup(),super.destroy()}}function de(e,t){const i=function(e,i){if(e in t)return t[e];if(void 0!==i)return i;throw"config missing: "+e},s=i("viewer"),r=i("ray2WorldPos"),o=i("handleMouseEvents",!1),n=i("handleTouchEvents",!1),a=i("onStart",he),l=i("onMove",he),A=i("onEnd",he),h=s.scene,u=h.canvas.canvas,d=e=>{const t=c.vec2([e.clientX,e.clientY]);ce(u.ownerDocument.documentElement,u,t),l(t,(e=>{const t=c.vec3(),i=c.vec3();return c.canvasPosToWorldRay(u,h.camera.viewMatrix,h.camera.projMatrix,h.camera.projection,e,t,i),r(t,i,e)})(t))};let p=null;const f=function(e){const t=p.matchesEvent(e);t&&d(t)},g=function(t){const i=p.matchesEvent(t);i&&(e.setOpacity(b),p.cleanup(),d(i),A())},m=function(t,i){p&&p.cleanup(),e.setOpacity(1),e.setClickable(!1),s.cameraControl.active=!1,p={matchesEvent:t,cleanup:function(){p=null,e.setClickable(!0),s.cameraControl.active=!0,i()}},a()},_=[],v=function(t,i){const s=e.on(t,i);_.push((()=>e.off(s)))};if(o&&(v("mouseover",(()=>!p&&e.setOpacity(1))),v("mouseleave",(()=>!p&&e.setOpacity(b))),v("mousedown",(e=>{1===e.which&&(u.addEventListener("mousemove",f),u.addEventListener("mouseup",g),m((e=>1===e.which&&e),(()=>{u.removeEventListener("mousemove",f),u.removeEventListener("mouseup",g)})))}))),n){let e;v("touchstart",(t=>{t.preventDefault(),1===t.touches.length&&(e=t.touches[0].identifier,m((t=>[...t.changedTouches].find((t=>t.identifier===e))),(()=>{e=null})))})),v("touchmove",(e=>{e.preventDefault(),f(e)})),v("touchend",(e=>{e.preventDefault(),g(e)}))}const b=.8;return e.setOpacity(b),function(){p&&p.cleanup(),_.forEach((e=>e())),e.setOpacity(1)}}function pe(e){const t=function(t,i){if(t in e)return e[t];if(void 0!==i)return i;throw"config missing: "+t},i=t("viewer"),s=t("handleMouseEvents",!1),r=t("handleTouchEvents",!1),o=t("pointerLens",null),n=t("dots"),a=t("ray2WorldPos"),l=t("onEnd",he),A=o?function(e){o.visible=!!e,e&&(o.canvasPos=e)}:()=>{},h=n.map((e=>{let t;return de(e,{handleMouseEvents:s,handleTouchEvents:r,viewer:i,ray2WorldPos:(e,i,s)=>a(e,i,s)||t,onStart:()=>{t=e.worldPos.slice(),c(!1,e)},onMove:(t,i)=>{A(t),e.worldPos=i},onEnd:()=>{l(t,e)||(e.worldPos=t),A(null),c(!0,e)}})})),c=(e,t)=>n.forEach((i=>i!==t&&i.setClickable(e)));return c(!0),function(){h.forEach((e=>e())),A(null)}}const fe=function(e,t,i){return function(s,r,o){const n=e.scene,a=n.canvas.canvas,l=(e,t)=>(t[0]=e.clientX,t[1]=e.clientY,ce(a.ownerDocument.documentElement,a,t),t),A=e=>{const t=c.vec3(),s=c.vec3();return c.canvasPosToWorldRay(a,n.camera.viewMatrix,n.camera.projMatrix,n.camera.projection,e,t,s),i(t,s)};let h=null;const u=()=>{};let d,p=u;const f=function(){t.stop(),clearTimeout(h),e.cameraControl.active=!0,p=u,d=null},g=function(){f(),a.removeEventListener("touchstart",m),a.removeEventListener("touchmove",_),a.removeEventListener("touchend",v)},m=function(i){const o=i.touches;if(1!==o.length)f(),s();else{const i=o[0],s=l(i,c.vec2());A(s)&&(d=i.identifier,p=e=>{c.distVec2(s,e)>20&&f()},h=setTimeout((function(){t.start(s),h=setTimeout((function(){t.stop(),e.cameraControl.active=!1,p=e=>{r(e,A(e))},p(s)}),300)}),250))}};a.addEventListener("touchstart",m,{passive:!0});const _=function(e){const t=[...e.changedTouches].find((e=>e.identifier===d));t&&p(l(t,c.vec2()))};a.addEventListener("touchmove",_,{passive:!0});const v=function(e){const t=[...e.changedTouches].find((e=>e.identifier===d));if(t){g();const e=l(t,c.vec2());o(e,A(e))}};return a.addEventListener("touchend",v,{passive:!0}),g}};class ge{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6,this._visible=!0,this._culled=!1;var i=this._wire,s=i.style;s.border="solid "+this._thickness+"px "+this._color,s.position="absolute",s["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,s.width="0px",s.height="0px",s.visibility="visible",s.top="0px",s.left="0px",s["-webkit-transform-origin"]="0 0",s["-moz-transform-origin"]="0 0",s["-ms-transform-origin"]="0 0",s["-o-transform-origin"]="0 0",s["transform-origin"]="0 0",s["-webkit-transform"]="rotate(0deg)",s["-moz-transform"]="rotate(0deg)",s["-ms-transform"]="rotate(0deg)",s["-o-transform"]="rotate(0deg)",s.transform="rotate(0deg)",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._wireClickable,o=r.style;o.border="solid "+this._thicknessClickable+"px "+this._color,o.position="absolute",o["z-index"]=void 0===t.zIndex?"2000002":t.zIndex+1,o.width="0px",o.height="0px",o.visibility="visible",o.top="0px",o.left="0px",o["-webkit-transform-origin"]="0 0",o["-moz-transform-origin"]="0 0",o["-ms-transform-origin"]="0 0",o["-o-transform-origin"]="0 0",o["transform-origin"]="0 0",o["-webkit-transform"]="rotate(0deg)",o["-moz-transform"]="rotate(0deg)",o["-ms-transform"]="rotate(0deg)",o["-o-transform"]="rotate(0deg)",o.transform="rotate(0deg)",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),t.onMouseOver&&r.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&(H.isIphoneSafari()?(r.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),r.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):r.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")}))),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}get visible(){return"visible"===this._wire.style.visibility}_update(){var e=Math.abs(Math.sqrt((this._x1-this._x2)*(this._x1-this._x2)+(this._y1-this._y2)*(this._y1-this._y2))),t=180*Math.atan2(this._y2-this._y1,this._x2-this._x1)/Math.PI,i=this._wire.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)";var s=this._wireClickable.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)"}setStartAndEnd(e,t,i,s){this._x1=e,this._y1=t,this._x2=i,this._y2=s,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class me{constructor(e,t={}){this._highlightClass="viewer-ruler-label-highlighted",this._prefix=t.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label",this._timeout=null;var i=this._label,s=i.style;s["border-radius"]="5px",s.color="white",s.padding="4px",s.border="solid 1px",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,s.width="auto",s.height="auto",s.visibility="visible",s.top="0px",s.left="0px",s["pointer-events"]="all",s.opacity=1,t.onContextMenu,i.innerText="",e.appendChild(i),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&i.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&i.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&i.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&i.addEventListener("mousedown",(e=>{t.onMouseDown(e,this),e.stopPropagation()})),t.onMouseUp&&i.addEventListener("mouseup",(e=>{t.onMouseUp(e,this),e.stopPropagation()})),t.onMouseMove&&i.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&(H.isIphoneSafari()?(i.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),i.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):i.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")})))}setPos(e,t){this._x=e,this._y=t;var i=this._label.style;i.left=Math.round(e)-20+"px",i.top=Math.round(t)-12+"px"}setPosOnWire(e,t,i,s){var r=e+.5*(i-e),o=t+.5*(s-t),n=this._label.style;n.left=Math.round(r)-20+"px",n.top=Math.round(o)-12+"px"}setPosBetweenWires(e,t,i,s,r,o){var n=(e+i+r)/3,a=(t+s+o)/3,l=this._label.style;l.left=Math.round(n)-20+"px",l.top=Math.round(a)-12+"px"}setText(e){this._label.innerHTML=this._prefix+(e||"")}setFillColor(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}setBorderColor(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}setOpacity(e){this._label.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}setClickable(e){this._label.style["pointer-events"]=e?"all":"none"}setPrefix(e){this._prefix!==e&&(this._prefix=e)}destroy(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}var _e=c.vec3(),ve=c.vec3();class be extends D{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._color=t.color||e.defaultColor;var i=this.plugin.viewer.scene;this._originWorld=c.vec3(),this._cornerWorld=c.vec3(),this._targetWorld=c.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},l=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))};this._originDot=new ue(i,t.origin,this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._cornerDot=new ue(i,t.corner,this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetDot=new ue(i,t.target,this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._originWire=new ge(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetWire=new ge(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._angleLabel=new me(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._cornerVisible=!1,this._targetVisible=!1,this._originWireVisible=!1,this._targetWireVisible=!1,this._angleVisible=!1,this._labelsVisible=!1,this._clickable=!1,this._originDot.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._cornerDot.on("worldPos",(e=>{this._cornerWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetDot.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(c.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){const d=-.3,p=this._originDot.viewPos[2],f=this._cornerDot.viewPos[2],g=this._targetDot.viewPos[2];if(p>d||f>d||g>d)return this._originDot.setVisible(!1),this._cornerDot.setVisible(!1),this._targetDot.setVisible(!1),this._originWire.setVisible(!1),this._targetWire.setVisible(!1),void this._angleLabel.setCulled(!0);c.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,i=this._cp,s=e.canvas.canvas.getBoundingClientRect();const m=this._container.getBoundingClientRect();for(var r=s.top-m.top,o=s.left-m.left,n=e.canvas.boundary,a=n[2],l=n[3],A=0,h=0,u=t.length;he.offsetTop+(e.offsetParent&&e.offsetParent!==t.parentNode&&h(e.offsetParent)),u=e=>e.offsetLeft+(e.offsetParent&&e.offsetParent!==t.parentNode&&u(e.offsetParent)),d=c.vec2(),p=e=>{e.snappedToVertex||e.snappedToEdge?(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.canvasPos,s.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red");const i=e.snappedCanvasPos||e.canvasPos;switch(r=!0,o=e.entity,l.set(e.worldPos),A.set(i),this._mouseState){case 0:this._canvasToPagePos?(this._canvasToPagePos(t,i,d),this.markerDiv.style.left=d[0]-5+"px",this.markerDiv.style.top=d[1]-5+"px"):(this.markerDiv.style.left=u(t)+i[0]-5+"px",this.markerDiv.style.top=h(t)+i[1]-5+"px");break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos,this._currentAngleMeasurement.corner.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos,this._currentAngleMeasurement.target.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer"}};this._onHoverSnapOrSurface=i.on("hoverSnapOrSurface",(e=>{this._snapping&&p(e)})),this._onHoverSurface=i.on("hoverSurface",(e=>{this._snapping||p(e)})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(n=e.clientX,a=e.clientY)}),t.addEventListener("mouseup",this._onMouseUp=e=>{if(1===e.which&&!(e.clientX>n+20||e.clientXa+20||e.clientY{if(r=!1,s&&(s.visible=!0,s.pointerPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!1),this.markerDiv.style.left="-100px",this.markerDiv.style.top="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}};this._onHoverSnapOrSurfaceOff=i.on("hoverSnapOrSurfaceOff",(e=>{this._snapping&&f(e)})),this._onHoverOff=i.on("hoverOff",(e=>{this._snapping||f(e)})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onHoverSnapOrSurface),t.off(this._onHoverSurface),t.off(this._onHoverSnapOrSurfaceOff),t.off(this._onHoverOff),this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}get currentMeasurement(){return this._currentAngleMeasurement}destroy(){this.deactivate(),super.destroy()}}class Be extends D{constructor(e,t,i,s){const r=e.plugin.viewer;super(r.scene);const o=pe({viewer:r,handleMouseEvents:i,handleTouchEvents:s,pointerLens:t.pointerLens,dots:[e.origin,e.corner,e.target],ray2WorldPos:(e,i,s)=>{const o=e=>{const t=r.scene.pick({canvasPos:s,snapToEdge:e,snapToVertex:e,pickSurface:!0});return t&&t.worldPos?t.worldPos:e&&o(!1)};return o(!!t.snapping)},onEnd:(e,t)=>{const i=!c.compareVec3(e,t.worldPos);return i&&this.fire("edited"),i}}),n=e.on("destroyed",o);this._deactivate=function(){e.off("destroyed",n),o()}}deactivate(){this._deactivate(),super.destroy()}}const we=c.vec3(),Pe=c.vec3(),Ce=c.vec3();class Me extends Ae{constructor(e,t){if(super(e,t),this.plugin=t.plugin,this._container=t.container,!this._container)throw"config missing: container";if(!t.markerElement&&!t.markerHTML)throw"config missing: need either markerElement or markerHTML";if(!t.labelElement&&!t.labelHTML)throw"config missing: need either labelElement or labelHTML";this._htmlDirty=!1,t.markerElement?(this._marker=t.markerElement,this._marker.addEventListener("click",this._onMouseClickedExternalMarker=()=>{this.plugin.fire("markerClicked",this)}),this._marker.addEventListener("contextmenu",this._onContextMenuExtenalMarker=()=>{this.plugin.fire("contextmenu",this)}),this._marker.addEventListener("mouseenter",this._onMouseEnterExternalMarker=()=>{this.plugin.fire("markerMouseEnter",this)}),this._marker.addEventListener("mouseleave",this._onMouseLeaveExternalMarker=()=>{this.plugin.fire("markerMouseLeave",this)}),this._markerExternal=!0):(this._markerHTML=t.markerHTML,this._htmlDirty=!0,this._markerExternal=!1),t.labelElement?(this._label=t.labelElement,this._labelExternal=!0):(this._labelHTML=t.labelHTML,this._htmlDirty=!0,this._labelExternal=!1),this._markerShown=!!t.markerShown,this._labelShown=!!t.labelShown,this._values=t.values||{},this._layoutDirty=!0,this._visibilityDirty=!0,this._labelPosition=24,this._buildHTML(),this._onTick=this.scene.on("tick",(()=>{this._htmlDirty&&(this._buildHTML(),this._htmlDirty=!1,this._layoutDirty=!0,this._visibilityDirty=!0),(this._layoutDirty||this._visibilityDirty)&&(this._markerShown||this._labelShown)&&(this._updatePosition(),this._layoutDirty=!1),this._visibilityDirty&&(this._marker.style.visibility=this.visible&&this._markerShown?"visible":"hidden",this._label.style.visibility=this.visible&&this._markerShown&&this._labelShown?"visible":"hidden",this._visibilityDirty=!1)})),this.on("canvasPos",(()=>{this._layoutDirty=!0})),this.on("visible",(()=>{this._visibilityDirty=!0})),this.setMarkerShown(!1!==t.markerShown),this.setLabelShown(t.labelShown),this.eye=t.eye?t.eye.slice():null,this.look=t.look?t.look.slice():null,this.up=t.up?t.up.slice():null,this.projection=t.projection}_buildHTML(){if(!this._markerExternal){this._marker&&(this._container.removeChild(this._marker),this._marker=null);let e=this._markerHTML||"

";_.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e.trim());const t=document.createRange().createContextualFragment(e);this._marker=t.firstChild,this._container.appendChild(this._marker),this._marker.style.visibility=this._markerShown?"visible":"hidden",this._marker.addEventListener("click",(()=>{this.plugin.fire("markerClicked",this)})),this._marker.addEventListener("contextmenu",(e=>{e.preventDefault(),this.plugin.fire("contextmenu",this)})),this._marker.addEventListener("mouseenter",(()=>{this.plugin.fire("markerMouseEnter",this)})),this._marker.addEventListener("mouseleave",(()=>{this.plugin.fire("markerMouseLeave",this)})),this._marker.addEventListener("wheel",(e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))}))}if(!this._labelExternal){this._label&&(this._container.removeChild(this._label),this._label=null);let e=this._labelHTML||"

";_.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e.trim());const t=document.createRange().createContextualFragment(e);this._label=t.firstChild,this._container.appendChild(this._label),this._label.style.visibility=this._markerShown&&this._labelShown?"visible":"hidden",this._label.addEventListener("wheel",(e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))}))}}_updatePosition(){const e=e=>e+"px",t=this.scene.canvas.boundary,i=t[0]+this.canvasPos[0],s=t[1]+this.canvasPos[1],r=this._marker.getBoundingClientRect().width,o=i+("right"===this._markerAlign?-1:"center"===this._markerAlign?0:1)*(r/2-12);this._marker.style.left=e(o-r/2),this._marker.style.top=e(s-12),this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;const n=this._label.getBoundingClientRect().width,a=Math.sign(this._labelPosition);this._label.style.left=e(o+a*(r/2+Math.abs(this._labelPosition)+n/2)-n/2),this._label.style.top=e(s-17),this._label.style["z-index"]=90005+Math.floor(this._viewPos[2])+1}_renderTemplate(e){for(var t in this._values)if(this._values.hasOwnProperty(t)){const i=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),i)}return e}setFromPickResult(e){if(e.worldPos&&e.worldNormal){const t=c.normalizeVec3(e.worldNormal,we),i=this.plugin&&this.plugin.surfaceOffset||0,s=c.mulVec3Scalar(t,i,Pe),r=c.addVec3(e.worldPos,s,Ce);this.entity=e.entity,this.worldPos=r}else this.error("Param 'pickResult' does not have both worldPos and worldNormal")}setMarkerAlign(e){const t=["left","center","right"];t.includes(e)?(this._markerAlign=e,this._updatePosition()):this.error("Param 'align' should be one of: "+JSON.stringify(t))}setLabelPosition(e){"number"!=typeof e?this.error("Param 'position' is not a number"):0===e?this.error("Param 'position' is zero"):(this._labelPosition=e,this._updatePosition())}setMarkerShown(e){e=!!e,this._markerShown!==e&&(this._markerShown=e,this._visibilityDirty=!0)}getMarkerShown(){return this._markerShown}setLabelShown(e){e=!!e,this._labelShown!==e&&(this._labelShown=e,this._visibilityDirty=!0)}getLabelShown(){return this._labelShown}setField(e,t){this._values[e]=t||"",this._htmlDirty=!0}getField(e){return this._values[e]}setValues(e){for(var t in e)if(e.hasOwnProperty(t)){const i=e[t];this.setField(t,i)}}getValues(){return this._values}destroy(){this._marker&&(this._markerExternal?(this._marker.removeEventListener("click",this._onMouseClickedExternalMarker),this._marker.removeEventListener("contextmenu",this._onContextMenuExtenalMarker),this._marker.removeEventListener("mouseenter",this._onMouseEnterExternalMarker),this._marker.removeEventListener("mouseleave",this._onMouseLeaveExternalMarker),this._marker=null):(this._marker.parentNode.removeChild(this._marker),this._marker=null)),this._label&&(this._labelExternal||this._label.parentNode.removeChild(this._label),this._label=null),this.scene.off(this._onTick),super.destroy()}}class Ee extends D{get type(){return"Spinner"}constructor(e,t={}){super(e,t),this._canvas=t.canvas,this._element=null,this._isCustom=!1,t.elementId&&(this._element=document.getElementById(t.elementId),this._element?this._adjustPosition():this.error("Can't find given Spinner HTML element: '"+t.elementId+"' - will automatically create default element")),this._element||this._createDefaultSpinner(),this.processes=0}_createDefaultSpinner(){this._injectDefaultCSS();const e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='
',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){const e="xeokit-spinner-css";if(document.getElementById(e))return;const t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}_adjustPosition(){if(this._isCustom)return;const e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const Fe=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class Ie extends D{constructor(e,t={}){super(e,t),this._backgroundColor=c.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const i=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),i.scene._webglContextLost(),i.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){i._initWebGL(),i.gl&&(i.scene._webglContextRestored(i.gl),i.fire("webglcontextrestored",i.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let s=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(s=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{s&&(s=!1,i.canvas.width=Math.round(i.canvas.clientWidth*i._resolutionScale),i.canvas.height=Math.round(i.canvas.clientHeight*i._resolutionScale),i.boundary[0]=i.canvas.offsetLeft,i.boundary[1]=i.canvas.offsetTop,i.boundary[2]=i.canvas.clientWidth,i.boundary[3]=i.canvas.clientHeight,i.fire("boundary",i.boundary))})),this._spinner=new Ee(this.scene,{canvas:this.canvas,elementId:t.spinnerElementId})}get type(){return"Canvas"}get backgroundColorFromAmbientLight(){return this._backgroundColorFromAmbientLight}set backgroundColorFromAmbientLight(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}get backgroundColor(){return this._backgroundColor}set backgroundColor(e){e?(this._backgroundColor[0]=e[0],this._backgroundColor[1]=e[1],this._backgroundColor[2]=e[2]):(this._backgroundColor[0]=1,this._backgroundColor[1]=1,this._backgroundColor[2]=1),this.glRedraw()}get resolutionScale(){return this._resolutionScale}set resolutionScale(e){if((e=e||1)===this._resolutionScale)return;this._resolutionScale=e;const t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}get spinner(){return this._spinner}_createCanvas(){const e="xeokit-canvas-"+c.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+='',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&&e0?Se.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?Se.FS_MAX_FLOAT_PRECISION="mediump":Se.FS_MAX_FLOAT_PRECISION="lowp":Se.FS_MAX_FLOAT_PRECISION="mediump",Se.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),Se.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),Se.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),Se.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),Se.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),Se.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),Se.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),Se.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),Se.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),Se.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){Se.SUPPORTED_EXTENSIONS[e]=!0})))}class Re{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get snappedCanvasPos(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null}set snappedCanvasPos(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}get worldPos(){return this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}get snapped(){return this.snappedToEdge||this.snappedToVertex}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}class Le{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;e0&&"/"===i.charAt(s+1)&&(i=i.substring(0,s)),t.push(i);return t.join("\n")}function Qe(e){console.error(e.join("\n"))}class Ve{constructor(e,t){this.id=Oe.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 Le(e,e.VERTEX_SHADER,Ne(this.source.vertex)),this._fragmentShader=new Le(e,e.FRAGMENT_SHADER,Ne(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void Qe(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void Qe(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void Qe(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void Qe(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 Qe(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;ithis.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}setData(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}bind(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}unbind(){this.allocated&&this._gl.bindBuffer(this.type,null)}destroy(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}class je{constructor(e,t){this.scene=e,this.aabb=c.AABB3(),this.origin=c.vec3(t),this.originHash=this.origin.join(),this.numMarkers=0,this.markers={},this.markerList=[],this.markerIndices={},this.positions=[],this.indices=[],this.positionsBuf=null,this.lenPositionsBuf=0,this.indicesBuf=null,this.sectionPlanesActive=[],this.culledBySectionPlanes=!1,this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.aabbDirty=!1,this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!1}addMarker(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}markerWorldPosUpdated(e){if(!this.markers[e.id])return;const t=this.markerIndices[e.id];this.positions[3*t+0]=e.worldPos[0],this.positions[3*t+1]=e.worldPos[1],this.positions[3*t+2]=e.worldPos[2],this.positionsDirty=!0}removeMarker(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}update(){this.markerListDirty&&(this._buildMarkerList(),this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0),this.positionsDirty&&(this._buildPositions(),this.positionsDirty=!1,this.aabbDirty=!0,this.vbosDirty=!0),this.aabbDirty&&(this._buildAABB(),this.aabbDirty=!1),this.vbosDirty&&(this._buildVBOs(),this.vbosDirty=!1),this.occlusionTestListDirty&&this._buildOcclusionTestList(),this._updateActiveSectionPlanes()}_buildMarkerList(){for(var e in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(e)&&(this.markerList[this.numMarkers]=this.markers[e],this.markerIndices[e]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers}_buildPositions(){let e=0;for(let t=0;t-t){i._setVisible(!1);continue}const n=i.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>s||l-10>r?i._setVisible(!1):!i.entity||i.entity.visible?i.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=i,this.pixels[o++]=a,this.pixels[o++]=l):i._setVisible(!0):i._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let i=0;i{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i||(i=new je(this._scene,e.origin),this._occlusionLayers[i.originHash]=i,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return;const i=e.origin.join();if(i!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let s=this._occlusionLayers[i];s||(s=new je(this._scene,e.origin),this._occlusionLayers[i]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.originHash],this._occlusionLayersListDirty=!0):i.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e0,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):e.markerZOffset<0&&i.push("clipPos.z += "+e.markerZOffset+";"),i.push(" gl_Position = clipPos;"),i.push("}"),i}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// OcclusionTester fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Ve(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e0){const e=s.sectionPlanes;for(let s=0;s{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=c.mat4();return()=>(e&&c.inverseMat4(s.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,i=this._program,s=this._scene,r=s.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=s.camera.project._state,l=a.near,A=a.far,h=a.matrix,u=this._getInverseProjectMat(),d=Math.random(),p="perspective"===s.camera.projection;Ke[0]=o,Ke[1]=n,t.viewport(0,0,o,n),t.clearColor(0,0,0,1),t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.frontFace(t.CCW),t.clear(t.COLOR_BUFFER_BIT),i.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,A),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,h),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,u),t.uniform1i(this._uPerspective,p),t.uniform1f(this._uScale,r.scale*(A/5)),t.uniform1f(this._uIntensity,r.intensity),t.uniform1f(this._uBias,r.bias),t.uniform1f(this._uKernelRadius,r.kernelRadius),t.uniform1f(this._uMinResolution,r.minResolution),t.uniform2fv(this._uViewport,Ke),t.uniform1f(this._uRandomSeed,d);const f=e.getDepthTexture();i.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e)return;const i=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new Ve(i,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),o=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new He(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new He(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new He(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const Je=new Float32Array(tt(17,[0,1])),Ye=new Float32Array(tt(17,[1,0])),Ze=new Float32Array(function(e,t){const i=[];for(let s=0;s<=e;s++)i.push(et(s,t));return i}(17,4)),qe=new Float32Array(2);class $e{constructor(e){this._scene=e,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._uViewport=null,this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new Ve(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS 16\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new He(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new He(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new He(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,i){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=c.mat4();return()=>(e&&c.inverseMat4(o.camera.projMatrix,t),t)})());const s=this._scene.canvas.gl,r=this._program,o=this._scene,n=s.drawingBufferWidth,a=s.drawingBufferHeight,l=o.camera.project._state,A=l.near,h=l.far;s.viewport(0,0,n,a),s.clearColor(0,0,0,1),s.enable(s.DEPTH_TEST),s.disable(s.BLEND),s.frontFace(s.CCW),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),r.bind(),qe[0]=n,qe[1]=a,s.uniform2fv(this._uViewport,qe),s.uniform1f(this._uCameraNear,A),s.uniform1f(this._uCameraFar,h),s.uniform1f(this._uDepthCutoff,.01),0===i?s.uniform2fv(this._uSampleOffsets,Ye):s.uniform2fv(this._uSampleOffsets,Je),s.uniform1fv(this._uSampleWeights,Ze);const u=e.getDepthTexture(),d=t.getTexture();r.bindTexture(this._uDepthTexture,u,0),r.bindTexture(this._uOcclusionTexture,d,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),s.drawElements(s.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function et(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function tt(e,t){const i=[];for(let s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}class it{constructor(e,t,i){i=i||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=i.size,this._hasDepthTexture=!!i.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(...e){if(this._touch(...e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}createTexture(e,t,i=null){const s=this.gl,r=s.createTexture();return s.bindTexture(s.TEXTURE_2D,r),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),i?s.texStorage2D(s.TEXTURE_2D,1,i,e,t):s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null),r}_touch(...e){let t,i;const s=this.gl;if(this.size?(t=this.size[0],i=this.size[1]):(t=s.drawingBufferWidth,i=s.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===i)return;this.buffer.textures.forEach((e=>s.deleteTexture(e))),s.deleteFramebuffer(this.buffer.framebuf),s.deleteRenderbuffer(this.buffer.renderbuf)}const r=[];let o;e.length>0?r.push(...e.map((e=>this.createTexture(t,i,e)))):r.push(this.createTexture(t,i)),this._hasDepthTexture&&(o=s.createTexture(),s.bindTexture(s.TEXTURE_2D,o),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,s.DEPTH_COMPONENT32F,t,i,0,s.DEPTH_COMPONENT,s.FLOAT,null));const n=s.createRenderbuffer();s.bindRenderbuffer(s.RENDERBUFFER,n),s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT32F,t,i);const a=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,a);for(let e=0;e0&&s.drawBuffers(r.map(((e,t)=>s.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,o,0):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,n),s.bindTexture(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,a),!s.isFramebuffer(a))throw"Invalid framebuffer";s.bindFramebuffer(s.FRAMEBUFFER,null);const l=s.checkFramebufferStatus(s.FRAMEBUFFER);switch(l){case s.FRAMEBUFFER_COMPLETE:break;case s.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case s.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:a,renderbuf:n,texture:r[0],textures:r,depthTexture:o,width:t,height:i},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,i=null,s=null,r=Uint8Array,o=4,n=0){const a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,A=new r(o),h=this.gl;return h.readBuffer(h.COLOR_ATTACHMENT0+n),h.readPixels(a,l,1,1,i||h.RGBA,s||h.UNSIGNED_BYTE,A,0),A}readArray(e=null,t=null,i=Uint8Array,s=4,r=0){const o=new i(this.buffer.width*this.buffer.height*s),n=this.gl;return n.readBuffer(n.COLOR_ATTACHMENT0+r),n.readPixels(0,0,this.buffer.width,this.buffer.height,e||n.RGBA,t||n.UNSIGNED_BYTE,o,0),o}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),i=t.pixelData,s=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,A=4*n,h=new Uint8Array(4*n);for(let e=0;ee.deleteTexture(t))),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}class st{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let s=i[e];return s||(s=new it(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=s),s}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}function rt(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}const ot=function(t,i){i=i||{};const s=new De(t),r=t.canvas.canvas,o=t.canvas.gl,n=!!i.transparent,a=i.alphaDepthMask,l=new e({});let A={},h={},u=[],d=[],f=!0,g=!0,m=!0,_=!0,v=!0,b=!0,y=!0,x=!0;const B=new st(t);let w=!1;const P=new Xe(t),C=new $e(t);function M(){f&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableMap,s=t.drawableListPreCull;let r=0;for(let e in i)i.hasOwnProperty(e)&&(s[r++]=i[e]);s.length=r}}(),f=!1,g=!0),g&&(!function(){let e=0;for(let t in A)if(A.hasOwnProperty(t)){const i=A[t].drawableListPreCull;for(let t=0,s=i.length;te.renderOrder-t.renderOrder))}(),g=!1,m=!0),m&&function(){let e=0;for(let t=0,i=u.length;t0)for(s.withSAO=!0,S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||H>0||k>0||O>0){if(o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):(o.blendEquation(o.FUNC_ADD),o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA)),s.backfaces=!1,a||o.depthMask(!1),(k>0||O>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),O>0)for(S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||G>0){if(s.lastProgramId=null,t.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),G>0)for(S=0;S0)for(S=0;S0||W>0||j>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),o.enable(o.CULL_FACE),W>0)for(S=0;S0)for(S=0;S0||X>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),X>0)for(S=0;S0)for(S=0;S0||Y>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),Y>0)for(S=0;S0)for(S=0;S0){const t=Math.floor(e/4),i=_.size[0],s=t%i-Math.floor(i/2),r=Math.floor(t/i)-Math.floor(i/2),o=Math.sqrt(Math.pow(s,2)+Math.pow(r,2));U.push({x:s,y:r,dist:o,isVertex:p&&f?x[e+3]>y.length/2:p,result:[x[e+0],x[e+1],x[e+2],x[e+3]],normal:[w[e+0],w[e+1],w[e+2],w[e+3]],id:[P[e+0],P[e+1],P[e+2],P[e+3]]})}let k=null,O=null,N=null,Q=null;if(U.length>0){U.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),Q=U[0].isVertex?"vertex":"edge";const e=U[0].result,t=U[0].normal,i=U[0].id,s=y[e[3]],r=s.origin,o=s.coordinateScale;O=c.normalizeVec3([t[0]/c.MAX_INT,t[1]/c.MAX_INT,t[2]/c.MAX_INT]),k=[e[0]*o[0]+r[0],e[1]*o[1]+r[1],e[2]*o[2]+r[2]],N=l.items[i[0]+(i[1]<<8)+(i[2]<<16)+(i[3]<<24)]}if(null===C&&null==k)return null;let V=null;null!==k&&(V=t.camera.projectWorldPos(k));const H=N&&N.delegatePickedEntity?N.delegatePickedEntity():N;return!H&&E&&(E=E.delegatePickedEntity?E.delegatePickedEntity():E),r.reset(),r.snappedToEdge="edge"===Q,r.snappedToVertex="vertex"===Q,r.worldPos=k||C,r.worldNormal=O||M,r.entity=H||E,r.canvasPos=n||t.camera.projectWorldPos(C||k),r.snappedCanvasPos=V||n,r}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new We(t,B),this._occlusionTester.addMarker(e),t.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){M(),this._occlusionTester.bindRenderBuf(),s.reset(),s.backfaces=!0,s.frontface=!0,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e=0,t=d.length;e{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!0:e.keyCode===this.KEY_ALT?this.altDown=!0:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!0),this.keyDown[e.keyCode]=!0,this.fire("keydown",e.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!1:e.keyCode===this.KEY_ALT?this.altDown=!1:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!1),this.keyDown[e.keyCode]=!1,this.fire("keyup",e.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=e=>{this.enabled&&(this.mouseover=!0,this._getMouseCanvasPos(e),this.fire("mouseenter",this.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=e=>{this.enabled&&(this.mouseover=!1,this._getMouseCanvasPos(e),this.fire("mouseleave",this.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!0;break;case 2:this.mouseDownMiddle=!0;break;case 3:this.mouseDownRight=!0}this._getMouseCanvasPos(e),this.element.focus(),this.fire("mousedown",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownRight=!1}this.fire("mouseup",this.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("click",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("dblclick",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}});const e=this.scene.tickify((()=>this.fire("mousemove",this.mouseCanvasPos,!0)));this.element.addEventListener("mousemove",this._mouseMoveListener=t=>{this.enabled&&(this._getMouseCanvasPos(t),e(),this.mouseover&&t.preventDefault())}),this.element.addEventListener("contextmenu",this._contextmenuListener=e=>{this.enabled&&(this._getMouseCanvasPos(e),this.fire("contextmenu",this.mouseCanvasPos,!0))});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,i)=>{if(!this.enabled)return;const s=Math.max(-1,Math.min(1,40*-e.deltaY));t(s)},{passive:!0});{let e,t;const i=2;this.on("mousedown",(i=>{e=i[0],t=i[1]})),this.on("mouseup",(s=>{e>=s[0]-i&&e<=s[0]+i&&t>=s[1]-i&&t<=s[1]+i&&this.fire("mouseclicked",s,!0)}))}this.element.addEventListener("touchstart",this._touchstartListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchstart",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this.element.addEventListener("touchend",this._touchendListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchend",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this._eventsBound=!0}_unbindEvents(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("contextmenu",this._contextmenuListener),this.element.removeEventListener("wheel",this._mouseWheelListener),this.element.removeEventListener("touchstart",this._touchstartListener),this.element.removeEventListener("touchend",this._touchendListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getTouchCanvasPos(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;return[e.pageX-i,e.pageY-s]}_getMouseCanvasPos(e){if(e){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()}}const at=new e({});class lt{constructor(e){this.id=at.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){at.removeItem(this.id)}}class At extends D{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new lt({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 ht extends D{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new lt({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.canvas.boundary,t=e[2]/e[3],i=this._fovAxis;let s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),c.perspectiveMat4(s*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class ct extends D{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new lt({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,i=e.canvas.boundary,s=i[2],r=i[3],o=s/r;let n,a,l,A;s>r?(n=-t,a=t,l=t/o,A=-t/o):(n=-t*o,a=t*o,l=t,A=-t),c.orthoMat4c(n,a,A,l,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class ut extends D{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new lt({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.mat4(),near:.1,far:1e4}),this._left=-1,this._right=1,this._bottom=-1,this._top=1,this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.left=t.left,this.right=t.right,this.bottom=t.bottom,this.top=t.top,this.near=t.near,this.far=t.far}_update(){c.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set left(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}get left(){return this._left}set right(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}get right(){return this._right}set top(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}get top(){return this._top}set bottom(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}get bottom(){return this._bottom}set near(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}get near(){return this._state.near}set far(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class dt extends D{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new lt({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.mat4()}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!1,this.matrix=t.matrix}set matrix(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}get matrix(){return this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy()}}const pt=c.vec3(),ft=c.vec3(),gt=c.vec3(),mt=c.vec3(),_t=c.vec3(),vt=c.vec3(),bt=c.vec4(),yt=c.vec4(),xt=c.vec4(),Bt=c.mat4(),wt=c.mat4(),Pt=c.vec3(),Ct=c.vec3(),Mt=c.vec3(),Et=c.vec3();class Ft extends D{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new lt({deviceMatrix:c.mat4(),hasDeviceMatrix:!1,matrix:c.mat4(),normalMatrix:c.mat4(),inverseMatrix:c.mat4()}),this._perspective=new ht(this),this._ortho=new ct(this),this._frustum=new ut(this),this._customProjection=new dt(this),this._project=this._perspective,this._eye=c.vec3([0,0,10]),this._look=c.vec3([0,0,0]),this._up=c.vec3([0,1,0]),this._worldUp=c.vec3([0,1,0]),this._worldRight=c.vec3([1,0,0]),this._worldForward=c.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?(c.subVec3(this._eye,this._look,Pt),c.normalizeVec3(Pt,Ct),c.mulVec3Scalar(Ct,1e3,Mt),c.addVec3(this._look,Mt,Et),t=Et):t=this._eye,e.hasDeviceMatrix?(c.lookAtMat4v(t,this._look,this._up,wt),c.mulMat4(e.deviceMatrix,wt,e.matrix)):c.lookAtMat4v(t,this._look,this._up,e.matrix),c.inverseMat4(this._state.matrix,this._state.inverseMatrix),c.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}orbitYaw(e){let t=c.subVec3(this._eye,this._look,pt);c.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,Bt),t=c.transformPoint3(Bt,t,ft),this.eye=c.addVec3(this._look,t,gt),this.up=c.transformPoint3(Bt,this._up,mt)}orbitPitch(e){if(this._constrainPitch&&(e=c.dotVec3(this._up,this._worldUp)/c.DEGTORAD)<1)return;let t=c.subVec3(this._eye,this._look,pt);const i=c.cross3Vec3(c.normalizeVec3(t,ft),c.normalizeVec3(this._up,gt));c.rotationMat4v(.0174532925*e,i,Bt),t=c.transformPoint3(Bt,t,mt),this.up=c.transformPoint3(Bt,this._up,_t),this.eye=c.addVec3(t,this._look,vt)}yaw(e){let t=c.subVec3(this._look,this._eye,pt);c.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,Bt),t=c.transformPoint3(Bt,t,ft),this.look=c.addVec3(t,this._eye,gt),this._gimbalLock&&(this.up=c.transformPoint3(Bt,this._up,mt))}pitch(e){if(this._constrainPitch&&(e=c.dotVec3(this._up,this._worldUp)/c.DEGTORAD)<1)return;let t=c.subVec3(this._look,this._eye,pt);const i=c.cross3Vec3(c.normalizeVec3(t,ft),c.normalizeVec3(this._up,gt));c.rotationMat4v(.0174532925*e,i,Bt),this.up=c.transformPoint3(Bt,this._up,vt),t=c.transformPoint3(Bt,t,mt),this.look=c.addVec3(t,this._eye,_t)}pan(e){const t=c.subVec3(this._eye,this._look,pt),i=[0,0,0];let s;if(0!==e[0]){const r=c.cross3Vec3(c.normalizeVec3(t,[]),c.normalizeVec3(this._up,ft));s=c.mulVec3Scalar(r,e[0]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]}0!==e[1]&&(s=c.mulVec3Scalar(c.normalizeVec3(this._up,gt),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=c.mulVec3Scalar(c.normalizeVec3(t,mt),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=c.addVec3(this._eye,i,_t),this.look=c.addVec3(this._look,i,vt)}zoom(e){const t=c.subVec3(this._eye,this._look,pt),i=Math.abs(c.lenVec3(t,ft)),s=Math.abs(i+e);if(s<.5)return;const r=c.normalizeVec3(t,gt);this.eye=c.addVec3(this._look,c.mulVec3Scalar(r,s),mt)}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=c.vec3(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}get worldAxis(){return this._worldAxis}get worldUp(){return this._worldUp}get xUp(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}get yUp(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}get zUp(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}get worldRight(){return this._worldRight}get worldForward(){return this._worldForward}set gimbalLock(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}get gimbalLock(){return this._gimbalLock}set constrainPitch(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}get eyeLookDist(){return c.lenVec3(c.subVec3(this._look,this._eye,pt))}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get viewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get normalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get viewNormalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get inverseViewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}get projMatrix(){return this[this.projection].matrix}get perspective(){return this._perspective}get ortho(){return this._ortho}get frustum(){return this._frustum}get customProjection(){return this._customProjection}set projection(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}get projection(){return this._projectionType}get project(){return this._project}projectWorldPos(e){const t=bt,i=yt,s=xt;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,c.mulMat4v4(this.viewMatrix,t,i),c.mulMat4v4(this.projMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[s[0]*o+o,s[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}class It extends D{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class Dt extends It{get type(){return"DirLight"}constructor(e,t={}){super(e,t),this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const i=this.scene.camera,s=this.scene.canvas;this._onCameraViewMatrix=i.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=i.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=s.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new lt({type:"dir",dir:c.vec3([1,1,1]),color:c.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=c.identityMat4());const e=this.scene.camera,t=this._state.dir,i=e.look,s=[i[0]-t[0],i[1]-t[1],i[2]-t[2]],r=[0,1,0];c.lookAtMat4v(s,i,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=c.identityMat4()),c.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new it(this.scene.canvas.canvas,this.scene.canvas.gl,{size:[1024,1024]})),this._shadowRenderBuf)}),this.dir=t.dir,this.color=t.color,this.intensity=t.intensity,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set dir(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get dir(){return this._state.dir}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}class St extends It{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:c.vec3([.7,.7,.7]),intensity:1},this.color=t.color,this.intensity=t.intensity,this.scene._lightCreated(this)}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}get intensity(){return this._state.intensity}destroy(){super.destroy(),this.scene._lightDestroyed(this)}}class Tt extends D{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),p.memory.meshes++}destroy(){super.destroy(),p.memory.meshes--}}var Rt=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=c.vec3(),h=c.vec3(),u=c.vec3(),d=c.vec3(),p=c.vec3(),f=c.vec3(),g=c.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;ux)||(T=i[F.index1],R=i[F.index2],(!L&&T>65535||R>65535)&&(L=!0),y.push(T),y.push(R));return L?new Uint32Array(y):new Uint16Array(y)}}();const Lt=function(){const e=c.mat4(),t=c.mat4();return function(i,s){s=s||c.mat4();const r=i[0],o=i[1],n=i[2],a=i[3]-r,l=i[4]-o,A=i[5]-n,h=65535;return c.identityMat4(e),c.translationMat4v(i,e),c.identityMat4(t),c.scalingMat4v([a/h,l/h,A/h],t),c.mulMat4(e,t,s),s}}();var Ut=function(){const e=c.mat4(),t=c.mat4();return function(i,s,r){const o=new Uint16Array(i.length),n=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);let a;for(a=0;a=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 Nt(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 Qt(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}const Vt={getPositionsBounds:function(e){const t=new Float32Array(3),i=new Float32Array(3);let s,r;for(s=0;s<3;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;sn&&(r=i,n=o),i=Ot(e,a,"floor","ceil"),s=Nt(i),o=Qt(e,a,s),o>n&&(r=i,n=o),i=Ot(e,a,"ceil","ceil"),s=Nt(i),o=Qt(e,a,s),o>n&&(r=i,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t},decompressNormal:function(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t}},Ht=p.memory,jt=c.AABB3();class Gt extends Tt{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new lt({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=Vt.getPositionsBounds(t.positions),s=Vt.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=Vt.getUVBounds(t.uv),s=Vt.compressUVs(t.uv,e.min,e.max);i.uv=s.quantized,i.uvDecodeMatrix=s.decodeMatrix}else i.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?i.normals=Vt.compressNormals(t.normals):i.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(i.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)),this._buildHash(),Ht.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new He(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),Ht.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new He(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),Ht.positions+=e.positionsBuf.numItems),e.normals){let i=e.compressGeometry;e.normalsBuf=new He(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),Ht.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new He(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),Ht.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new He(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),Ht.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=Rt(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new He(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),Ht.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=c.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new He(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new He(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),Ht.positions+=this._pickTrianglePositionsBuf.numItems,Ht.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),Vt.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=Vt.getPositionsBounds(e),s=Vt.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),Vt.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),Vt.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=c.AABB3()),c.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=c.OBB3()),c.positions3ToAABB3(this._state.positions,jt,this._state.positionsDecodeMatrix),c.AABB3ToOBB3(jt,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(),Ht.meshes--}}function zt(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return _.apply(e,{positions:[c,u,d,l,u,d,l,A,d,c,A,d,c,u,d,c,A,d,c,A,h,c,u,h,c,u,d,c,u,h,l,u,h,l,u,d,l,u,d,l,u,h,l,A,h,l,A,d,l,A,h,c,A,h,c,A,d,l,A,d,c,A,h,l,A,h,l,u,h,c,u,h],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 Wt extends D{get type(){return"Material"}constructor(e,t={}){super(e,t),p.memory.materials++}destroy(){super.destroy(),p.memory.materials--}}const Kt={opaque:0,mask:1,blend:2},Xt=["opaque","mask","blend"];class Jt extends Wt{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new lt({type:"PhongMaterial",ambient:c.vec3([1,1,1]),diffuse:c.vec3([1,1,1]),specular:c.vec3([1,1,1]),emissive:c.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.ambient=t.ambient,this.diffuse=t.diffuse,this.specular=t.specular,this.emissive=t.emissive,this.alpha=t.alpha,this.shininess=t.shininess,this.reflectivity=t.reflectivity,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,t.ambientMap&&(this._ambientMap=this._checkComponent("Texture",t.ambientMap)),t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.reflectivityMap&&(this._reflectivityMap=this._checkComponent("Texture",t.reflectivityMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.diffuseFresnel&&(this._diffuseFresnel=this._checkComponent("Fresnel",t.diffuseFresnel)),t.specularFresnel&&(this._specularFresnel=this._checkComponent("Fresnel",t.specularFresnel)),t.emissiveFresnel&&(this._emissiveFresnel=this._checkComponent("Fresnel",t.emissiveFresnel)),t.alphaFresnel&&(this._alphaFresnel=this._checkComponent("Fresnel",t.alphaFresnel)),t.reflectivityFresnel&&(this._reflectivityFresnel=this._checkComponent("Fresnel",t.reflectivityFresnel)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this._makeHash()}_makeHash(){const e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}set shininess(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}get shininess(){return this._state.shininess}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set reflectivity(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}get reflectivity(){return this._state.reflectivity}get normalMap(){return this._normalMap}get ambientMap(){return this._ambientMap}get diffuseMap(){return this._diffuseMap}get specularMap(){return this._specularMap}get emissiveMap(){return this._emissiveMap}get alphaMap(){return this._alphaMap}get reflectivityMap(){return this._reflectivityMap}get occlusionMap(){return this._occlusionMap}get diffuseFresnel(){return this._diffuseFresnel}get specularFresnel(){return this._specularFresnel}get emissiveFresnel(){return this._emissiveFresnel}get alphaFresnel(){return this._alphaFresnel}get reflectivityFresnel(){return this._reflectivityFresnel}set alphaMode(e){let t=Kt[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" - defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return Xt[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}destroy(){super.destroy(),this._state.destroy()}}const Yt={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}};class Zt extends Wt{get type(){return"EmphasisMaterial"}get presets(){return Yt}constructor(e,t={}){super(e,t),this._state=new lt({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),this._preset="default",t.preset?(this.preset=t.preset,void 0!==t.fill&&(this.fill=t.fill),t.fillColor&&(this.fillColor=t.fillColor),void 0!==t.fillAlpha&&(this.fillAlpha=t.fillAlpha),void 0!==t.edges&&(this.edges=t.edges),t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth),void 0!==t.backfaces&&(this.backfaces=t.backfaces),void 0!==t.glowThrough&&(this.glowThrough=t.glowThrough)):(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.backfaces=t.backfaces,this.glowThrough=t.glowThrough)}set fill(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}get fill(){return this._state.fill}set fillColor(e){let t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}get fillColor(){return this._state.fillColor}set fillAlpha(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}get fillAlpha(){return this._state.fillAlpha}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set glowThrough(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}get glowThrough(){return this._state.glowThrough}set preset(e){if(e=e||"default",this._preset===e)return;const t=Yt[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Yt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const qt={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 $t extends Wt{get type(){return"EdgeMaterial"}get presets(){return qt}constructor(e,t={}){super(e,t),this._state=new lt({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),this._preset="default",t.preset?(this.preset=t.preset,t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth)):(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth),this.edges=!1!==t.edges}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=qt[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(qt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const ei={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 ti extends D{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=c.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return ei}set units(e){e||(e="meters");ei[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=c.vec3(3)){t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}realToWorldPos(e,t=c.vec3(3)){return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}class ii extends D{constructor(e,t={}){super(e,t),this._supported=Se.SUPPORTED_EXTENSIONS.OES_standard_derivatives,this.enabled=t.enabled,this.kernelRadius=t.kernelRadius,this.intensity=t.intensity,this.bias=t.bias,this.scale=t.scale,this.minResolution=t.minResolution,this.numSamples=t.numSamples,this.blur=t.blur,this.blendCutoff=t.blendCutoff,this.blendFactor=t.blendFactor}get supported(){return this._supported}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}get enabled(){return this._enabled}get possible(){if(!this._supported)return!1;if(!this._enabled)return!1;const e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}get active(){return this._active}set kernelRadius(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}get kernelRadius(){return this._kernelRadius}set intensity(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}get intensity(){return this._intensity}set bias(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}get bias(){return this._bias}set scale(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}get scale(){return this._scale}set minResolution(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}get minResolution(){return this._minResolution}set numSamples(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}get numSamples(){return this._numSamples}set blur(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}get blur(){return this._blur}set blendCutoff(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}get blendCutoff(){return this._blendCutoff}set blendFactor(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}get blendFactor(){return this._blendFactor}destroy(){super.destroy()}}class si extends D{constructor(e,t={}){super(e,t),this.sliceColor=t.sliceColor,this.sliceThickness=t.sliceThickness}set sliceThickness(e){null==e&&(e=0),this._sliceThickness!==e&&(this._sliceThickness=e,this.glRedraw())}get sliceThickness(){return this._sliceThickness}set sliceColor(e){null==e&&(e=[0,0,0,1]),this._sliceColor!==e&&(this._sliceColor=e,this.glRedraw())}get sliceColor(){return this._sliceColor}destroy(){super.destroy()}}const ri={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class oi extends Wt{get type(){return"PointsMaterial"}get presets(){return ri}constructor(e,t={}){super(e,t),this._state=new lt({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),t.preset?(this.preset=t.preset,void 0!==t.pointSize&&(this.pointSize=t.pointSize),void 0!==t.roundPoints&&(this.roundPoints=t.roundPoints),void 0!==t.perspectivePoints&&(this.perspectivePoints=t.perspectivePoints),void 0!==t.minPerspectivePointSize&&(this.minPerspectivePointSize=t.minPerspectivePointSize),void 0!==t.maxPerspectivePointSize&&(this.maxPerspectivePointSize=t.minPerspectivePointSize)):(this._preset="default",this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize),this.filterIntensity=t.filterIntensity,this.minIntensity=t.minIntensity,this.maxIntensity=t.maxIntensity}set pointSize(e){this._state.pointSize=e||2,this.glRedraw()}get pointSize(){return this._state.pointSize}set roundPoints(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}get roundPoints(){return this._state.roundPoints}set perspectivePoints(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}get perspectivePoints(){return this._state.perspectivePoints}set minPerspectivePointSize(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}get minPerspectivePointSize(){return this._state.minPerspectivePointSize}set maxPerspectivePointSize(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}get maxPerspectivePointSize(){return this._state.maxPerspectivePointSize}set filterIntensity(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}get filterIntensity(){return this._state.filterIntensity}set minIntensity(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}get minIntensity(){return this._state.minIntensity}set maxIntensity(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}get maxIntensity(){return this._state.maxIntensity}set preset(e){if(e=e||"default",this._preset===e)return;const t=ri[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(ri).join(", "))}get preset(){return this._preset}get hash(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}destroy(){super.destroy(),this._state.destroy()}}const ni={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class ai extends Wt{get type(){return"LinesMaterial"}get presets(){return ni}constructor(e,t={}){super(e,t),this._state=new lt({type:"LinesMaterial",lineWidth:null}),t.preset?(this.preset=t.preset,void 0!==t.lineWidth&&(this.lineWidth=t.lineWidth)):(this._preset="default",this.lineWidth=t.lineWidth)}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=ni[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(ni).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function li(e,t){const i={};let s,r;for(let o=0,n=t.length;o{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new ot(this,{transparent:s,alphaDepthMask:r}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;let e=null;this.getHash=function(){if(e)return e;const t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";const i=[];for(let e=0,s=t;ethis._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},this._sectionPlanesState.setNumCachedSectionPlanes(t.numCachedSectionPlanes||0),this._lightsState=new function(){const e=c.vec4([0,0,0,0]),t=c.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let i=null,s=null;this.getHash=function(){if(i)return i;const e=[],t=this.lights;let s;for(let i=0,r=t.length;i0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),i=e.join(""),i},this.addLight=function(e){this.lights.push(e),s=null,i=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t{this._renderer.imageDirty()}))}_initDefaults(){}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+_.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=c.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],_.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}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_deRegisterVisibleObject(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_deRegisterXRayedObject(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}_objectHighlightedUpdated(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}_deRegisterHighlightedObject(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_deRegisterSelectedObject(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_deRegisterColorizedObject(e){delete this.colorizedObjects[e.id],this._numColorizedObjects--,this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_deRegisterOpacityObject(e){delete this.opacityObjects[e.id],this._numOpacityObjects--,this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_deRegisterOffsetObject(e){delete this.offsetObjects[e.id],this._numOffsetObjects--,this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get readableGeometryEnabled(){return this._readableGeometry}get pickSurfacePrecisionEnabled(){return this._readableGeometry}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set numCachedSectionPlanes(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}get numCachedSectionPlanes(){return this._sectionPlanesState.getNumCachedSectionPlanes()}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}get markerZOffset(){return null==this._markerZOffset?-.001:this._markerZOffset}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&M.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const i=this._passes,s=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),A=!0}A||(t=-100,i=-100,s=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=n,this._aabbDirty=!1,this._center=null}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const i=e.includeEntities||e.include;i&&(e.includeEntityIds=li(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=li(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){if(void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),e.canvasPos)return this._renderer.snapPick(e);this.error("Scene.snapPick() canvasPos parameter expected")}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,i=e.length;t{if(e.collidable){const l=e.aabb;l[0]o&&(o=l[3]),l[4]>n&&(n=l[4]),l[5]>a&&(a=l[5]),t=!0}})),t){const e=c.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=o,e[4]=n,e[5]=a,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const i=e.visible!==t;return e.visible=t,i}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const i=e.collidable!==t;return e.collidable=t,i}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const i=e.culled!==t;return e.culled=t,i}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const i=e.selected!==t;return e.selected=t,i}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const i=e.highlighted!==t;return e.highlighted=t,i}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const i=e.xrayed!==t;return e.xrayed=t,i}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const i=e.edges!==t;return e.edges=t,i}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const i=e.opacity!==t;return e.opacity=t,i}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const i=e.pickable!==t;return e.pickable=t,i}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){_.isString(e)&&(e=[e]);let i=!1;for(let s=0,r=e.length;s{r>s&&(s=r,e(...i))}));return this._tickifiedFunctions[t]={tickSubId:n,wrapperFunc:o},o}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const hi=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene._lightsState,r=e._geometry._state,o=e._state.billboard,n=e._state.stationary,a=i.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,A=[];A.push("#version 300 es"),A.push("// Lambertian drawing vertex shader"),A.push("in vec3 position;"),A.push("uniform mat4 modelMatrix;"),A.push("uniform mat4 viewMatrix;"),A.push("uniform mat4 projMatrix;"),A.push("uniform vec4 colorize;"),A.push("uniform vec3 offset;"),l&&A.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(A.push("uniform float logDepthBufFC;"),A.push("out float vFragDepth;"),A.push("bool isPerspectiveMatrix(mat4 m) {"),A.push(" return (m[2][3] == - 1.0);"),A.push("}"),A.push("out float isPerspective;"));a&&A.push("out vec4 vWorldPosition;");if(A.push("uniform vec4 lightAmbient;"),A.push("uniform vec4 materialColor;"),A.push("uniform vec3 materialEmissive;"),r.normalsBuf){A.push("in vec3 normal;"),A.push("uniform mat4 modelNormalMatrix;"),A.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),A.push(" }"),A.push(" return normalize(v);"),A.push("}"))}A.push("out vec4 vColor;"),"points"===r.primitiveName&&A.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(A.push("void billboard(inout mat4 mat) {"),A.push(" mat[0][0] = 1.0;"),A.push(" mat[0][1] = 0.0;"),A.push(" mat[0][2] = 0.0;"),"spherical"===o&&(A.push(" mat[1][0] = 0.0;"),A.push(" mat[1][1] = 1.0;"),A.push(" mat[1][2] = 0.0;")),A.push(" mat[2][0] = 0.0;"),A.push(" mat[2][1] = 0.0;"),A.push(" mat[2][2] =1.0;"),A.push("}"));A.push("void main(void) {"),A.push("vec4 localPosition = vec4(position, 1.0); "),A.push("vec4 worldPosition;"),l&&A.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?A.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):A.push("vec4 localNormal = vec4(normal, 0.0); "),A.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),A.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));A.push("mat4 viewMatrix2 = viewMatrix;"),A.push("mat4 modelMatrix2 = modelMatrix;"),n&&A.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(A.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),A.push("billboard(modelMatrix2);"),A.push("billboard(viewMatrix2);"),A.push("billboard(modelViewMatrix);"),r.normalsBuf&&(A.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),A.push("billboard(modelNormalMatrix2);"),A.push("billboard(viewNormalMatrix2);"),A.push("billboard(modelViewNormalMatrix);")),A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&A.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(A.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),A.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),A.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=s.lights.length;e0,o=t.gammaOutput,n=[];n.push("#version 300 es"),n.push("// Lambertian drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));if(r){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}"points"===s.primitiveName&&(n.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push("float r = dot(cxy, cxy);"),n.push("if (r > 1.0) {"),n.push(" discard;"),n.push("}"));t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");o?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(e)):(this.vertex=function(e){const t=e.scene;e._material;const i=e._state,s=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=i.billboard,l=i.background,A=i.stationary,h=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),c=di(e),u=s.getNumAllocatedSectionPlanes()>0,d=ui(e),p=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),p&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),u&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));o.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(c){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(let e=0,t=o.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}h&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),p&&f.push("uniform mat3 uvDecodeMatrix;"));r.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===r.primitiveName&&f.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = 1.0;"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===a&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = 1.0;"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(d){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(let e=0,t=o.lights.length;e0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(let e=0,t=o.lights.length;e0,l=di(e),A=s.uvBuf,h="PhongMaterial"===n.type,c="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,d=ui(e);t.gammaInput;const p=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));d&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),p&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var g=0;g0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),o.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),h&&((o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = "+ci[o.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(c||u)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),o.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+ci[o.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),s.colors&&f.push("in vec4 vColor;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._occlusionMap||i._alphaMap)&&f.push("in vec2 vUV;");l&&(o.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));n.ambient&&f.push("uniform vec3 materialAmbient;");n.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==n.alpha&&null!==n.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");n.emissive&&f.push("uniform vec3 materialEmissive;");n.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==n.glossiness&&null!==n.glossiness&&f.push("uniform float materialGlossiness;");void 0!==n.shininess&&null!==n.shininess&&f.push("uniform float materialShininess;");n.specular&&f.push("uniform vec3 materialSpecular;");void 0!==n.metallic&&null!==n.metallic&&f.push("uniform float materialMetallic;");void 0!==n.roughness&&null!==n.roughness&&f.push("uniform float materialRoughness;");void 0!==n.specularF0&&null!==n.specularF0&&f.push("uniform float materialSpecularF0;");A&&i._ambientMap&&(f.push("uniform sampler2D ambientMap;"),i._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));A&&i._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),i._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));A&&i._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),i._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));A&&i._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),i._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&A&&i._metallicMap&&(f.push("uniform sampler2D metallicMap;"),i._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&A&&i._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),i._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&A&&i._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),i._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&i._normalMap&&(f.push("uniform sampler2D normalMap;"),i._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));A&&i._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),i._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));A&&i._alphaMap&&(f.push("uniform sampler2D alphaMap;"),i._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&A&&i._specularMap&&(f.push("uniform sampler2D specularMap;"),i._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&A&&i._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),i._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&A&&i._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),i._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(i._diffuseFresnel||i._specularFresnel||i._alphaFresnel||i._emissiveFresnel||i._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),i._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),i._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),i._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),i._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),i._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(let e=0,t=o.lights.length;e 0.0) { discard; }"),f.push("}")}"points"===s.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),n.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");n.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):n.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");s.colors&&f.push("diffuseColor *= vColor.rgb;");n.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");n.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==n.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");s.colors&&f.push("alpha *= vColor.a;");void 0!==n.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==n.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==n.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==n.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._occlusionMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));A&&i._ambientMap&&(i._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+ci[i._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));A&&i._diffuseMap&&(i._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+ci[i._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));A&&i._baseColorMap&&(i._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+ci[i._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));A&&i._emissiveMap&&(i._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+ci[i._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));A&&i._alphaMap&&(i._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));A&&i._occlusionMap&&(i._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(o.lights.length>0||o.lightMaps.length>0||o.reflectionMaps.length>0)){A&&i._normalMap?(i._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),A&&i._specularMap&&(i._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),A&&i._glossinessMap&&(i._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),A&&i._specularGlossinessMap&&(i._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),A&&i._metallicMap&&(i._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),A&&i._roughnessMap&&(i._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),A&&i._metallicRoughnessMap&&(i._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),i._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),i._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),i._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),i._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),h&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),u&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),c&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),o.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),h&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(u||c)&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(let e=0,t=o.lights.length;e0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(h=0,c=o.sectionPlanes.length;h0&&r.lightMaps[0].texture&&this._uLightMap&&(a.bindTexture(this._uLightMap,r.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),r.reflectionMaps.length>0&&r.reflectionMaps[0].texture&&this._uReflectionMap&&(a.bindTexture(this._uReflectionMap,r.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor),this._baseTextureUnit=e.textureUnit};class _i{constructor(e){this.vertex=function(e){const t=e.scene,i=t._lightsState,s=function(e){const t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),r=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,o=!!e._geometry._state.compressGeometry,n=e._state.billboard,a=e._state.stationary,l=[];l.push("#version 300 es"),l.push("// EmphasisFillShaderSource vertex shader"),l.push("in vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),l.push("uniform vec3 offset;"),o&&l.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;"));r&&l.push("out vec4 vWorldPosition;");if(l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),s){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"))}l.push("out vec4 vColor;"),("spherical"===n||"cylindrical"===n)&&(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = 1.0;"),l.push(" mat[0][1] = 0.0;"),l.push(" mat[0][2] = 0.0;"),"spherical"===n&&(l.push(" mat[1][0] = 0.0;"),l.push(" mat[1][1] = 1.0;"),l.push(" mat[1][2] = 0.0;")),l.push(" mat[2][0] = 0.0;"),l.push(" mat[2][1] = 0.0;"),l.push(" mat[2][2] =1.0;"),l.push("}"));l.push("void main(void) {"),l.push("vec4 localPosition = vec4(position, 1.0); "),l.push("vec4 worldPosition;"),o&&l.push("localPosition = positionsDecodeMatrix * localPosition;");s&&(o?l.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):l.push("vec4 localNormal = vec4(normal, 0.0); "),l.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),l.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));l.push("mat4 viewMatrix2 = viewMatrix;"),l.push("mat4 modelMatrix2 = modelMatrix;"),a&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===n||"cylindrical"===n?(l.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),l.push("billboard(modelMatrix2);"),l.push("billboard(viewMatrix2);"),l.push("billboard(modelViewMatrix);"),s&&(l.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),l.push("billboard(modelNormalMatrix2);"),l.push("billboard(viewNormalMatrix2);"),l.push("billboard(modelViewNormalMatrix);")),l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),s)for(let e=0,t=i.lights.length;e0,o=[];o.push("#version 300 es"),o.push("// Lambertian drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}"points"===e._geometry._state.primitiveName&&(o.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("float r = dot(cxy, cxy);"),o.push("if (r > 1.0) {"),o.push(" discard;"),o.push("}"));t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const vi=new e({}),bi=c.vec3(),yi=function(e,t){this.id=vi.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new _i(t),this._allocate(t)},xi={};yi.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=xi[t];return i||(i=new yi(t,e),xi[t]=i,p.memory.programs++),i._useCount++,i},yi.prototype.put=function(){0==--this._useCount&&(vi.removeItem(this.id),this._program&&this._program.destroy(),delete xi[this._hash],p.memory.programs--)},yi.prototype.webglContextRestored=function(){this._program=null},yi.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl,n=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,A=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,A?e.getRTCViewMatrix(a.originHash,A):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Edges drawing vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec4 edgeColor;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));i&&n.push("out vec4 vWorldPosition;");n.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n.push("vColor = edgeColor;"),i&&n.push("vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.getNumAllocatedSectionPlanes()>0,o=[];o.push("#version 300 es"),o.push("// Edges drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const wi=new e({}),Pi=c.vec3(),Ci=function(e,t){this.id=wi.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Bi(t),this._allocate(t)},Mi={};Ci.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=Mi[t];return i||(i=new Ci(t,e),Mi[t]=i,p.memory.programs++),i._useCount++,i},Ci.prototype.put=function(){0==--this._useCount&&(wi.removeItem(this.id),this._program&&this._program.destroy(),delete Mi[this._hash],p.memory.programs--)},Ci.prototype.webglContextRestored=function(){this._program=null},Ci.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl;let n;const a=t._state,l=t._geometry,A=l._state,h=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(a.originHash,h):r.viewMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh picking vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("out vec4 vViewPosition;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("uniform vec2 pickClipPos;"),n.push("vec4 remapClipPos(vec4 clipPos) {"),n.push(" clipPos.xy /= clipPos.w;"),n.push(" clipPos.xy -= pickClipPos;"),n.push(" clipPos.xy *= clipPos.w;"),n.push(" return clipPos;"),n.push("}"),n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==r&&"cylindrical"!==r||(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"));n.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = remapClipPos(clipPos);"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(r.push("uniform vec4 pickColor;"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = pickColor; "),r.push("}"),r}(e)}}const Fi=c.vec3(),Ii=function(e,t){this._hash=e,this._shaderSource=new Ei(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Di={};Ii.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=Di[t];if(!i){if(i=new Ii(t,e),i.errors)return console.log(i.errors.join("\n")),null;Di[t]=i,p.memory.programs++}return i._useCount++,i},Ii.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Di[this._hash],p.memory.programs--)},Ii.prototype.webglContextRestored=function(){this._program=null},Ii.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t>24&255,h=l>>16&255,c=l>>8&255,u=255&l;s.uniform4f(this._uPickColor,u/255,c/255,h/255,A/255),s.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(s.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&s.drawArrays(s.TRIANGLES,0,n.positions.numItems)},Ii.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Ve(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0,s=!!e._geometry._state.compressGeometry,r=[];r.push("#version 300 es"),r.push("// Surface picking vertex shader"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),i&&(r.push("uniform bool clippable;"),r.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));r.push("uniform vec2 pickClipPos;"),r.push("vec4 remapClipPos(vec4 clipPos) {"),r.push(" clipPos.xy /= clipPos.w;"),r.push(" clipPos.xy -= pickClipPos;"),r.push(" clipPos.xy *= clipPos.w;"),r.push(" return clipPos;"),r.push("}"),r.push("out vec4 vColor;"),s&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),s&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),i&&r.push(" vWorldPosition = worldPosition;");r.push(" vColor = color;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = remapClipPos(clipPos);"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Surface picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),r.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = vColor;"),r.push("}"),r}(e)}}const Ti=c.vec3(),Ri=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Si(t),this._allocate(t)},Li={};Ri.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=Li[t];if(!i){if(i=new Ri(t,e),i.errors)return console.log(i.errors.join("\n")),null;Li[t]=i,p.memory.programs++}return i._useCount++,i},Ri.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Li[this._hash],p.memory.programs--)},Ri.prototype.webglContextRestored=function(){this._program=null},Ri.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,A=o.backfaces,h=o.frontface,c=i.camera.project,u=n._getPickTrianglePositions(),d=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,i.logarithmicDepthBufferEnabled){const e=2/(Math.log(c.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}if(s.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh occlusion vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push("}"),r}(e)}}const ki=c.vec3(),Oi=function(e,t){this._hash=e,this._shaderSource=new Ui(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ni={};Oi.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let i=Ni[t];if(!i){if(i=new Oi(t,e),i.errors)return console.log(i.errors.join("\n")),null;Ni[t]=i,p.memory.programs++}return i._useCount++,i},Oi.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ni[this._hash],p.memory.programs--)},Oi.prototype.webglContextRestored=function(){this._program=null},Oi.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._material._state,o=t._state,n=t._geometry._state,a=t.origin;if(r.alpha<1)return;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){const t=r.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=r.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),this._lastMaterialId=r.id}const l=i.camera;if(s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!e._geometry._state.compressGeometry,s=[];s.push("// Mesh shadow vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),s.push("uniform vec3 offset;"),i&&s.push("uniform mat4 positionsDecodeMatrix;");t&&s.push("out vec4 vWorldPosition;");s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),s.push("vec4 worldPosition;"),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;");s.push("worldPosition = modelMatrix * localPosition;"),s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&s.push("vWorldPosition = worldPosition;");return s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(e)}}const Vi=function(e,t){this._hash=e,this._shaderSource=new Qi(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Hi={};Vi.get=function(e){const t=e.scene,i=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=Hi[i];if(!s){if(s=new Vi(i,e),s.errors)return console.log(s.errors.join("\n")),null;Hi[i]=s,p.memory.programs++}return s._useCount++,s},Vi.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Hi[this._hash],p.memory.programs--)},Vi.prototype.webglContextRestored=function(){this._program=null},Vi.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene.canvas.gl,s=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.id!==this._lastMaterialId){const t=s.backfaces;e.backfaces!==t&&(t?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const r=s.frontface;e.frontface!==r&&(r?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=r),e.lineWidth!==s.lineWidth&&(i.lineWidth(s.lineWidth),e.lineWidth=s.lineWidth),this._uPointSize&&i.uniform1i(this._uPointSize,s.pointSize),this._lastMaterialId=s.id}if(i.uniformMatrix4fv(this._uModelMatrix,i.FALSE,t.worldMatrix),r.combineGeometry){const s=t.vertexBufs;s.id!==this._lastVertexBufsId&&(s.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(s.positionsBuf,s.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),this._lastVertexBufsId=s.id)}this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),i.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(i.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(i.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(i.drawArrays(i.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},Vi.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Ve(i,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a0)for(let i=0;i0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const ts=function(){const e=c.vec3(),t=c.vec3(),i=c.vec3(),s=c.vec3(),r=c.vec3(),o=c.vec3(),n=c.vec4(),a=c.vec3(),l=c.vec3(),A=c.vec3(),h=c.vec3(),u=c.vec3(),d=c.vec3(),p=c.vec3(),f=c.vec3(),g=c.vec3(),m=c.vec4(),_=c.vec4(),v=c.vec4(),b=c.vec3(),y=c.vec3(),x=c.vec3(),B=c.vec3(),w=c.vec3(),P=c.vec3(),C=c.vec3(),M=c.vec3(),E=c.vec3(),F=c.vec3(),I=c.vec3();return function(D,S,T,R,L){var U=L.primIndex;if(null!=U&&U>-1){const Q=D.geometry._state,V=D.scene,H=V.camera,j=V.canvas;if("triangles"===Q.primitiveName){L.primitive="triangle";const V=U,G=Q.indices,W=Q.positions;let K,X,J;if(G){var k=G[V+0],O=G[V+1],N=G[V+2];o[0]=k,o[1]=O,o[2]=N,L.indices=o,K=3*k,X=3*O,J=3*N}else K=3*V,X=K+3,J=X+3;if(i[0]=W[K+0],i[1]=W[K+1],i[2]=W[K+2],s[0]=W[X+0],s[1]=W[X+1],s[2]=W[X+2],r[0]=W[J+0],r[1]=W[J+1],r[2]=W[J+2],Q.compressGeometry){const e=Q.positionsDecodeMatrix;e&&(Vt.decompressPosition(i,e,i),Vt.decompressPosition(s,e,s),Vt.decompressPosition(r,e,r))}L.canvasPos?c.canvasPosToLocalRay(j.canvas,D.origin?z(S,D.origin):S,T,R,D.worldMatrix,L.canvasPos,e,t):L.origin&&L.direction&&c.worldRayToLocalRay(D.worldMatrix,L.origin,L.direction,e,t),c.normalizeVec3(t),c.rayPlaneIntersect(e,t,i,s,r,n),L.localPos=n,L.position=n,m[0]=n[0],m[1]=n[1],m[2]=n[2],m[3]=1,c.transformVec4(D.worldMatrix,m,_),a[0]=_[0],a[1]=_[1],a[2]=_[2],L.canvasPos&&D.origin&&(a[0]+=D.origin[0],a[1]+=D.origin[1],a[2]+=D.origin[2]),L.worldPos=a,c.transformVec4(H.matrix,_,v),l[0]=v[0],l[1]=v[1],l[2]=v[2],L.viewPos=l,c.cartesianToBarycentric(n,i,s,r,A),L.bary=A;const Y=Q.normals;if(Y){if(Q.compressGeometry){const e=3*k,t=3*O,i=3*N;Vt.decompressNormal(Y.subarray(e,e+2),h),Vt.decompressNormal(Y.subarray(t,t+2),u),Vt.decompressNormal(Y.subarray(i,i+2),d)}else h[0]=Y[K],h[1]=Y[K+1],h[2]=Y[K+2],u[0]=Y[X],u[1]=Y[X+1],u[2]=Y[X+2],d[0]=Y[J],d[1]=Y[J+1],d[2]=Y[J+2];const e=c.addVec3(c.addVec3(c.mulVec3Scalar(h,A[0],b),c.mulVec3Scalar(u,A[1],y),x),c.mulVec3Scalar(d,A[2],B),w);L.worldNormal=c.normalizeVec3(c.transformVec3(D.worldNormalMatrix,e,P))}const Z=Q.uv;if(Z){if(p[0]=Z[2*k],p[1]=Z[2*k+1],f[0]=Z[2*O],f[1]=Z[2*O+1],g[0]=Z[2*N],g[1]=Z[2*N+1],Q.compressGeometry){const e=Q.uvDecodeMatrix;e&&(Vt.decompressUV(p,e,p),Vt.decompressUV(f,e,f),Vt.decompressUV(g,e,g))}L.uv=c.addVec3(c.addVec3(c.mulVec2Scalar(p,A[0],C),c.mulVec2Scalar(f,A[1],M),E),c.mulVec2Scalar(g,A[2],F),I)}}}}}();function is(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);let s=e.height||1;s<0&&(console.error("negative height not allowed - will invert"),s*=-1);let r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<3&&(r=3);let o=e.heightSegments||1;o<0&&(console.error("negative heightSegments not allowed - will invert"),o*=-1),o<1&&(o=1);const n=!!e.openEnded;let a=e.center;const l=a?a[0]:0,A=a?a[1]:0,h=a?a[2]:0,c=s/2,u=s/o,d=2*Math.PI/r,p=1/r,f=(t-i)/o,g=[],m=[],v=[],b=[];let y,x,B,w,P,C,M,E,F,I,D;const S=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(y=0;y<=o;y++)for(P=t-y*f,C=c-y*u,x=0;x<=r;x++)B=Math.sin(x*d),w=Math.cos(x*d),m.push(P*B),m.push(S),m.push(P*w),v.push(x*p),v.push(1*y/o),g.push(P*B+l),g.push(C+A),g.push(P*w+h);for(y=0;y0){for(F=g.length/3,m.push(0),m.push(1),m.push(0),v.push(.5),v.push(.5),g.push(0+l),g.push(c+A),g.push(0+h),x=0;x<=r;x++)B=Math.sin(x*d),w=Math.cos(x*d),I=.5*Math.sin(x*d)+.5,D=.5*Math.cos(x*d)+.5,m.push(t*B),m.push(1),m.push(t*w),v.push(I),v.push(D),g.push(t*B+l),g.push(c+A),g.push(t*w+h);for(x=0;x0){for(F=g.length/3,m.push(0),m.push(-1),m.push(0),v.push(.5),v.push(.5),g.push(0+l),g.push(0-c+A),g.push(0+h),x=0;x<=r;x++)B=Math.sin(x*d),w=Math.cos(x*d),I=.5*Math.sin(x*d)+.5,D=.5*Math.cos(x*d)+.5,m.push(i*B),m.push(-1),m.push(i*w),v.push(I),v.push(D),g.push(i*B+l),g.push(0-c+A),g.push(i*w+h);for(x=0;x":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function os(e={}){var t=e.origin||[0,0,0],i=t[0],s=t[1],r=t[2],o=e.size||1,n=[],a=[],l=e.text;_.isNumeric(l)&&(l=""+l);for(var A,h,c,u,d,p,f,g,m,v=(l||"").split("\n"),b=0,y=0,x=.04,B=0;B0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let i=0,s=e.length;i1;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);const o=ws(i,this.wrapS);o&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,o);const n=ws(i,this.wrapT);if(n&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,n),this.type===i.TEXTURE_3D||this.type===i.TEXTURE_2D_ARRAY){const e=ws(i,this.wrapR);e&&i.texParameteri(this.target,i.TEXTURE_WRAP_R,e),i.texParameteri(this.type,i.TEXTURE_WRAP_R,e)}r?(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,Es(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,Es(i,this.magFilter))):(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,ws(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,ws(i,this.magFilter)));const a=ws(i,this.format,this.encoding),l=ws(i,this.type),A=Ms(i,this.internalFormat,a,l,this.encoding,!1);i.texStorage2D(i.TEXTURE_2D,s,A,e[0].width,e[0].height);for(let t=0,s=e.length;t>t;return e+1}class Ss extends D{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new lt({texture:new Cs({gl:this.scene.canvas.gl}),matrix:c.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=c.vec2([0,0]),this._scale=c.vec2([1,1]),this._rotate=c.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),p.memory.textures++}_checkMinFilter(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}_checkMagFilter(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}_checkWrapS(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkWrapT(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this._state.texture=new Cs({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,i;0===this._translate[0]&&0===this._translate[1]||(t=c.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(i=c.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?c.mulMat4(t,i):i),0!==this._rotate&&(i=c.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?c.mulMat4(t,i):i),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=Fs(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let i=new Image;i.onload=function(){i=Fs(i),t._state.texture.setImage(i,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),p.memory.textures--}}const Ts=p.memory,Rs=c.AABB3();class Ls extends Tt{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new lt({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._aabb=null,this._obb=c.OBB3();const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=Vt.getPositionsBounds(t.positions),o=Vt.compressPositions(t.positions,e.min,e.max);r=o.quantized,i.positionsDecodeMatrix=o.decodeMatrix,i.positionsBuf=new He(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),Ts.positions+=i.positionsBuf.numItems,c.positions3ToAABB3(t.positions,this._aabb),c.positions3ToAABB3(r,Rs,i.positionsDecodeMatrix),c.AABB3ToOBB3(Rs,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);i.colorsBuf=new He(s,s.ARRAY_BUFFER,e,e.length,4,s.STATIC_DRAW),Ts.colors+=i.colorsBuf.numItems}if(t.uv){const e=Vt.getUVBounds(t.uv),r=Vt.compressUVs(t.uv,e.min,e.max),o=r.quantized;i.uvDecodeMatrix=r.decodeMatrix,i.uvBuf=new He(s,s.ARRAY_BUFFER,o,o.length,2,s.STATIC_DRAW),Ts.uvs+=i.uvBuf.numItems}if(t.normals){const e=Vt.compressNormals(t.normals);let r=i.compressGeometry;i.normalsBuf=new He(s,s.ARRAY_BUFFER,e,e.length,3,s.STATIC_DRAW,r),Ts.normals+=i.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);i.indicesBuf=new He(s,s.ELEMENT_ARRAY_BUFFER,e,e.length,1,s.STATIC_DRAW),Ts.indices+=i.indicesBuf.numItems;const o=Rt(r,e,i.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new He(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),Ts.meshes++}else this.error("Config expected: indices");else this.error("Config expected: positions")}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positionsBuf&&t.push("p"),e.colorsBuf&&t.push("c"),(e.normalsBuf||e.autoVertexNormals)&&t.push("n"),e.uvBuf&&t.push("u"),t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf}get primitive(){return this._state.primitiveName}get aabb(){return this._aabb}get obb(){return this._obb}get numTriangles(){return this._numTriangles}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),e.destroy(),Ts.meshes--}}var Us={};function ks(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return _.apply(e,{primitive:"lines",positions:[l,A,h,l,A,d,l,u,h,l,u,d,c,A,h,c,A,d,c,u,h,c,u,d],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function Os(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let i=e.divisions||1;i<0&&(console.error("negative divisions not allowed - will invert"),i*=-1),i<1&&(i=1),t=t||10,i=i||10;const s=t/i,r=t/2,o=[],n=[];let a=0;for(let e=0,t=-r;e<=i;e++,t+=s)o.push(-r),o.push(0),o.push(t),o.push(r),o.push(0),o.push(t),o.push(t),o.push(0),o.push(-r),o.push(t),o.push(0),o.push(r),n.push(a++),n.push(a++),n.push(a++),n.push(a++);return _.apply(e,{primitive:"lines",positions:o,indices:n})}function Ns(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);let s=e.xSegments||1;s<0&&(console.error("negative xSegments not allowed - will invert"),s*=-1),s<1&&(s=1);let r=e.xSegments||1;r<0&&(console.error("negative zSegments not allowed - will invert"),r*=-1),r<1&&(r=1);const o=e.center,n=o?o[0]:0,a=o?o[1]:0,l=o?o[2]:0,A=t/2,h=i/2,c=Math.floor(s)||1,u=Math.floor(r)||1,d=c+1,p=u+1,f=t/c,g=i/u,m=new Float32Array(d*p*3),v=new Float32Array(d*p*3),b=new Float32Array(d*p*2);let y,x,B,w,P,C,M,E=0,F=0;for(y=0;y65535?Uint32Array:Uint16Array)(c*u*6);for(y=0;y360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const A=n?n[2]:0,h=[],u=[],d=[],p=[];let f,g,m,v,b,y,x,B,w,P,C,M;for(B=0;B<=r;B++)for(x=0;x<=s;x++)f=x/s*o,g=.785398+B/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),m=(t+i*Math.cos(g))*Math.cos(f),v=(t+i*Math.cos(g))*Math.sin(f),b=i*Math.sin(g),h.push(m+a),h.push(v+l),h.push(b+A),d.push(1-x/s),d.push(B/r),y=c.normalizeVec3(c.subVec3([m,v,b],[a,l,A],[]),[]),u.push(y[0]),u.push(y[1]),u.push(y[2]);for(B=1;B<=r;B++)for(x=1;x<=s;x++)w=(s+1)*B+x-1,P=(s+1)*(B-1)+x-1,C=(s+1)*(B-1)+x,M=(s+1)*B+x,p.push(w),p.push(P),p.push(C),p.push(C),p.push(M),p.push(w);return _.apply(e,{positions:h,normals:u,uv:d,indices:p})}function Vs(e={}){if(e.points.length%3!=0)throw"Size of points array for given polyline should be divisible by 3";let t=e.points.length/3;if(t<2)throw"There should be at least 2 points to create a polyline";let i=[];for(let e=0;e>8},Us.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},Us.parse={},Us.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",s=0;sr&&(r=l),Ao&&(o=A),hn&&(n=h)}return{min:{x:t,y:i,z:s},max:{x:r,y:o,z:n}}};class Hs extends D{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=c.vec3(t.pos||[0,0,0]),this._up=c.vec3(t.up||[0,1,0]),this._normal=c.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=c.vec3(),this._rtcPos=c.vec3(),this._imageSize=c.vec2(),this._texture=new Ss(this,{flipY:!0}),this._image=new Image,"jpg"!==this._type&&"png"!==this._type&&(this.error('Unsupported type - defaulting to "jpg"'),this._type="jpg"),this._node=new gs(this,{matrix:c.inverseMat4(c.lookAtMat4v(this._pos,c.subVec3(this._pos,this._normal,c.mat4()),this._up,c.mat4())),children:[this._bitmapMesh=new es(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new Gt(this,Ns({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Jt(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0})})]}),t.image?this.image=t.image:t.src?this.src=t.src:t.imageData&&(this.imageData=t.imageData),this.scene._bitmapCreated(this)}set visible(e){this._bitmapMesh.visible=e}get visible(){return this._bitmapMesh.visible}set image(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}get image(){return this._image}set src(e){if(e){this._image.onload=()=>{this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale()},this._image.src=e;switch(e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}}get src(){return this._image.src}set imageData(e){this._image.onload=()=>{this._texture.image=image,this._imageSize[0]=image.width,this._imageSize[1]=image.height,this._updateBitmapMeshScale()},this._image.src=e}get imageData(){const e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")}set type(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}get type(){return this._type}get pos(){return this._pos}get normal(){return this._normal}get up(){return this._up}set height(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}get height(){return this._height}set collidable(e){this._bitmapMesh.collidable=!1!==e}get collidable(){return this._bitmapMesh.collidable}set clippable(e){this._bitmapMesh.clippable=!1!==e}get clippable(){return this._bitmapMesh.clippable}set pickable(e){this._bitmapMesh.pickable=!1!==e}get pickable(){return this._bitmapMesh.pickable}set opacity(e){this._bitmapMesh.opacity=e}get opacity(){return this._bitmapMesh.opacity}destroy(){super.destroy(),this.scene._bitmapDestroyed(this)}_updateBitmapMeshScale(){const e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height/e,1,this._height]}}const js=(e,t)=>{const i=[];let s=[];function r(e,i){let s,r;for(let o=0;o<3;o++)if(s=t[3*e+o],r=t[3*i+o],s!==r)return r-s;return 0}let o=e.slice().sort(r),n=null;for(let e=0,t=o.length;eo&&r>n?o>n?(a=r,l=o,A=n):(a=r,l=n,A=o):o>r&&o>n?r>n?(a=o,l=r,A=n):(a=o,l=n,A=r):n>r&&n>o&&(r>o?(a=n,l=r,A=o):(a=n,l=o,A=r)),s[t+0]=[a,l],s[t+1]=[l,A],a>A){const e=A;A=a,a=e}s[t+2]=[A,a]}function a(e,t){let i,s;for(let r=0;r<2;r++)if(i=e[r],s=t[r],s!==i)return s-i;return 0}s=s.slice(0,e.length),s.sort(a);let l=0;for(let e=0;e0&&2!==l)},Gs=c.vec3(),zs=c.vec3(),Ws=c.vec3();class Ks{constructor(){this.vertices=[],this.indices=[],this.reset()}reset(){this.lenVertices=0,this.lenIndices=0,this.primitive=null}setPrimitive(e){this.primitive=e}addVertex(e){this.vertices[this.lenVertices++]=e[0],this.vertices[this.lenVertices++]=e[1],this.vertices[this.lenVertices++]=e[2]}addIndex(e){this.indices[this.lenIndices++]=e}get volume(){const e=this.vertices,t=this.indices;if("solid"!==this.primitive&&"surface"!==this.primitive&&"triangles"!==this.primitive)return-1;if("solid"!==this.primitive&&!js(t,e))return-1;let i=0;for(let s=0;s{Xs.addVertex(e)})),this.getEachIndex((e=>{Xs.addIndex(e)})),this._volume=Xs.volume;break;default:this._volume=0}return this._volume}get surfaceArea(){if(null!==this._surfaceArea)return this._surfaceArea;switch(this.layer.primitive){case"solid":case"surface":case"triangles":ir.reset(),this.getEachVertex((e=>{ir.addVertex(e)})),this.getEachIndex((e=>{ir.addIndex(e)})),this._surfaceArea=ir.surfaceArea;break;default:this._surfaceArea=0}return this._surfaceArea}set aabb(e){if(this._aabbLocal=e,this.origin){this._aabbLocal=e.slice(0);const t=this.origin;this._aabbLocal[0]+=t[0],this._aabbLocal[1]+=t[1],this._aabbLocal[2]+=t[2],this._aabbLocal[3]+=t[0],this._aabbLocal[4]+=t[1],this._aabbLocal[5]+=t[2]}}get aabb(){return this._aabbWorldDirty&&(c.AABB3ToOBB3(this._aabbLocal,sr),this.transform?(c.transformOBB3(this.transform.worldMatrix,sr,rr),c.transformOBB3(this.model.worldMatrix,rr,or),c.OBB3ToAABB3(or,this._aabbWorld)):(c.transformOBB3(this.model.worldMatrix,sr,rr),c.OBB3ToAABB3(rr,this._aabbWorld)),this._aabbWorldDirty=!1),this._aabbWorld}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const ar=new class{constructor(){this._uint8Arrays={},this._float32Arrays={}}_clear(){this._uint8Arrays={},this._float32Arrays={}}getUInt8Array(e){let t=this._uint8Arrays[e];return t||(t=new Uint8Array(e),this._uint8Arrays[e]=t),t}getFloat32Array(e){let t=this._float32Arrays[e];return t||(t=new Float32Array(e),this._float32Arrays[e]=t),t}};let lr=0;const Ar={NOT_RENDERED:0,COLOR_OPAQUE:1,COLOR_TRANSPARENT:2,SILHOUETTE_HIGHLIGHTED:3,SILHOUETTE_SELECTED:4,SILHOUETTE_XRAYED:5,EDGES_COLOR_OPAQUE:6,EDGES_COLOR_TRANSPARENT:7,EDGES_HIGHLIGHTED:8,EDGES_SELECTED:9,EDGES_XRAYED:10,PICK:11},hr=new Float32Array([1,1,1,1]),cr=new Float32Array([0,0,0,1]),ur=c.vec4(),dr=c.vec3(),pr=c.vec3(),fr=c.mat4();class gr{constructor(e,t=!1,{instancing:i=!1,edges:s=!1,useAlphaCutoff:r=!1}={}){this._scene=e,this._withSAO=t,this._instancing=i,this._edges=s,this._useAlphaCutoff=r,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}_getHash(){return this._scene._sectionPlanesState.getHash()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){return[""]}_buildFragmentShader(){return[""]}_addMatricesUniformBlockLines(e,t=!1){return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}_addRemapClipPosLines(e,t=1){return e.push("uniform vec2 drawingBufferSize;"),e.push("uniform vec2 pickClipPos;"),e.push("vec4 remapClipPos(vec4 clipPos) {"),e.push(" clipPos.xy /= clipPos.w;"),1===t?e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"):e.push(` clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(${t}));`),e.push(" clipPos.xy *= clipPos.w;"),e.push(" return clipPos;"),e.push("}"),e}getValid(){return this._hash===this._getHash()}setSectionPlanesStateUniforms(e){const t=this._scene,{gl:i}=t.canvas,{model:s,layerIndex:r}=e,o=t._sectionPlanesState.getNumAllocatedSectionPlanes(),n=t._sectionPlanesState.sectionPlanes.length;if(o>0){const a=t._sectionPlanesState.sectionPlanes,l=r*n,A=s.renderFlags;t.crossSections&&(i.uniform4fv(this._uSliceColor,t.crossSections.sliceColor),i.uniform1f(this._uSliceThickness,t.crossSections.sliceThickness));for(let t=0;t0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0&&p.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,p.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),p.lightMaps.length>0&&p.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,p.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const i=a.drawingBufferWidth,s=a.drawingBufferHeight;ur[0]=i,ur[1]=s,ur[2]=t.blendCutoff,ur[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,ur),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(this._useAlphaCutoff&&a.uniform1f(this._alphaCutoffLocation,h.alphaCutoff),s){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(i===Ar[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const i=n.xrayMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===Ar[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const i=n.highlightMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===Ar[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const i=n.selectedMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else a.uniform4fv(this._uColor,this._edges?cr:hr)}this._draw({state:l,frameCtx:e,incrementDrawState:r}),a.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,p.memory.programs--}}class mr extends gr{constructor(e,t,{edges:i=!1,useAlphaCutoff:s=!1}={}){super(e,t,{instancing:!1,edges:i,useAlphaCutoff:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;if(this._edges)t.drawElements(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0);else{const e=s.pickElementsCount||i.indicesBuf.numItems,o=s.pickElementsOffset?s.pickElementsOffset*i.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,i.indicesBuf.itemType,o),r&&s.drawElements++}}}class _r extends mr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r;const o=[];o.push("#version 300 es"),o.push("// Triangles batching draw vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;")),o.push("out vec4 vColor;"),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching draw fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class vr extends mr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._lightsState,i=e._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching flat-shading draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),s){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e sliceThickness) { "),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" newColor = sliceColor;"),r.push(" }"),r.push("}")}r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;"),r.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),r.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),r.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,i=t.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching silhouette fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r){for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" newColor = sliceColor;"),o.push(" }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = newColor;"),o.push("}"),o}}class yr extends mr{constructor(e){super(e,!1,{instancing:!1,edges:!0})}}class xr extends yr{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Br extends yr{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class wr extends mr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class Pr extends mr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Cr extends mr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec3 worldNormal = octDecode(normal.xy); "),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class Mr extends mr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching occlusion vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class Er extends mr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching depth fragment shader"),s.push("precision highp float;"),s.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),s.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),s.push("}"),s}}class Fr extends mr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class Ir extends mr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry shadow vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" int colorFlag = int(flags) & 0xF;"),i.push(" bool visible = (colorFlag > 0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}}class Dr extends mr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Triangles batching quality draw vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),o.push("vFragDepth = 1.0 + clipPos.w;")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Triangles batching quality draw fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),n.push("uniform sampler2D uAOMap;"),n.push("in vec4 vViewPosition;"),n.push("in vec3 vViewNormal;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("in vec2 vMetallicRoughness;"),s.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick flat normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick flat normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class Tr extends mr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching color texture vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=this._useAlphaCutoff,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching color texture fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Qr=c.vec3(),Vr=c.vec3(),Hr=c.vec3(),jr=c.vec3(),Gr=c.mat4();class zr extends gr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Qr;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Vr;if(l){const e=Hr;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=z(p,t,Gr),m=jr,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElements(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Wr{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._colorTextureRendererAlphaCutoff&&!this._colorTextureRendererAlphaCutoff.getValid()&&(this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererAlphaCutoff=null),this._colorTextureRendererWithSAOAlphaCutoff&&!this._colorTextureRendererWithSAOAlphaCutoff.getValid()&&(this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new br(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new wr(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new Pr(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Nr(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new zr(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new _r(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new _r(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new vr(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new vr(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Tr(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Tr(this._scene,!0)),this._colorTextureRendererWithSAO}get colorTextureRendererAlphaCutoff(){return this._colorTextureRendererAlphaCutoff||(this._colorTextureRendererAlphaCutoff=new Tr(this._scene,!1,{useAlphaCutoff:!0})),this._colorTextureRendererAlphaCutoff}get colorTextureRendererWithSAOAlphaCutoff(){return this._colorTextureRendererWithSAOAlphaCutoff||(this._colorTextureRendererWithSAOAlphaCutoff=new Tr(this._scene,!0,{useAlphaCutoff:!0})),this._colorTextureRendererWithSAOAlphaCutoff}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new Dr(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Dr(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new br(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Er(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Fr(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new xr(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Br(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new wr(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Cr(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Sr(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Pr(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Mr(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Ir(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new zr(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Nr(this._scene)),this._snapInitRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererAlphaCutoff&&this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff&&this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Kr={};let Xr=65536,Jr=5e6;class Yr{constructor(){}set doublePrecisionEnabled(e){c.setDoublePrecisionEnabled(e)}get doublePrecisionEnabled(){return c.getDoublePrecisionEnabled()}set maxDataTextureHeight(e){(e=1024*Math.ceil(e/1024))>4096?e=4096:e<1024&&(e=1024),Xr=e}get maxDataTextureHeight(){return Xr}set maxGeometryBatchSize(e){e<1e5?e=1e5:e>5e6&&(e=5e6),Jr=e}get maxGeometryBatchSize(){return Jr}}const Zr=new Yr;class qr{constructor(e=Zr.maxGeometryBatchSize){this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const $r=c.mat4(),eo=c.mat4();function to(e,t,i){const s=e.length,r=new Uint16Array(s),o=t[0],n=t[1],a=t[2],l=t[3]-o,A=t[4]-n,h=t[5]-a,u=65525,d=u/l,p=u/A,f=u/h,g=e=>e>=0?e:0;for(let t=0;t=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 ro(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}const oo=c.mat4(),no=c.mat4(),ao=c.vec4([0,0,0,1]),lo=c.vec3(),Ao=c.vec3(),ho=c.vec3(),co=c.vec3(),uo=c.vec3(),po=c.vec3(),fo=c.vec3();class go{constructor(e){this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Kr[t];return i||(i=new Wr(e),Kr[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Kr[t],i._destroy()}))),i}(e.model.scene),this._buffer=new qr(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new lt({origin:c.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:e.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=c.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=c.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=c.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.solid=!!e.solid,this.primitive=e.primitive}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)for(let e=0,t=o.length;e0){const e=oo;m?c.inverseMat4(c.transposeMat4(m,no),e):c.identityMat4(e,e),function(e,t,i,s,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,A,h,u,d=new Float32Array([0,0,0,0]),p=new Float32Array([0,0,0,0]);for(u=0;uh&&(l=n,h=A),n=so(p,"floor","ceil"),a=ro(n),A=o(p,a),A>h&&(l=n,h=A),n=so(p,"ceil","ceil"),a=ro(n),A=o(p,a),A>h&&(l=n,h=A),s[r+u+0]=l[0],s[r+u+1]=l[1],s[r+u+2]=0}(e,r,r.length,b.normals,b.normals.length)}if(l)for(let e=0,t=l.length;e0)for(let e=0,t=n.length;e0)for(let e=0,t=a.length;e0){const s=this._state.positionsDecodeMatrix?new Uint16Array(i.positions):to(i.positions,this._modelAABB,this._state.positionsDecodeMatrix=c.mat4());if(e.positionsBuf=new He(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this.model.scene.readableGeometryEnabled)for(let e=0,t=this._portions.length;e0){const s=new Int8Array(i.normals);let r=!0;e.normalsBuf=new He(t,t.ARRAY_BUFFER,s,i.normals.length,3,t.STATIC_DRAW,r)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new He(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.uv.length>0)if(e.uvDecodeMatrix){let s=!1;e.uvBuf=new He(t,t.ARRAY_BUFFER,i.uv,i.uv.length,2,t.STATIC_DRAW,s)}else{const s=Vt.getUVBounds(i.uv),r=Vt.compressUVs(i.uv,s.min,s.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=c.mat3(r.decodeMatrix),e.uvBuf=new He(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(i.metallicRoughness.length>0){const s=new Uint8Array(i.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new He(t,t.ARRAY_BUFFER,s,i.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s),o=!1;e.flagsBuf=new He(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new He(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new He(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new He(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){const s=new Uint32Array(i.edgeIndices);e.edgeIndicesBuf=new He(t,t.ELEMENT_ARRAY_BUFFER,s,i.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,i){t&J&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&te&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ee&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ie&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&q&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&se&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&Z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Y&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&q?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&Y?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=e,s=this._portions[i],r=4*s.vertsBaseIndex,o=4*s.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],A=t[2],h=t[3];for(let e=0;e_)&&(_=e,s.set(v),r&&c.triangleNormal(p,f,g,r),m=!0)}}return m&&r&&(c.transformVec3(this.model.worldNormalMatrix,r,r),c.normalizeVec3(r)),m}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}class mo extends gr{constructor(e,t,{edges:i=!1,useAlphaCutoff:s=!1}={}){super(e,t,{instancing:!0,edges:i,useAlphaCutoff:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;this._edges?t.drawElementsInstanced(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0,i.numInstances):(t.drawElementsInstanced(t.TRIANGLES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),r&&s.drawElements++)}}class _o extends mo{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r,o,n;const a=[];for(a.push("#version 300 es"),a.push("// Instancing geometry drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec2 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;"),r=0,o=i.lights.length;r= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),s&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),a.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),r=0,o=i.lights.length;r0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class vo extends mo{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry flat-shading drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState;let s,r;const o=t.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry flat-shading drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),o){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}for(n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),s=0,r=i.lights.length;s0,i=[];return i.push("#version 300 es"),i.push("// Instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing fill fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = newColor;"),s.push("}"),s}}class yo extends mo{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class xo extends yo{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Bo extends yo{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesColorRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class wo extends mo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class Po extends mo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Co extends mo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec2 normal;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("in vec4 modelNormalMatrixCol0;"),i.push("in vec4 modelNormalMatrixCol1;"),i.push("in vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class Mo extends mo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class Eo extends mo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Instancing geometry depth drawing fragment shader"),o.push("precision highp float;"),o.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),o.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),o.push("}"),o}}class Fo extends mo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class Io extends mo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const Do={3e3:"linearToLinear",3001:"sRGBToLinear"};class So extends mo{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Instancing geometry quality drawing vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),o.push("in vec4 modelMatrixCol0;"),o.push("in vec4 modelMatrixCol1;"),o.push("in vec4 modelMatrixCol2;"),o.push("in vec4 modelNormalMatrixCol0;"),o.push("in vec4 modelNormalMatrixCol1;"),o.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),o.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),o.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Instancing geometry quality drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),n.push("#define PI 3.14159265359"),n.push("#define RECIPROCAL_PI 0.31830988618"),n.push("#define RECIPROCAL_PI2 0.15915494"),n.push("#define EPSILON 1e-6"),n.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),n.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),n.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),n.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),n.push(" return normalize(surf_norm );"),n.push(" }"),n.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),n.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),n.push(" vec2 st0 = dFdx( uv.st );"),n.push(" vec2 st1 = dFdy( uv.st );"),n.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),n.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),n.push(" vec3 N = normalize( surf_norm );"),n.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),n.push(" mat3 tsn = mat3( S, T, N );"),n.push(" return normalize( tsn * mapN );"),n.push("}"),n.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),n.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),n.push("}"),n.push("struct IncidentLight {"),n.push(" vec3 color;"),n.push(" vec3 direction;"),n.push("};"),n.push("struct ReflectedLight {"),n.push(" vec3 diffuse;"),n.push(" vec3 specular;"),n.push("};"),n.push("struct Geometry {"),n.push(" vec3 position;"),n.push(" vec3 viewNormal;"),n.push(" vec3 worldNormal;"),n.push(" vec3 viewEyeDir;"),n.push("};"),n.push("struct Material {"),n.push(" vec3 diffuseColor;"),n.push(" float specularRoughness;"),n.push(" vec3 specularColor;"),n.push(" float shine;"),n.push("};"),n.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),n.push(" float r = ggxRoughness + 0.0001;"),n.push(" return (2.0 / (r * r) - 2.0);"),n.push("}"),n.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),n.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),n.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),n.push("}"),s.reflectionMaps.length>0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = "+Do[s.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = "+Do[s.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&i.push("out float vFlags;"),i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&i.push("vFlags = flags;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class Ro extends mo{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=this._useAlphaCutoff,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Vo=c.vec3(),Ho=c.vec3(),jo=c.vec3(),Go=c.vec3(),zo=c.mat4();class Wo extends gr{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Vo;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Ho;if(l){const e=c.transformPoint3(h,l,jo);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=z(p,t,zo),m=Go,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0,a.numInstances),a.edgeIndicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Ko{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._colorTextureRendererAlphaCutoff&&!this._colorTextureRendererAlphaCutoff.getValid()&&(this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererAlphaCutoff=null),this._colorTextureRendererWithSAOAlphaCutoff&&!this._colorTextureRendererWithSAOAlphaCutoff.getValid()&&(this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new bo(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new wo(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new Po(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Qo(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Wo(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new _o(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new _o(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new vo(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new vo(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Ro(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Ro(this._scene,!0)),this._colorTextureRendererWithSAO}get colorTextureRendererAlphaCutoff(){return this._colorTextureRendererAlphaCutoff||(this._colorTextureRendererAlphaCutoff=new Ro(this._scene,!1,{useAlphaCutoff:!0})),this._colorTextureRendererAlphaCutoff}get colorTextureRendererWithSAOAlphaCutoff(){return this._colorTextureRendererWithSAOAlphaCutoff||(this._colorTextureRendererWithSAOAlphaCutoff=new Ro(this._scene,!0,{useAlphaCutoff:!0})),this._colorTextureRendererWithSAOAlphaCutoff}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new So(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new So(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new bo(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Eo(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Fo(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new xo(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Bo(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new wo(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Co(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new To(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Po(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Mo(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Io(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Wo(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Qo(this._scene)),this._snapInitRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererAlphaCutoff&&this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff&&this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Xo={};const Jo=new Uint8Array(4),Yo=new Float32Array(1),Zo=c.vec4([0,0,0,1]),qo=new Float32Array(3),$o=c.vec3(),en=c.vec3(),tn=c.vec3(),sn=c.vec3(),rn=c.vec3(),on=c.vec3(),nn=c.vec3(),an=new Float32Array(4);class ln{constructor(e){this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Xo[t];return i||(i=new Ko(e),Xo[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Xo[t],i._destroy()}))),i}(e.model.scene),this._aabb=c.collapseAABB3(),this._state=new lt({numInstances:0,obb:c.OBB3(),origin:c.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrix=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.solid=!!e.solid,this.numIndices=e.geometry.numIndices,this.primitive=e.geometry.primitive}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;e.colorsBuf=new He(s,s.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,s.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let i=!1;e.metallicRoughnessBuf=new He(s,s.ARRAY_BUFFER,t,this._metallicRoughness.length,2,s.STATIC_DRAW,i)}if(o>0){let t=!1;e.flagsBuf=new He(s,s.ARRAY_BUFFER,new Float32Array(o),o,1,s.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new He(s,s.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,s.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const i=!1;e.positionsBuf=new He(s,s.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,s.STATIC_DRAW,i),e.positionsDecodeMatrix=c.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const i=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new He(s,s.ARRAY_BUFFER,i,i.length,4,s.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const i=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new He(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new He(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,s.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new He(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,s.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new He(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelMatrixCol1Buf=new He(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelMatrixCol2Buf=new He(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new He(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new He(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new He(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new He(s,s.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,s.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&i&&i.colorTexture&&i.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!i&&!!i.colorTexture,this.model.scene.readableGeometryEnabled||(this._state.geometry=null),this._finalized=!0}initFlags(e,t,i){t&J&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&te&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ee&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ie&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&q&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&se&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&Z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Y&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&q?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&Y?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";Jo[0]=t[0],Jo[1]=t[1],Jo[2]=t[2],Jo[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(Jo,4*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&J),r=!!(t&ee),o=!!(t&te),n=!!(t&ie),a=!!(t&se),l=!!(t&Z),A=!!(t&Y);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Ar.NOT_RENDERED:i?Ar.COLOR_TRANSPARENT:Ar.COLOR_OPAQUE,c=!s||A?Ar.NOT_RENDERED:n?Ar.SILHOUETTE_SELECTED:o?Ar.SILHOUETTE_HIGHLIGHTED:r?Ar.SILHOUETTE_XRAYED:Ar.NOT_RENDERED;let u=0;u=!s||A?Ar.NOT_RENDERED:n?Ar.EDGES_SELECTED:o?Ar.EDGES_HIGHLIGHTED:r?Ar.EDGES_XRAYED:a?i?Ar.EDGES_COLOR_TRANSPARENT:Ar.EDGES_COLOR_OPAQUE:Ar.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Ar.PICK:Ar.NOT_RENDERED)<<12,d|=(t&q?1:0)<<16,Yo[0]=d,this._state.flagsBuf&&this._state.flagsBuf.setData(Yo,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(qo[0]=t[0],qo[1]=t[1],qo[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(qo,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.readableGeometryEnabled)return!1;const i=this._state,s=i.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=s.positionsCompressed,n=i.origin,a=n[0],l=n[1],A=n[2],h=Zo,u=r.matrix,d=this.model.matrix,p=i.positionsDecodeMatrix;for(let e=0,i=o.length;ev)&&(v=e,s.set(b),r&&c.triangleNormal(f,g,m,r),_=!0)}}return _&&r&&(c.transformVec3(a.normalMatrix,r,r),c.transformVec3(this.model.worldNormalMatrix,r,r),c.normalizeVec3(r)),_}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}class An extends gr{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawElements(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0),r&&s.drawElements++}}class hn extends An{drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class cn extends An{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const un=c.vec3(),dn=c.vec3(),pn=c.vec3(),fn=c.vec3(),gn=c.mat4();class mn extends gr{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=un;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=dn;if(l){const e=pn;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=z(p,t,gn),m=fn,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const _n=c.vec3(),vn=c.vec3(),bn=c.vec3(),yn=c.vec3(),xn=c.mat4();class Bn extends gr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=_n;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=vn;if(l){const e=bn;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=z(p,t,xn),m=yn,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class wn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new hn(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new cn(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new mn(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Bn(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Pn={};class Cn{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}class Mn{constructor(e){this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Pn[t];return i||(i=new wn(e),Pn[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Pn[t],i._destroy()}))),i}(e.model.scene),this.model=e.model,this._buffer=new Cn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new lt({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:c.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=c.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=c.vec3(e.origin)),this.primitive=e.primitive}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new He(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=to(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new He(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new He(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.colors.length>0){const s=i.colors.length/4,r=new Float32Array(s);let o=!1;e.flagsBuf=new He(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new He(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new He(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&J&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&te&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ee&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ie&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&q&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&se&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&Z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Y&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&q?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&Y?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],A=t[3];for(let e=0;e0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 lightAmbient;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Lines instancing color fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),o.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):o.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class In extends En{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const Dn=c.vec3(),Sn=c.vec3(),Tn=c.vec3();c.vec3();const Rn=c.mat4();class Ln extends gr{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Dn;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Sn;if(l){const e=c.transformPoint3(h,l,Tn);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=z(p,t,Rn),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),a.indicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Un=c.vec3(),kn=c.vec3(),On=c.vec3();c.vec3();const Nn=c.mat4();class Qn extends gr{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Un;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=kn;if(l){const e=c.transformPoint3(h,l,On);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=z(p,t,Nn),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Vn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._snapInitRenderer||(this._snapInitRenderer=new Ln(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Qn(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Fn(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new In(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Ln(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Qn(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Hn={};const jn=new Uint8Array(4),Gn=new Float32Array(1),zn=new Float32Array(3),Wn=new Float32Array(4);class Kn{constructor(e){this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Hn[t];return i||(i=new Vn(e),Hn[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Hn[t],i._destroy()}))),i}(e.model.scene),this._aabb=c.collapseAABB3(),this._state=new lt({obb:c.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,e.origin&&(this._state.origin=c.vec3(e.origin)),this._finalized=!1,this.primitive=e.primitive}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;this._state.colorsBuf=new He(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(r>0){let t=!1;this._state.flagsBuf=new He(e,e.ARRAY_BUFFER,new Float32Array(r),r,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new He(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.colorsCompressed&&i.colorsCompressed.length>0){const s=new Uint8Array(i.colorsCompressed),r=!1;t.colorsBuf=new He(e,e.ARRAY_BUFFER,s,s.length,4,e.STATIC_DRAW,r)}if(i.positionsCompressed&&i.positionsCompressed.length>0){const s=!1;t.positionsBuf=new He(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,s),t.positionsDecodeMatrix=c.mat4(i.positionsDecodeMatrix)}if(i.indices&&i.indices.length>0&&(t.indicesBuf=new He(e,e.ELEMENT_ARRAY_BUFFER,new Uint32Array(i.indices),i.indices.length,1,e.STATIC_DRAW),t.numIndices=i.indices.length),this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new He(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new He(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new He(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this.model.scene.readableGeometryEnabled||(this._state.geometry=null),this._finalized=!0}initFlags(e,t,i){t&J&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&te&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ee&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ie&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&q&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&se&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&Z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Y&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&q?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&Y?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";jn[0]=t[0],jn[1]=t[1],jn[2]=t[2],jn[3]=t[3],this._state.colorsBuf.setData(jn,4*e,4)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&J),r=!!(t&ee),o=!!(t&te),n=!!(t&ie),a=!!(t&se),l=!!(t&Z),A=!!(t&Y);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Ar.NOT_RENDERED:i?Ar.COLOR_TRANSPARENT:Ar.COLOR_OPAQUE,c=!s||A?Ar.NOT_RENDERED:n?Ar.SILHOUETTE_SELECTED:o?Ar.SILHOUETTE_HIGHLIGHTED:r?Ar.SILHOUETTE_XRAYED:Ar.NOT_RENDERED;let u=0;u=!s||A?Ar.NOT_RENDERED:n?Ar.EDGES_SELECTED:o?Ar.EDGES_HIGHLIGHTED:r?Ar.EDGES_XRAYED:a?i?Ar.EDGES_COLOR_TRANSPARENT:Ar.EDGES_COLOR_OPAQUE:Ar.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Ar.PICK:Ar.NOT_RENDERED)<<12,d|=(t&q?255:0)<<16,Gn[0]=d,this._state.flagsBuf.setData(Gn,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(zn[0]=t[0],zn[1]=t[1],zn[2]=t[2],this._state.offsetsBuf.setData(zn,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;Wn[0]=t[0],Wn[1]=t[4],Wn[2]=t[8],Wn[3]=t[12],this._state.modelMatrixCol0Buf.setData(Wn,i),Wn[0]=t[1],Wn[1]=t[5],Wn[2]=t[9],Wn[3]=t[13],this._state.modelMatrixCol1Buf.setData(Wn,i),Wn[0]=t[2],Wn[1]=t[6],Wn[2]=t[10],Wn[3]=t[14],this._state.modelMatrixCol2Buf.setData(Wn,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ar.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ar.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ar.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ar.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ar.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Ar.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Ar.PICK)}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class Xn extends gr{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,i.positionsBuf.numItems),r&&s.drawArrays++}}class Jn extends Xn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial,s=[];return s.push("#version 300 es"),s.push("// Points batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Yn extends Xn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points batching silhouette vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = color;"),o.push("}"),o}}class Zn extends Xn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class qn extends Xn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batched pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batched pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class $n extends Xn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push(" gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}const ea=c.vec3(),ta=c.vec3(),ia=c.vec3(),sa=c.vec3(),ra=c.mat4();class oa extends gr{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=ea;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=ta;if(l){const e=ia;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=z(p,t,ra),m=sa,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const na=c.vec3(),aa=c.vec3(),la=c.vec3(),Aa=c.vec3(),ha=c.mat4();class ca extends gr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=na;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=aa;if(l){const e=la;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=z(p,t,ha),m=Aa,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class ua{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Jn(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Yn(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Zn(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new qn(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new $n(this._scene)),this._occlusionRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new oa(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new ca(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const da={};class pa{constructor(e){this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=da[t];return i||(i=new ua(e),da[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete da[t],i._destroy()}))),i}(e.model.scene);const t=e.maxGeometryBatchSize||5e6,i=function(){const e=[];return{append:function(t,i=1,s=1){e.push({data:t,times:i,denormalizeScale:s})},compileBuffer:function(t){let i=0;e.forEach((e=>{i+=e.times*e.data.length}));const s=new t(i);let r=0;return e.forEach((e=>{const t=e.data,i=e.denormalizeScale,o=s.subarray(r);if(1===i)o.set(t,0);else for(let e=0;ee.length>0?new He(t,t.ARRAY_BUFFER,e,e.length,i,s):null,r=this._preCompressedPositionsExpected?i.positions.compileBuffer(Uint16Array):to(i.positions.compileBuffer(Float32Array),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=s(r,3,t.STATIC_DRAW),e.flagsBuf=s(new Float32Array(this._buffer.vertsIndex),1,t.DYNAMIC_DRAW),e.colorsBuf=s(i.colors.compileBuffer(Uint8Array),4,t.STATIC_DRAW),e.pickColorsBuf=s(i.pickColors.compileBuffer(Uint8Array),4,t.STATIC_DRAW),e.offsetsBuf=this.model.scene.entityOffsetsEnabled?s(new Float32Array(3*this._buffer.vertsIndex),3,t.DYNAMIC_DRAW):null,this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&J&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&te&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ee&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ie&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&q&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Y&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&q?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&Y?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class ma extends fa{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 silhouetteColor;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class _a extends fa{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick mesh fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class va extends fa{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class ba extends fa{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class ya extends fa{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points instancing depth vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return o.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class xa extends fa{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("gl_PointSize = pointSize;"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const Ba=c.vec3(),wa=c.vec3(),Pa=c.vec3();c.vec3();const Ca=c.mat4();class Ma extends gr{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Ba;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=wa;if(l){const e=c.transformPoint3(h,l,Pa);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=z(p,t,Ca),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ea=c.vec3(),Fa=c.vec3(),Ia=c.vec3();c.vec3();const Da=c.mat4();class Sa extends gr{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Ea;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Fa;if(l){const e=c.transformPoint3(h,l,Ia);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=z(p,t,Da),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Ta{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new ga(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new ma(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new ya(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new _a(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new va(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new ba(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new xa(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Ma(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Sa(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Ra={};const La=new Uint8Array(4),Ua=new Float32Array(1),ka=new Float32Array(3),Oa=new Float32Array(4);class Na{constructor(e){this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Ra[t];return i||(i=new Ta(e),Ra[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Ra[t],i._destroy()}))),i}(e.model.scene),this._aabb=c.collapseAABB3(),this._state=new lt({obb:c.OBB3(),numInstances:0,origin:e.origin?c.vec3(e.origin):null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,this.primitive=e.geometry.primitive}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let s=!1;i.flagsBuf=new He(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,s)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;i.offsetsBuf=new He(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(s.positionsCompressed&&s.positionsCompressed.length>0){const t=!1;i.positionsBuf=new He(e,e.ARRAY_BUFFER,s.positionsCompressed,s.positionsCompressed.length,3,e.STATIC_DRAW,t),i.positionsDecodeMatrix=c.mat4(s.positionsDecodeMatrix)}if(s.colorsCompressed&&s.colorsCompressed.length>0){const t=new Uint8Array(s.colorsCompressed),r=!1;i.colorsBuf=new He(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;i.modelMatrixCol0Buf=new He(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),i.modelMatrixCol1Buf=new He(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),i.modelMatrixCol2Buf=new He(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;i.pickColorsBuf=new He(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}i.geometry=null,this._finalized=!0}initFlags(e,t,i){t&J&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&te&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ee&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ie&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&q&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&se&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&Z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Y&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&q?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&Y?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";La[0]=t[0],La[1]=t[1],La[2]=t[2],this._state.colorsBuf.setData(La,3*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&J),r=!!(t&ee),o=!!(t&te),n=!!(t&ie),a=!!(t&se),l=!!(t&Z),A=!!(t&Y);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Ar.NOT_RENDERED:i?Ar.COLOR_TRANSPARENT:Ar.COLOR_OPAQUE,c=!s||A?Ar.NOT_RENDERED:n?Ar.SILHOUETTE_SELECTED:o?Ar.SILHOUETTE_HIGHLIGHTED:r?Ar.SILHOUETTE_XRAYED:Ar.NOT_RENDERED;let u=0;u=!s||A?Ar.NOT_RENDERED:n?Ar.EDGES_SELECTED:o?Ar.EDGES_HIGHLIGHTED:r?Ar.EDGES_XRAYED:a?i?Ar.EDGES_COLOR_TRANSPARENT:Ar.EDGES_COLOR_OPAQUE:Ar.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Ar.PICK:Ar.NOT_RENDERED)<<12,d|=(t&q?255:0)<<16,Ua[0]=d,this._state.flagsBuf.setData(Ua,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(ka[0]=t[0],ka[1]=t[1],ka[2]=t[2],this._state.offsetsBuf.setData(ka,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;Oa[0]=t[0],Oa[1]=t[4],Oa[2]=t[8],Oa[3]=t[12],this._state.modelMatrixCol0Buf.setData(Oa,i),Oa[0]=t[1],Oa[1]=t[5],Oa[2]=t[9],Oa[3]=t[13],this._state.modelMatrixCol1Buf.setData(Oa,i),Oa[0]=t[2],Oa[1]=t[6],Oa[2]=t[10],Oa[3]=t[14],this._state.modelMatrixCol2Buf.setData(Oa,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ar.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ar.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ar.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ar.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ar.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Ar.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Ar.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Ar.PICK)}drawPickNormals(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Ar.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Ar.PICK)}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}const Qa=c.vec3(),Va=c.vec3(),Ha=c.mat4();class ja{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uPerObjectDecodeMatrix,this._uPerVertexPosition,this.uPerObjectColorAndFlags,this._uPerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=Qa;if(g){const t=c.transformPoint3(u,A,Va);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=z(p,e,Ha)}else f=p;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,8),n.drawArrays(n.LINES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,16),n.drawArrays(n.LINES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,32),n.drawArrays(n.LINES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// LinesDataTextureColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uPerObjectDecodeMatrix;"),i.push("uniform highp sampler2D uPerObjectMatrix;"),i.push("uniform lowp usampler2D uPerObjectColorAndFlags;"),i.push("uniform mediump usampler2D uPerVertexPosition;"),i.push("uniform highp usampler2D uPerLineIndices;"),i.push("uniform mediump usampler2D uPerLineObject;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push(" int lineIndex = gl_VertexID / 2;"),i.push(" int h_packed_object_id_index = (lineIndex >> 3) & 4095;"),i.push(" int v_packed_object_id_index = (lineIndex >> 3) >> 12;"),i.push(" int objectIndex = int(texelFetch(uPerLineObject, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push(" ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" } else {"),i.push(" ivec4 packedVertexBase = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push(" ivec4 packedLineIndexBaseOffset = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push(" int lineIndexBaseOffset = (packedLineIndexBaseOffset.r << 24) + (packedLineIndexBaseOffset.g << 16) + (packedLineIndexBaseOffset.b << 8) + packedLineIndexBaseOffset.a;"),i.push(" int h_index = (lineIndex - lineIndexBaseOffset) & 4095;"),i.push(" int v_index = (lineIndex - lineIndexBaseOffset) >> 12;"),i.push(" ivec3 vertexIndices = ivec3(texelFetch(uPerLineIndices, ivec2(h_index, v_index), 0));"),i.push(" ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push(" int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push(" int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push(" mat4 objectInstanceMatrix = mat4 (texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" vec3 position = vec3(texelFetch(uPerVertexPosition, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" uvec4 color = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push(" if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" };"),i.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push(" vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push(" vFragDepth = 1.0 + clipPos.w;"),i.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push(" gl_Position = clipPos;"),i.push(" vec4 rgb = vec4(color.rgba);"),i.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// LinesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Ga{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null)}eagerCreateRenders(){}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new ja(this._scene,!1)),this._colorRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy()}}const za={};class Wa{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perLineNumberPortionId8Bits=[],this.perLineNumberPortionId16Bits=[],this.perLineNumberPortionId32Bits=[]}}class Ka{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerLineIdPortionIds8Bits=null,this.texturePerLineIdPortionIds16Bits=null,this.texturePerLineIdPortionIds32Bits=null,this.texturePerLineIdIndices8Bits=null,this.texturePerLineIdIndices16Bits=null,this.texturePerLineIdIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerLineIdIndices8Bits,16:this.texturePerLineIdIndices16Bits,32:this.texturePerLineIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerLineIdPortionIds8Bits,16:this.texturePerLineIdPortionIds16Bits,32:this.texturePerLineIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindLineIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}}class Xa{constructor(e,t,i,s,r=null){this._gl=e,this._texture=t,this._textureWidth=i,this._textureHeight=s,this._textureData=r}bindTexture(e,t,i){return e.bindTexture(t,this,i)}bind(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}unbind(e){}}const Ja={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalLines:0,totalLines8Bits:0,totalLines16Bits:0,totalLines32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(Ja,null,4));let e=0;Object.keys(Ja).forEach((t=>{t.startsWith("size")&&(e+=Ja[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/Ja.totalLines).toFixed(2)}`);let t={};Object.keys(Ja).forEach((i=>{i.startsWith("size")&&(t[i]=`${(Ja[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class Ya{disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}generateTextureForColorsAndFlags(e,t,i,s,r){const o=t.length;this.numPortions=o;const n=4096,a=Math.ceil(o/512);if(0===a)throw"texture height===0";const l=new Uint8Array(16384*a);Ja.sizeDataColorsAndFlags+=l.byteLength,Ja.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),l.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20);const A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,n,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,a,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Xa(e,A,n,a,l)}generateTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);Ja.sizeDataTextureOffsets+=r.byteLength,Ja.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Xa(e,o,i,s,r)}generateTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);Ja.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete za[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new Wa,this._dataTextureState=new Ka,this._dataTextureGenerator=new Ya,this._state=new lt({origin:c.vec3(t.origin),textureState:this._dataTextureState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this.primitive=t.primitive,this._finalized=!1}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&Ja.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/2})),(this._state.numVertices+s>4096*qa||t+r>4096*qa)&&Ja.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*qa&&t+r<=4096*qa}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/2/8)*2;Ja.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}const i=t.positionsCompressed,s=t.indices,r=this._buffer;r.positionsCompressed.push(i);const o=r.lenPositionsCompressed/3,n=i.length/3;let a;r.lenPositionsCompressed+=i.length;let l=0;if(s){let e;l=s.length/2,n<=256?(e=r.indices8Bits,a=r.lenIndices8Bits/2,r.lenIndices8Bits+=s.length):n<=65536?(e=r.indices16Bits,a=r.lenIndices16Bits/2,r.lenIndices16Bits+=s.length):(e=r.indices32Bits,a=r.lenIndices32Bits/2,r.lenIndices32Bits+=s.length),e.push(s)}this._state.numVertices+=n,Ja.numberOfGeometries++;return{vertexBase:o,numVertices:n,numLines:l,indicesBase:a}}_createSubPortion(e,t){const i=e.color,s=e.colors,r=e.opacity,o=e.meshMatrix,n=e.pickColor,a=this._buffer,l=this._state;a.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),a.perObjectInstancePositioningMatrices.push(o||sl),a.perObjectSolid.push(!!e.solid),s?a.perObjectColors.push([255*s[0],255*s[1],255*s[2],255]):i&&a.perObjectColors.push([i[0],i[1],i[2],r]),a.perObjectPickColors.push(n),a.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?l.numIndices8Bits:t.numVertices<=65536?l.numIndices16Bits:l.numIndices32Bits,a.perObjectIndexBaseOffsets.push(e/2-t.indicesBase)}const A=this._subPortions.length;if(t.numLines>0){let e,i=2*t.numLines;t.numVertices<=256?(e=a.perLineNumberPortionId8Bits,l.numIndices8Bits+=i,Ja.totalLines8Bits+=t.numLines):t.numVertices<=65536?(e=a.perLineNumberPortionId16Bits,l.numIndices16Bits+=i,Ja.totalLines16Bits+=t.numLines):(e=a.perLineNumberPortionId32Bits,l.numIndices32Bits+=i,Ja.totalLines32Bits+=t.numLines),Ja.totalLines+=t.numLines;for(let i=0;i0&&(t.texturePerLineIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerLineIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerLineIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}initFlags(e,t,i){t&J&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&te&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ee&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ie&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&q&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Y&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&q?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&Y?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,el))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),c.bindTexture(c.TEXTURE_2D,h.texturePerObjectColorsAndFlags._texture),c.texSubImage2D(c.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,c.RGBA_INTEGER,c.UNSIGNED_BYTE,el))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,el))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,tl))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,$a))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ar.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ar.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){}drawSilhouetteHighlighted(e,t){}drawSilhouetteSelected(e,t){}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}setPickMatrices(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawSnapInit(e,t){}drawSnap(e,t){}drawPickNormals(e,t){}destroy(){if(this._destroyed)return;const e=this._state;this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}const ol=c.vec3(),nl=c.vec3(),al=c.vec3();c.vec3();const ll=c.vec4(),Al=c.mat4();class hl{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=ol;if(g){const t=c.transformPoint3(u,A,nl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=z(r.viewMatrix,e,Al),f=al,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(let e=0,t=r.length;e0;let r;const o=[];o.push("#version 300 es"),o.push("// TrianglesDataTextureColorRenderer vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("uniform mat4 sceneModelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),o.push("uniform highp sampler2D uTexturePerObjectMatrix;"),o.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),o.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),o.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),o.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),o.push("uniform vec3 uCameraEyeRtc;"),o.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("out float isPerspective;")),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e> 3) & 4095;"),o.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),o.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),o.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),o.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),o.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),o.push("if (int(flags.x) != renderPass) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("} else {"),o.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),o.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),o.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),o.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),o.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),o.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),o.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),o.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),o.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),o.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),o.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),o.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),o.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),o.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),o.push("if (color.a == 0u) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("};"),o.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),o.push("vec3 position;"),o.push("position = positions[gl_VertexID % 3];"),o.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),o.push("if (solid != 1u) {"),o.push("if (isPerspectiveMatrix(projMatrix)) {"),o.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),o.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("} else {"),o.push("if (viewNormal.z < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("}"),o.push("}"),o.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const cl=new Float32Array([1,1,1]),ul=c.vec3(),dl=c.vec3(),pl=c.vec3();c.vec3();const fl=c.mat4();class gl{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=ul;if(A){const t=dl;c.transformPoint3(u,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=z(p,e,fl),g=pl,g[0]=r.eye[0]-e[0],g[1]=r.eye[1]-e[1],g[2]=r.eye[2]-e[2]}else f=p,g=r.eye;if(n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),i===Ar.SILHOUETTE_XRAYED){const e=s.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Ar.SILHOUETTE_HIGHLIGHTED){const e=s.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Ar.SILHOUETTE_SELECTED){const e=s.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,cl);if(s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(m>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,r=o.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = color;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ml=new Float32Array([0,0,0,1]),_l=c.vec3(),vl=c.vec3();c.vec3();const bl=c.mat4();class yl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=_l;if(g){const t=c.transformPoint3(u,A,vl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=z(p,e,bl)}else f=p;if(n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),i===Ar.EDGES_XRAYED){const e=r.xrayMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Ar.EDGES_HIGHLIGHTED){const e=r.highlightMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Ar.EDGES_SELECTED){const e=r.selectedMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,ml);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const xl=c.vec3(),Bl=c.vec3(),wl=c.mat4();class Pl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=xl;if(g){const t=c.transformPoint3(u,A,Bl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=z(p,e,wl)}else f=p;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uObjectPerObjectOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Cl=c.vec3(),Ml=c.vec3(),El=c.vec3(),Fl=c.mat4();class Il{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=e.pickViewMatrix||o.viewMatrix,f=e.pickProjMatrix||o.projMatrix,g=e.pickOrigin||o.eye,m=e.pickProjMatrix?e.pickZFar:o.project.far;let _,v;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const b=0!==A[0]||0!==A[1]||0!==A[2],y=0!==h[0]||0!==h[1]||0!==h[2];if(b||y){const e=Cl;if(b){const t=c.transformPoint3(u,A,Ml);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],_=z(p,e,Fl),v=El,v[0]=g[0]-e[0],v[1]=g[1]-e[1],v[2]=g[2]-e[2]}else _=p,v=g;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,_),n.uniformMatrix4fv(this._uProjMatrix,!1,f),n.uniform3fv(this._uCameraEyeRtc,v),n.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(m+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const x=r._sectionPlanesState.getNumAllocatedSectionPlanes(),B=r._sectionPlanesState.sectionPlanes.length;if(x>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*B,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var s=0;s 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Dl=c.vec3(),Sl=c.vec3(),Tl=c.vec3();c.vec3();const Rl=c.mat4();class Ll{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=e.pickViewMatrix||o.viewMatrix,f=e.pickProjMatrix||o.projMatrix,g=e.pickOrigin||o.eye,m=e.pickProjMatrix?e.pickZFar:o.project.far;let _,v;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const t=Dl;if(A){const e=Sl;c.transformPoint3(u,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],_=z(p,t,Rl),v=Tl,v[0]=g[0]-t[0],v[1]=g[1]-t[1],v[2]=g[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else _=p,v=g,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(n.uniform3fv(this._uCameraEyeRtc,v),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniform1f(this._uPickZNear,e.pickZNear),n.uniform1f(this._uPickZFar,e.pickZFar),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,_),n.uniformMatrix4fv(this._uProjMatrix,!1,f),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(m+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const b=r._sectionPlanesState.getNumAllocatedSectionPlanes(),y=r._sectionPlanesState.sectionPlanes.length;if(b>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*y,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0;s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outPackedDepth = packDepth(zNormalizedDepth); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ul=c.vec3(),kl=c.vec3(),Ol=c.vec3(),Nl=c.vec3();c.vec3();const Ql=c.mat4();class Vl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=Ul;let m,_;g[0]=c.safeInv(p[3]-p[0])*c.MAX_INT,g[1]=c.safeInv(p[4]-p[1])*c.MAX_INT,g[2]=c.safeInv(p[5]-p[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(g[0]),e.snapPickCoordinateScale[1]=c.safeInv(g[1]),e.snapPickCoordinateScale[2]=c.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=kl;if(v){const e=c.transformPoint3(u,A,Ol);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=z(f,t,Ql),_=Nl,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),x=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*x,o=s.renderFlags;for(let t=0;t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(B,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(B,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(B,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uSnapVectorA;"),i.push("uniform vec2 uSnapInvVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),i.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("}"),i.push("{"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vViewPosition = clipPos;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Hl=c.vec3(),jl=c.vec3(),Gl=c.vec3(),zl=c.vec3();c.vec3();const Wl=c.mat4();class Kl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=Hl;let m,_;g[0]=c.safeInv(p[3]-p[0])*c.MAX_INT,g[1]=c.safeInv(p[4]-p[1])*c.MAX_INT,g[2]=c.safeInv(p[5]-p[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(g[0]),e.snapPickCoordinateScale[1]=c.safeInv(g[1]),e.snapPickCoordinateScale[2]=c.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=jl;if(v){const e=Gl;c.transformPoint3(u,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=z(f,t,Wl),_=zl,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this._uVectorA,e.snapVectorA),n.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),x=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*x,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uVectorAB;"),i.push("uniform vec2 uInverseVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),i.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("}"),i.push("{"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" } else {"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Xl=c.vec3(),Jl=c.vec3(),Yl=c.vec3();c.vec3();const Zl=c.mat4();class ql{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=e.pickViewMatrix||o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=Xl;if(A){const t=Jl;c.transformPoint3(u,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=z(p,e,Zl),g=Yl,g[0]=o.eye[0]-e[0],g[1]=o.eye[1]-e[1],g[2]=o.eye[2]-e[2]}else f=p,g=o.eye;n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureOcclusionRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" } else {"),i.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureColorRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const $l=c.vec3(),eA=c.vec3(),tA=c.vec3();c.vec3();const iA=c.mat4();class sA{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=$l;if(g){const t=c.transformPoint3(u,A,eA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=z(r.viewMatrix,e,iA),f=tA,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const rA=c.vec3(),oA=c.vec3(),nA=c.vec3();c.vec3();const aA=c.mat4();class lA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));const g=0!==l[0]||0!==l[1]||0!==l[2],m=0!==A[0]||0!==A[1]||0!==A[2];if(g||m){const e=rA;if(g){const t=oA;c.transformPoint3(h,l,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=A[0],e[1]+=A[1],e[2]+=A[2],p=z(d,e,aA),f=nA,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=d,f=o.eye;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),n.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&Se.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),Se.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out vec4 vFlags2;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(Se.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&Se.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&Se.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&Se.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const AA=c.vec3(),hA=c.vec3(),cA=c.vec3();c.vec3(),c.vec4();const uA=c.mat4();class dA{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a));const p=e.pickViewMatrix||r.viewMatrix,f=e.pickProjMatrix||r.projMatrix,g=e.pickOrigin||r.eye,m=e.pickProjMatrix?e.pickZFar:r.project.far;let _,v;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const b=0!==A[0]||0!==A[1]||0!==A[2],y=0!==h[0]||0!==h[1]||0!==h[2];if(b||y){const e=AA;if(b){const t=c.transformPoint3(u,A,hA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],_=z(p,e,uA),v=cA,v[0]=g[0]-e[0],v[1]=g[1]-e[1],v[2]=g[2]-e[2]}else _=p,v=g;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,_),n.uniformMatrix4fv(this._uProjMatrix,!1,f),n.uniform3fv(this._uCameraEyeRtc,v),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const e=2/(Math.log(m+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const x=s._sectionPlanesState.getNumAllocatedSectionPlanes(),B=s._sectionPlanesState.sectionPlanes.length;if(x>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*B,r=o.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// trianglesDatatextureNormalsRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTexturePickNormalsRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class pA{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new gl(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Il(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new Ll(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new dA(this._scene)),this._snapRenderer||(this._snapRenderer=new Vl(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Kl(this._scene)),this._snapRenderer||(this._snapRenderer=new Vl(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new hl(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new hl(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new gl(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new sA(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new lA(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new yl(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Pl(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Il(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new dA(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new dA(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Ll(this._scene)),this._pickDepthRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Vl(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Kl(this._scene)),this._snapInitRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new ql(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const fA={};class gA{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}class mA{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindTriangleIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}bindEdgeIndicesTextures(e,t,i,s){this.edgeIndicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[s].bindTexture(e,i,6)}}const _A={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(_A,null,4));let e=0;Object.keys(_A).forEach((t=>{t.startsWith("size")&&(e+=_A[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/_A.totalPolygons).toFixed(2)}`);let t={};Object.keys(_A).forEach((i=>{i.startsWith("size")&&(t[i]=`${(_A[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class vA{constructor(){}disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}createTextureForColorsAndFlags(e,t,i,s,r,o,n){const a=t.length;this.numPortions=a;const l=4096,A=Math.ceil(a/512);if(0===A)throw"texture height===0";const h=new Uint8Array(16384*A);_A.sizeDataColorsAndFlags+=h.byteLength,_A.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),h.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20),h.set([o[e]>>24&255,o[e]>>16&255,o[e]>>8&255,255&o[e]],32*e+24),h.set([n[e]?1:0,0,0,0],32*e+28);const c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,A),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,A,e.RGBA_INTEGER,e.UNSIGNED_BYTE,h,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Xa(e,c,l,A,h)}createTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);_A.sizeDataTextureOffsets+=r.byteLength,_A.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Xa(e,o,i,s,r)}createTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);_A.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete fA[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new gA,this._dtxState=new mA,this._dtxTextureFactory=new vA,this._state=new lt({origin:c.vec3(t.origin),metallicRoughnessBuf:null,textureState:this._dtxState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numEdgeIndices8Bits:0,numEdgeIndices16Bits:0,numEdgeIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this.model.scene.readableGeometryEnabled&&(this._subPortionReadableGeometries={}),this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this.primitive=t.primitive,this._finalized=!1}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&_A.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/3})),(this._state.numVertices+s>4096*yA||t+r>4096*yA)&&_A.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*yA&&t+r<=4096*yA}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/3/8)*3;_A.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}if(t.edgeIndices){const e=8*Math.ceil(t.edgeIndices.length/2/8)*2;_A.overheadSizeAlignementEdgeIndices+=2*(e-t.edgeIndices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.edgeIndices),t.edgeIndices=i}const i=t.positionsCompressed,s=t.indices,r=t.edgeIndices,o=this._buffer;o.positionsCompressed.push(i);const n=o.lenPositionsCompressed/3,a=i.length/3;let l;o.lenPositionsCompressed+=i.length;let A,h=0;if(s){let e;h=s.length/3,a<=256?(e=o.indices8Bits,l=o.lenIndices8Bits/3,o.lenIndices8Bits+=s.length):a<=65536?(e=o.indices16Bits,l=o.lenIndices16Bits/3,o.lenIndices16Bits+=s.length):(e=o.indices32Bits,l=o.lenIndices32Bits/3,o.lenIndices32Bits+=s.length),e.push(s)}let c=0;if(r){let e;c=r.length/2,a<=256?(e=o.edgeIndices8Bits,A=o.lenEdgeIndices8Bits/2,o.lenEdgeIndices8Bits+=r.length):a<=65536?(e=o.edgeIndices16Bits,A=o.lenEdgeIndices16Bits/2,o.lenEdgeIndices16Bits+=r.length):(e=o.edgeIndices32Bits,A=o.lenEdgeIndices32Bits/2,o.lenEdgeIndices32Bits+=r.length),e.push(r)}this._state.numVertices+=a,_A.numberOfGeometries++;return{vertexBase:n,numVertices:a,numTriangles:h,numEdges:c,indicesBase:l,edgeIndicesBase:A}}_createSubPortion(e,t,i,s){const r=e.color;e.metallic,e.roughness;const o=e.colors,n=e.opacity,a=e.meshMatrix,l=e.pickColor,A=this._buffer,h=this._state;A.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),A.perObjectInstancePositioningMatrices.push(a||MA),A.perObjectSolid.push(!!e.solid),o?A.perObjectColors.push([255*o[0],255*o[1],255*o[2],255]):r&&A.perObjectColors.push([r[0],r[1],r[2],n]),A.perObjectPickColors.push(l),A.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?h.numIndices8Bits:t.numVertices<=65536?h.numIndices16Bits:h.numIndices32Bits,A.perObjectIndexBaseOffsets.push(e/3-t.indicesBase)}{let e;e=t.numVertices<=256?h.numEdgeIndices8Bits:t.numVertices<=65536?h.numEdgeIndices16Bits:h.numEdgeIndices32Bits,A.perObjectEdgeIndexBaseOffsets.push(e/2-t.edgeIndicesBase)}const c=this._subPortions.length;if(t.numTriangles>0){let e,i=3*t.numTriangles;t.numVertices<=256?(e=A.perTriangleNumberPortionId8Bits,h.numIndices8Bits+=i,_A.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(e=A.perTriangleNumberPortionId16Bits,h.numIndices16Bits+=i,_A.totalPolygons16Bits+=t.numTriangles):(e=A.perTriangleNumberPortionId32Bits,h.numIndices32Bits+=i,_A.totalPolygons32Bits+=t.numTriangles),_A.totalPolygons+=t.numTriangles;for(let i=0;i0){let e,i=2*t.numEdges;t.numVertices<=256?(e=A.perEdgeNumberPortionId8Bits,h.numEdgeIndices8Bits+=i,_A.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(e=A.perEdgeNumberPortionId16Bits,h.numEdgeIndices16Bits+=i,_A.totalEdges16Bits+=t.numEdges):(e=A.perEdgeNumberPortionId32Bits,h.numEdgeIndices32Bits+=i,_A.totalEdges32Bits+=t.numEdges),_A.totalEdges+=t.numEdges;for(let i=0;i0&&(t.texturePerEdgeIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId8Bits)),s.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId16Bits)),s.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId32Bits)),s.lenIndices8Bits>0&&(t.texturePerPolygonIdIndices8Bits=this._dtxTextureFactory.createTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerPolygonIdIndices16Bits=this._dtxTextureFactory.createTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerPolygonIdIndices32Bits=this._dtxTextureFactory.createTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),s.lenEdgeIndices8Bits>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this._dtxTextureFactory.createTextureFor8BitsEdgeIndices(i,s.edgeIndices8Bits,s.lenEdgeIndices8Bits)),s.lenEdgeIndices16Bits>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this._dtxTextureFactory.createTextureFor16BitsEdgeIndices(i,s.edgeIndices16Bits,s.lenEdgeIndices16Bits)),s.lenEdgeIndices32Bits>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this._dtxTextureFactory.createTextureFor32BitsEdgeIndices(i,s.edgeIndices32Bits,s.lenEdgeIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}isEmpty(){return 0===this._numPortions}initFlags(e,t,i){t&J&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&te&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ee&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ie&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&q&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&se&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&Z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Y&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&q?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dtxState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&Y?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,wA))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),g.bindTexture(g.TEXTURE_2D,f.texturePerObjectColorsAndFlags._texture),g.texSubImage2D(g.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,g.RGBA_INTEGER,g.UNSIGNED_BYTE,wA))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,wA))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,PA))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,BA))}getEachVertex(e,t){if(!this.model.scene.readableGeometryEnabled)return;const i=this._state,s=this._portionToSubPortionsMap[e];if(s)for(let e=0,r=s.length;e{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==LA[e])return void LA[e].push({onLoad:t,onProgress:i,onError:s});LA[e]=[],LA[e].push({onLoad:t,onProgress:i,onError:s});const o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),n=this.mimeType,a=this.responseType;fetch(o).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;const i=LA[e],s=t.body.getReader(),r=t.headers.get("Content-Length"),o=r?parseInt(r):0,n=0!==o;let a=0;const l=new ReadableStream({start(e){!function t(){s.read().then((({done:s,value:r})=>{if(s)e.close();else{a+=r.byteLength;const s=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=i.length;e{switch(a){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,n)));case"json":return e.json();default:if(void 0===n)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(n),i=t&&t[1]?t[1].toLowerCase():void 0,s=new TextDecoder(i);return e.arrayBuffer().then((e=>s.decode(e)))}}})).then((t=>{DA.add(e,t);const i=LA[e];delete LA[e];for(let e=0,s=i.length;e{const i=LA[e];if(void 0===i)throw this.manager.itemError(e),t;delete LA[e];for(let e=0,s=i.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class kA{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e{const s=this._getIdleWorker();-1!==s?(this._initWorker(s),this.workerStatus|=1<e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let OA=0;class NA{constructor({viewer:e,transcoderPath:t,workerLimit:i}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new kA,this._workerSourceURL="",i&&this._workerPool.setWorkerLimit(i);const s=e.capabilities;this._workerConfig={astcSupported:s.astcSupported,etc1Supported:s.etc1Supported,etc2Supported:s.etc2Supported,dxtSupported:s.dxtSupported,bptcSupported:s.bptcSupported,pvrtcSupported:s.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new UA;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),i=new UA;i.setPath(this._transcoderPath),i.setResponseType("arraybuffer"),i.setWithCredentials(this.withCredentials);const s=i.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,s]).then((([e,t])=>{const i=NA.BasisWorker.toString(),s=["/* constants */","let _EngineFormat = "+JSON.stringify(NA.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(NA.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(NA.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([s])),this._transcoderBinary=t,this._workerPool.setWorkerCreator((()=>{const e=new Worker(this._workerSourceURL),t=this._transcoderBinary.slice(0);return e.postMessage({type:"init",config:this._workerConfig,transcoderBinary:t},[t]),e}))})),OA>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),OA++}return this._transcoderPending}transcode(e,t,i={}){return new Promise(((s,r)=>{const o=i;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const i=e.data,{mipmaps:o,width:n,height:a,format:l,type:A,error:h,dfdTransferFn:c,dfdFlags:u}=i;if("error"===A)return r(h);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?1006:1008,magFilter:1===o.length?1006:1008,encoding:2===c?3001:3e3,premultiplyAlpha:!!(1&u)}}),s()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),OA--}}NA.BasisFormat={ETC1S:0,UASTC_4x4:1},NA.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16},NA.EngineFormat={RGBAFormat:1023,RGBA_ASTC_4x4_Format:37808,RGBA_BPTC_Format:36492,RGBA_ETC2_EAC_Format:37496,RGBA_PVRTC_4BPPV1_Format:35842,RGBA_S3TC_DXT5_Format:33779,RGB_ETC1_Format:36196,RGB_ETC2_Format:37492,RGB_PVRTC_4BPPV1_Format:35840,RGB_S3TC_DXT1_Format:33776},NA.BasisWorker=function(){let e,t,i;const s=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const h=n.data;switch(h.type){case"init":e=h.config,c=h.transcoderBinary,t=new Promise((e=>{i={wasmBinary:c,onRuntimeInitialized:e},BASIS(i)})).then((()=>{i.initializeBasis(),void 0===i.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:c,mipmaps:u,format:d,dfdTransferFn:p,dfdFlags:f}=function(t){const n=new i.KTX2File(new Uint8Array(t));function h(){n.close(),n.delete()}if(!n.isValid())throw h(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const c=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),d=n.getHeight(),p=n.getLevels(),f=n.getHasAlpha(),g=n.getDFDTransferFunc(),m=n.getDFDFlags(),{transcoderFormat:_,engineFormat:v}=function(t,i,n,h){let c,u;const d=t===o.ETC1S?a:l;for(let s=0;s{delete QA[t],i.destroy()}))),i} +"use strict";Object.defineProperty(exports,"__esModule",{value:!0});class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){let e;if(2===arguments.length){const t=arguments[0];if(e=arguments[1],this.items[t])throw"ID clash: '"+t+"'";return this.items[t]=e,t}for(e=arguments[0]||{};;){const t=this._lastUniqueId++;if(!this.items[t])return this.items[t]=e,t}}removeItem(e){const t=this.items[e];return delete this.items[e],t}}const t=new e;class i{constructor(e){this.id=e,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0}}class s{constructor(){this.items=[]}}class r{constructor(e,t,i,s,r){this.id=e,this.getTitle=t,this.doAction=i,this.getEnabled=s,this.getShown=r,this.itemElement=null,this.subMenu=null,this.enabled=!0}}let o=!0,n=o?Float64Array:Float32Array;const a=new n(3),l=new n(16),A=new n(16),h=new n(4),c={setDoublePrecisionEnabled(e){o=e,n=o?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>o,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new n(e||2),vec3:e=>new n(e||3),vec4:e=>new n(e||4),mat3:e=>new n(e||9),mat3ToMat4:(e,t=new n(16))=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t),mat4:e=>new n(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,i){const s=new n(2);for(let r=0,o=e.length;r{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,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(ee[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i),addVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i),addVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i),addVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i),subVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i),subVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i),subVec2:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i),geometricMeanVec2(...e){const t=new n(e[0]);for(let i=1;i(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i),subScalarVec4:(e,t,i)=>(i||(i=e),i[0]=t-e[0],i[1]=t-e[1],i[2]=t-e[2],i[3]=t-e[3],i),mulVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]*t[0],i[1]=e[1]*t[1],i[2]=e[2]*t[2],i[3]=e[3]*t[3],i),mulVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i),mulVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i),mulVec2Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i),divVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i),divVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i[3]=e[3]/t[3],i),divScalarVec3:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i),divVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i),divVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i[3]=e[3]/t,i),divScalarVec4:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i[3]=e/t[3],i),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const i=e[0],s=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[s*a-r*n,r*o-i*a,i*n-s*o,0]},cross3Vec3(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return i[0]=r*l-o*a,i[1]=o*n-s*l,i[2]=s*a-r*n,i},sqLenVec4:e=>c.dotVec4(e,e),lenVec4:e=>Math.sqrt(c.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=>c.dotVec3(e,e),sqLenVec2:e=>c.dotVec2(e,e),lenVec3:e=>Math.sqrt(c.sqLenVec3(e)),distVec3:(()=>{const e=new n(3);return(t,i)=>c.lenVec3(c.subVec3(t,i,e))})(),lenVec2:e=>Math.sqrt(c.sqLenVec2(e)),distVec2:(()=>{const e=new n(2);return(t,i)=>c.lenVec2(c.subVec2(t,i,e))})(),rcpVec3:(e,t)=>c.divScalarVec3(1,e,t),normalizeVec4(e,t){const i=1/c.lenVec4(e);return c.mulVec4Scalar(e,i,t)},normalizeVec3(e,t){const i=1/c.lenVec3(e);return c.mulVec3Scalar(e,i,t)},normalizeVec2(e,t){const i=1/c.lenVec2(e);return c.mulVec2Scalar(e,i,t)},angleVec3(e,t){let i=c.dotVec3(e,t)/Math.sqrt(c.sqLenVec3(e)*c.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:(()=>{const e=new n(3);return(t,i)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=c.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=c.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=c.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({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||c.vec3())[0]=e.x,t[1]=e.y,t[2]=e.z,t),dupMat4:e=>e.slice(0,16),mat4To3:e=>[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]],m4s:e=>[e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e],setMat4ToZeroes:()=>c.m4s(0),setMat4ToOnes:()=>c.m4s(1),diagonalMat4v:e=>new n([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,i,s)=>c.diagonalMat4v([e,t,i,s]),diagonalMat4s:e=>c.diagonalMat4c(e,e,e,e),identityMat4:(e=new n(16))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e),identityMat3:(e=new n(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i),addMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i),addScalarMat4:(e,t,i)=>c.addMat4Scalar(t,e,i),subMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i),subMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i),subScalarMat4:(e,t,i)=>(i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i),mulMat4(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],A=e[6],h=e[7],c=e[8],u=e[9],d=e[10],p=e[11],f=e[12],g=e[13],m=e[14],_=e[15],v=t[0],b=t[1],y=t[2],x=t[3],B=t[4],w=t[5],P=t[6],C=t[7],M=t[8],E=t[9],F=t[10],I=t[11],D=t[12],S=t[13],T=t[14],R=t[15];return i[0]=v*s+b*a+y*c+x*f,i[1]=v*r+b*l+y*u+x*g,i[2]=v*o+b*A+y*d+x*m,i[3]=v*n+b*h+y*p+x*_,i[4]=B*s+w*a+P*c+C*f,i[5]=B*r+w*l+P*u+C*g,i[6]=B*o+w*A+P*d+C*m,i[7]=B*n+w*h+P*p+C*_,i[8]=M*s+E*a+F*c+I*f,i[9]=M*r+E*l+F*u+I*g,i[10]=M*o+E*A+F*d+I*m,i[11]=M*n+E*h+F*p+I*_,i[12]=D*s+S*a+T*c+R*f,i[13]=D*r+S*l+T*u+R*g,i[14]=D*o+S*A+T*d+R*m,i[15]=D*n+S*h+T*p+R*_,i},mulMat3(e,t,i){i||(i=new n(9));const s=e[0],r=e[3],o=e[6],a=e[1],l=e[4],A=e[7],h=e[2],c=e[5],u=e[8],d=t[0],p=t[3],f=t[6],g=t[1],m=t[4],_=t[7],v=t[2],b=t[5],y=t[8];return i[0]=s*d+r*g+o*v,i[3]=s*p+r*m+o*b,i[6]=s*f+r*_+o*y,i[1]=a*d+l*g+A*v,i[4]=a*p+l*m+A*b,i[7]=a*f+l*_+A*y,i[2]=h*d+c*g+u*v,i[5]=h*p+c*m+u*b,i[8]=h*f+c*_+u*y,i},mulMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i),mulMat4v4(e,t,i=c.vec4()){const s=t[0],r=t[1],o=t[2],n=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*n,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*n,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*n,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*n,i},transposeMat4(e,t){const i=e[4],s=e[14],r=e[8],o=e[13],n=e[12],a=e[9];if(!t||e===t){const t=e[1],l=e[2],A=e[3],h=e[6],c=e[7],u=e[11];return e[1]=i,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=h,e[11]=s,e[12]=A,e[13]=c,e[14]=u,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=n,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=o,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4(e){const t=e[0],i=e[1],s=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],A=e[8],h=e[9],c=e[10],u=e[11],d=e[12],p=e[13],f=e[14],g=e[15];return d*h*a*r-A*p*a*r-d*n*c*r+o*p*c*r+A*n*f*r-o*h*f*r-d*h*s*l+A*p*s*l+d*i*c*l-t*p*c*l-A*i*f*l+t*h*f*l+d*n*s*u-o*p*s*u-d*i*a*u+t*p*a*u+o*i*f*u-t*n*f*u-A*n*s*g+o*h*s*g+A*i*a*g-t*h*a*g-o*i*c*g+t*n*c*g},inverseMat4(e,t){t||(t=e);const i=e[0],s=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],A=e[7],h=e[8],c=e[9],u=e[10],d=e[11],p=e[12],f=e[13],g=e[14],m=e[15],_=i*a-s*n,v=i*l-r*n,b=i*A-o*n,y=s*l-r*a,x=s*A-o*a,B=r*A-o*l,w=h*f-c*p,P=h*g-u*p,C=h*m-d*p,M=c*g-u*f,E=c*m-d*f,F=u*m-d*g,I=1/(_*F-v*E+b*M+y*C-x*P+B*w);return t[0]=(a*F-l*E+A*M)*I,t[1]=(-s*F+r*E-o*M)*I,t[2]=(f*B-g*x+m*y)*I,t[3]=(-c*B+u*x-d*y)*I,t[4]=(-n*F+l*C-A*P)*I,t[5]=(i*F-r*C+o*P)*I,t[6]=(-p*B+g*b-m*v)*I,t[7]=(h*B-u*b+d*v)*I,t[8]=(n*E-a*C+A*w)*I,t[9]=(-i*E+s*C-o*w)*I,t[10]=(p*x-f*b+m*_)*I,t[11]=(-h*x+c*b-d*_)*I,t[12]=(-n*M+a*P-l*w)*I,t[13]=(i*M-s*P+r*w)*I,t[14]=(-p*y+f*v-g*_)*I,t[15]=(h*y-c*v+u*_)*I,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const i=t||c.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v(e,t){const i=t||c.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(()=>{const e=new n(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,c.translationMat4v(e,r))})(),translationMat4s:(e,t)=>c.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>c.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,i,s){const r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;const o=s[7];s[4]+=o*e,s[5]+=o*t,s[6]+=o*i;const n=s[11];s[8]+=n*e,s[9]+=n*t,s[10]+=n*i;const a=s[15];return s[12]+=a*e,s[13]+=a*t,s[14]+=a*i,s},setMat4Translation:(e,t,i)=>(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i),rotationMat4v(e,t,i){const s=c.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=s[0],l=s[1],A=s[2];let h,u,d,p,f,g;return h=a*l,u=l*A,d=A*a,p=a*r,f=l*r,g=A*r,(i=i||c.mat4())[0]=n*a*a+o,i[1]=n*h+g,i[2]=n*d-f,i[3]=0,i[4]=n*h-g,i[5]=n*l*l+o,i[6]=n*u+p,i[7]=0,i[8]=n*d+f,i[9]=n*u-p,i[10]=n*A*A+o,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:(e,t,i,s,r)=>c.rotationMat4v(e,[t,i,s],r),scalingMat4v:(e,t=c.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=c.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new n(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,c.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=>c.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,i=c.mat4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=s+s,l=r+r,A=o+o,h=s*a,u=s*l,d=s*A,p=r*l,f=r*A,g=o*A,m=n*a,_=n*l,v=n*A;return i[0]=1-(p+g),i[1]=u+v,i[2]=d-_,i[3]=0,i[4]=u-v,i[5]=1-(h+g),i[6]=f+m,i[7]=0,i[8]=d+_,i[9]=f-m,i[10]=1-(h+p),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler(e,t,i=c.vec4()){const s=c.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],A=e[9],h=e[2],u=e[6],d=e[10];return"XYZ"===t?(i[1]=Math.asin(s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(-A,d),i[2]=Math.atan2(-o,r)):(i[0]=Math.atan2(u,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(A,-1,1)),Math.abs(A)<.99999?(i[1]=Math.atan2(n,d),i[2]=Math.atan2(a,l)):(i[1]=Math.atan2(-h,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(u,-1,1)),Math.abs(u)<.99999?(i[1]=Math.atan2(-h,d),i[2]=Math.atan2(-o,l)):(i[1]=0,i[2]=Math.atan2(a,r))):"ZYX"===t?(i[1]=Math.asin(-s(h,-1,1)),Math.abs(h)<.99999?(i[0]=Math.atan2(u,d),i[2]=Math.atan2(a,r)):(i[0]=0,i[2]=Math.atan2(-o,l))):"YZX"===t?(i[2]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-A,l),i[1]=Math.atan2(-h,r)):(i[0]=0,i[1]=Math.atan2(n,d))):"XZY"===t&&(i[2]=Math.asin(-s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(u,l),i[1]=Math.atan2(n,r)):(i[0]=Math.atan2(-A,d),i[1]=0)),i},composeMat4:(e,t,i,s=c.mat4())=>(c.quaternionToRotationMat4(t,s),c.scaleMat4v(i,s),c.translateMat4v(e,s),s),decomposeMat4:(()=>{const e=new n(3),t=new n(16);return function(i,s,r,o){e[0]=i[0],e[1]=i[1],e[2]=i[2];let n=c.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];const a=c.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];const l=c.lenVec3(e);c.determinantMat4(i)<0&&(n=-n),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);const A=1/n,h=1/a,u=1/l;return t[0]*=A,t[1]*=A,t[2]*=A,t[4]*=h,t[5]*=h,t[6]*=h,t[8]*=u,t[9]*=u,t[10]*=u,c.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v(e,t,i,s){s||(s=c.mat4());const r=e[0],o=e[1],n=e[2],a=i[0],l=i[1],A=i[2],h=t[0],u=t[1],d=t[2];if(r===h&&o===u&&n===d)return c.identityMat4();let p,f,g,m,_,v,b,y,x,B;return p=r-h,f=o-u,g=n-d,B=1/Math.sqrt(p*p+f*f+g*g),p*=B,f*=B,g*=B,m=l*g-A*f,_=A*p-a*g,v=a*f-l*p,B=Math.sqrt(m*m+_*_+v*v),B?(B=1/B,m*=B,_*=B,v*=B):(m=0,_=0,v=0),b=f*v-g*_,y=g*m-p*v,x=p*_-f*m,B=Math.sqrt(b*b+y*y+x*x),B?(B=1/B,b*=B,y*=B,x*=B):(b=0,y=0,x=0),s[0]=m,s[1]=b,s[2]=p,s[3]=0,s[4]=_,s[5]=y,s[6]=f,s[7]=0,s[8]=v,s[9]=x,s[10]=g,s[11]=0,s[12]=-(m*r+_*o+v*n),s[13]=-(b*r+y*o+x*n),s[14]=-(p*r+f*o+g*n),s[15]=1,s},lookAtMat4c:(e,t,i,s,r,o,n,a,l)=>c.lookAtMat4v([e,t,i],[s,r,o],[n,a,l],[]),orthoMat4c(e,t,i,s,r,o,n){n||(n=c.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2/l,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=-2/A,n[11]=0,n[12]=-(e+t)/a,n[13]=-(s+i)/l,n[14]=-(o+r)/A,n[15]=1,n},frustumMat4v(e,t,i){i||(i=c.mat4());const s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];c.addVec4(r,s,l),c.subVec4(r,s,A);const o=2*s[2],n=A[0],a=A[1],h=A[2];return i[0]=o/n,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=o/a,i[6]=0,i[7]=0,i[8]=l[0]/n,i[9]=l[1]/a,i[10]=-l[2]/h,i[11]=-1,i[12]=0,i[13]=0,i[14]=-o*r[2]/h,i[15]=0,i},frustumMat4(e,t,i,s,r,o,n){n||(n=c.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2*r/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2*r/l,n[6]=0,n[7]=0,n[8]=(t+e)/a,n[9]=(s+i)/l,n[10]=-(o+r)/A,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/A,n[15]=0,n},perspectiveMat4(e,t,i,s,r){const o=[],n=[];return o[2]=i,n[2]=s,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],c.frustumMat4v(o,n,r)},compareMat4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15],transformPoint3(e,t,i=c.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=c.vec4())=>(i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i),transformPoints3(e,t,i){const s=i||[],r=t.length;let o,n,a,l;const A=e[0],h=e[1],c=e[2],u=e[3],d=e[4],p=e[5],f=e[6],g=e[7],m=e[8],_=e[9],v=e[10],b=e[11],y=e[12],x=e[13],B=e[14],w=e[15];let P;for(let e=0;e{const e=new n(16),t=new n(16),i=new n(16);return function(s,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),i),s,n)}})(),lerpVec3(e,t,i,s,r,o){const n=o||c.vec3(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n},lerpMat4(e,t,i,s,r,o){const n=o||c.mat4(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n[3]=s[3]+a*(r[3]-s[3]),n[4]=s[4]+a*(r[4]-s[4]),n[5]=s[5]+a*(r[5]-s[5]),n[6]=s[6]+a*(r[6]-s[6]),n[7]=s[7]+a*(r[7]-s[7]),n[8]=s[8]+a*(r[8]-s[8]),n[9]=s[9]+a*(r[9]-s[9]),n[10]=s[10]+a*(r[10]-s[10]),n[11]=s[11]+a*(r[11]-s[11]),n[12]=s[12]+a*(r[12]-s[12]),n[13]=s[13]+a*(r[13]-s[13]),n[14]=s[14]+a*(r[14]-s[14]),n[15]=s[15]+a*(r[15]-s[15]),n},flatten(e){const t=[];let i,s,r,o,n;for(i=0,s=e.length;i(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,i=c.vec4()){const s=e[0]*c.DEGTORAD/2,r=e[1]*c.DEGTORAD/2,o=e[2]*c.DEGTORAD/2,n=Math.cos(s),a=Math.cos(r),l=Math.cos(o),A=Math.sin(s),h=Math.sin(r),u=Math.sin(o);return"XYZ"===t?(i[0]=A*a*l+n*h*u,i[1]=n*h*l-A*a*u,i[2]=n*a*u+A*h*l,i[3]=n*a*l-A*h*u):"YXZ"===t?(i[0]=A*a*l+n*h*u,i[1]=n*h*l-A*a*u,i[2]=n*a*u-A*h*l,i[3]=n*a*l+A*h*u):"ZXY"===t?(i[0]=A*a*l-n*h*u,i[1]=n*h*l+A*a*u,i[2]=n*a*u+A*h*l,i[3]=n*a*l-A*h*u):"ZYX"===t?(i[0]=A*a*l-n*h*u,i[1]=n*h*l+A*a*u,i[2]=n*a*u-A*h*l,i[3]=n*a*l+A*h*u):"YZX"===t?(i[0]=A*a*l+n*h*u,i[1]=n*h*l+A*a*u,i[2]=n*a*u-A*h*l,i[3]=n*a*l-A*h*u):"XZY"===t&&(i[0]=A*a*l-n*h*u,i[1]=n*h*l-A*a*u,i[2]=n*a*u+A*h*l,i[3]=n*a*l+A*h*u),i},mat4ToQuaternion(e,t=c.vec4()){const i=e[0],s=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],A=e[6],h=e[10];let u;const d=i+n+h;return d>0?(u=.5/Math.sqrt(d+1),t[3]=.25/u,t[0]=(A-a)*u,t[1]=(r-l)*u,t[2]=(o-s)*u):i>n&&i>h?(u=2*Math.sqrt(1+i-n-h),t[3]=(A-a)/u,t[0]=.25*u,t[1]=(s+o)/u,t[2]=(r+l)/u):n>h?(u=2*Math.sqrt(1+n-i-h),t[3]=(r-l)/u,t[0]=(s+o)/u,t[1]=.25*u,t[2]=(a+A)/u):(u=2*Math.sqrt(1+h-i-n),t[3]=(o-s)/u,t[0]=(r+l)/u,t[1]=(a+A)/u,t[2]=.25*u),t},vec3PairToQuaternion(e,t,i=c.vec4()){const s=Math.sqrt(c.dotVec3(e,e)*c.dotVec3(t,t));let r=s+c.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])):c.cross3Vec3(e,t,i),i[3]=r,c.normalizeQuaternion(i)},angleAxisToQuaternion(e,t=c.vec4()){const i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:(()=>{const e=new n(16);return(t,i,s)=>(s=s||c.vec3(),c.quaternionToRotationMat4(t,e),c.mat4ToEuler(e,i,s),s)})(),mulQuaternions(e,t,i=c.vec4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],A=t[2],h=t[3];return i[0]=n*a+s*h+r*A-o*l,i[1]=n*l+r*h+o*a-s*A,i[2]=n*A+o*h+s*l-r*a,i[3]=n*h-s*a-r*l-o*A,i},vec3ApplyQuaternion(e,t,i=c.vec3()){const s=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],A=e[3],h=A*s+a*o-l*r,u=A*r+l*s-n*o,d=A*o+n*r-a*s,p=-n*s-a*r-l*o;return i[0]=h*A+p*-n+u*-l-d*-a,i[1]=u*A+p*-a+d*-n-h*-l,i[2]=d*A+p*-l+h*-a-u*-n,i},quaternionToMat4(e,t){t=c.identityMat4(t);const i=e[0],s=e[1],r=e[2],o=e[3],n=2*i,a=2*s,l=2*r,A=n*o,h=a*o,u=l*o,d=n*i,p=a*i,f=l*i,g=a*s,m=l*s,_=l*r;return t[0]=1-(g+_),t[1]=p+u,t[2]=f-h,t[4]=p-u,t[5]=1-(d+_),t[6]=m+A,t[8]=f+h,t[9]=m-A,t[10]=1-(d+g),t},quaternionToRotationMat4(e,t){const i=e[0],s=e[1],r=e[2],o=e[3],n=i+i,a=s+s,l=r+r,A=i*n,h=i*a,c=i*l,u=s*a,d=s*l,p=r*l,f=o*n,g=o*a,m=o*l;return t[0]=1-(u+p),t[4]=h-m,t[8]=c+g,t[1]=h+m,t[5]=1-(A+p),t[9]=d-f,t[2]=c-g,t[6]=d+f,t[10]=1-(A+u),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const i=c.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)=>c.normalizeQuaternion(c.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=c.vec4()){const i=(e=c.normalizeQuaternion(e,h))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:e=>new n(e||6),AABB2:e=>new n(e||4),OBB3:e=>new n(e||32),OBB2:e=>new n(e||16),Sphere3:(e,t,i,s)=>new n([e,t,i,s]),transformOBB3(e,t,i=t){let s;const r=t.length;let o,n,a;const l=e[0],A=e[1],h=e[2],c=e[3],u=e[4],d=e[5],p=e[6],f=e[7],g=e[8],m=e[9],_=e[10],v=e[11],b=e[12],y=e[13],x=e[14],B=e[15];for(s=0;s{const e=new n(3),t=new n(3),i=new n(3);return s=>(e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5],c.subVec3(t,e,i),Math.abs(c.lenVec3(i)))})(),getAABB3DiagPoint:(()=>{const e=new n(3),t=new n(3),i=new n(3);return(s,r)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5];const o=c.subVec3(t,e,i),n=r[0]-s[0],a=s[3]-r[0],l=r[1]-s[1],A=s[4]-r[1],h=r[2]-s[2],u=s[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>A?l:A,o[2]+=h>u?h:u,Math.abs(c.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const i=t||c.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||c.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:(e=c.AABB3())=>(e[0]=c.MAX_DOUBLE,e[1]=c.MAX_DOUBLE,e[2]=c.MAX_DOUBLE,e[3]=c.MIN_DOUBLE,e[4]=c.MIN_DOUBLE,e[5]=c.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=c.OBB3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t),positions3ToAABB3:(()=>{const e=new n(3);return(t,i,s)=>{i=i||c.AABB3();let r,o,n,a=c.MAX_DOUBLE,l=c.MAX_DOUBLE,A=c.MAX_DOUBLE,h=c.MIN_DOUBLE,u=c.MIN_DOUBLE,d=c.MIN_DOUBLE;for(let i=0,p=t.length;ih&&(h=r),o>u&&(u=o),n>d&&(d=n);return i[0]=a,i[1]=l,i[2]=A,i[3]=h,i[4]=u,i[5]=d,i}})(),OBB3ToAABB3(e,t=c.AABB3()){let i,s,r,o=c.MAX_DOUBLE,n=c.MAX_DOUBLE,a=c.MAX_DOUBLE,l=c.MIN_DOUBLE,A=c.MIN_DOUBLE,h=c.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToAABB3(e,t=c.AABB3()){let i,s,r,o=c.MAX_DOUBLE,n=c.MAX_DOUBLE,a=c.MAX_DOUBLE,l=c.MIN_DOUBLE,A=c.MIN_DOUBLE,h=c.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToSphere3:(()=>{const e=new n(3);return(t,i)=>{i=i||c.vec4();let s,r=0,o=0,n=0;const a=t.length;for(s=0;sA&&(A=l);return i[3]=A,i}})(),positions3ToSphere3:(()=>{const e=new n(3),t=new n(3);return(i,s)=>{s=s||c.vec4();let r,o=0,n=0,a=0;const l=i.length;let A=0;for(r=0;rA&&(A=u);return s[3]=A,s}})(),OBB3ToSphere3:(()=>{const e=new n(3),t=new n(3);return(i,s)=>{s=s||c.vec4();let r,o=0,n=0,a=0;const l=i.length,A=l/4;for(r=0;ru&&(u=h);return s[3]=u,s}})(),getSphere3Center:(e,t=c.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=c.vec3()){let i=0,s=0,r=0;for(var o=0,n=e.length;o(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3](e[0]=c.MAX_DOUBLE,e[1]=c.MAX_DOUBLE,e[2]=c.MIN_DOUBLE,e[3]=c.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]e[0]<=t[0]&&e[3]>=t[0]&&e[1]<=t[1]&&e[4]>=t[1]&&e[2]<=t[2]&&e[5]>=t[2],planeAABB3Intersect(e,t,i){let s,r;e[0]>0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]);if(s<=-t&&r<=-t)return-1;return s>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=c.AABB2()){let i,s,r,o,n=c.MAX_DOUBLE,a=c.MAX_DOUBLE,l=c.MIN_DOUBLE,A=c.MIN_DOUBLE;for(let t=0,h=e.length;tl&&(l=i),s>A&&(A=s);return t[0]=n,t[1]=a,t[2]=l,t[3]=A,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]2*(1-e)*(i-t)+2*e*(s-i),tangentQuadraticBezier3:(e,t,i,s,r)=>-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r,tangentSpline:e=>6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e),catmullRomInterpolate(e,t,i,s,r){const o=.5*(i-e),n=.5*(s-t),a=r*r;return(2*t-2*i+o+n)*(r*a)+(-3*t+3*i-2*o-n)*a+o*r+t},b2p0(e,t){const i=1-e;return i*i*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0(e,t){const i=1-e;return i*i*i*t},b3p1(e,t){const i=1-e;return 3*i*i*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal(e,t,i,s=c.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=i[0]-e[0],l=i[1]-e[1],A=i[2]-e[2],h=o*A-n*l,u=n*a-r*A,d=r*l-o*a,p=Math.sqrt(h*h+u*u+d*d);return 0===p?(s[0]=0,s[1]=0,s[2]=0):(s[0]=h/p,s[1]=u/p,s[2]=d/p),s},rayTriangleIntersect:(()=>{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3);return(o,n,a,l,A,h)=>{h=h||c.vec3();const u=c.subVec3(l,a,e),d=c.subVec3(A,a,t),p=c.cross3Vec3(n,d,i),f=c.dotVec3(u,p);if(f<1e-6)return null;const g=c.subVec3(o,a,s),m=c.dotVec3(g,p);if(m<0||m>f)return null;const _=c.cross3Vec3(g,u,r),v=c.dotVec3(n,_);if(v<0||m+v>f)return null;const b=c.dotVec3(d,_)/f;return h[0]=o[0]+b*n[0],h[1]=o[1]+b*n[1],h[2]=o[2]+b*n[2],h}})(),rayPlaneIntersect:(()=>{const e=new n(3),t=new n(3),i=new n(3),s=new n(3);return(r,o,n,a,l,A)=>{A=A||c.vec3(),o=c.normalizeVec3(o,e);const h=c.subVec3(a,n,t),u=c.subVec3(l,n,i),d=c.cross3Vec3(h,u,s);c.normalizeVec3(d,d);const p=-c.dotVec3(n,d),f=-(c.dotVec3(r,d)+p)/c.dotVec3(o,d);return A[0]=r[0]+f*o[0],A[1]=r[1]+f*o[1],A[2]=r[2]+f*o[2],A}})(),cartesianToBarycentric:(()=>{const e=new n(3),t=new n(3),i=new n(3);return(s,r,o,n,a)=>{const l=c.subVec3(n,r,e),A=c.subVec3(o,r,t),h=c.subVec3(s,r,i),u=c.dotVec3(l,l),d=c.dotVec3(l,A),p=c.dotVec3(l,h),f=c.dotVec3(A,A),g=c.dotVec3(A,h),m=u*f-d*d;if(0===m)return null;const _=1/m,v=(f*p-d*g)*_,b=(u*g-d*p)*_;return a[0]=1-v-b,a[1]=b,a[2]=v,a}})(),barycentricInsideTriangle(e){const t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian(e,t,i,s,r=c.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+i[0]*n+s[0]*a,r[1]=t[1]*o+i[1]*n+s[1]*a,r[2]=t[2]*o+i[2]*n+s[2]*a,r},mergeVertices(e,t,i,s){const r={},o=[],n=[],a=t?[]:null,l=i?[]:null,A=[];let h,c,u,d;const p=1e4;let f,g,m=0;for(f=0,g=e.length;f{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3),o=new n(3);return(n,a,l)=>{let A,h;const u=new Array(n.length/3);let d,p,f,g,m,_,v;for(A=0,h=a.length;A{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3),o=new n(3),a=new n(3);return(n,l,A)=>{const h=new Float32Array(n.length);for(let u=0;u>24&255,h=u>>16&255,A=u>>8&255,l=255&u,a=t[i],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+1],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+2],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,i={}){const s=i.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,A,h,u;const d=1e4;let p,f,g,m,_,v;for(f=0,m=e.length;f{const e=new n(4),t=new n(4);return(i,s,r,o,n)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=1,c.transformVec4(i,e,t),o[0]=t[0],o[1]=t[1],o[2]=t[2],e[0]=r[0],e[1]=r[1],e[2]=r[2],c.transformVec3(i,e,t),c.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new n(16),t=new n(4),i=new n(4),s=(t,i,s,r,o)=>{o[0]=t,o[1]=i,o[2]=s,o[3]=1,c.transformVec4(e,o,o),r||c.mulVec4Scalar(o,1/o[3])};return(r,o,n,a,l,A,h)=>{const u="ortho"===a;c.mulMat4(n,o,e),c.inverseMat4(e,e);const d=2*l[0]/r.width-1,p=1-2*l[1]/r.height;s(d,p,-1,u,t),s(d,p,1,u,i),A[0]=t[0],A[1]=t[1],A[2]=t[2],c.subVec3(i,t,h),c.normalizeVec3(h)}})(),canvasPosToLocalRay:(()=>{const e=new n(3),t=new n(3);return(i,s,r,o,n,a,l,A)=>{c.canvasPosToWorldRay(i,s,r,o,a,e,t),c.worldRayToLocalRay(n,e,t,l,A)}})(),worldRayToLocalRay:(()=>{const e=new n(16),t=new n(4),i=new n(4);return(s,r,o,n,a)=>{const l=c.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,c.transformVec4(l,t,i),n[0]=i[0],n[1]=i[1],n[2]=i[2],c.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(i,s,r,o){const a=new n(6),l={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:a};let A,h;for(a[0]=a[1]=a[2]=Number.POSITIVE_INFINITY,a[3]=a[4]=a[5]=Number.NEGATIVE_INFINITY,A=0,h=i.length;Aa[3]&&(a[3]=r[t]),r[t+1]a[4]&&(a[4]=r[t+1]),r[t+2]a[5]&&(a[5]=r[t+2])}}if(i.length<20||o>10)return l.triangles=i,l.leaf=!0,l;e[0]=a[3]-a[0],e[1]=a[4]-a[1],e[2]=a[5]-a[2];let u=0;e[1]>e[u]&&(u=1),e[2]>e[u]&&(u=2),l.splitDim=u;const d=(a[u]+a[u+3])/2,p=new Array(i.length);let f=0;const g=new Array(i.length);let m=0;for(A=0,h=i.length;A{const s=e.length/3,r=new Array(s);for(let e=0;e=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=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t}};c.buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=c.vec3(),h=c.vec3(),u=c.vec3(),d=c.vec3(),p=c.vec3(),f=c.vec3(),g=c.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;ux)||(T=i[F.index1],R=i[F.index2],(!L&&T>65535||R>65535)&&(L=!0),y.push(T),y.push(R));return L?new Uint32Array(y):new Uint16Array(y)}}(),c.planeClipsPositions3=function(e,t,i,s=3){for(let r=0,o=i.length;r=this._headLength){const e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}const e=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,e}push(e){return this._length++,this._tail.push(e),this}unshift(e){return this._head[--this._index]=e,this._length++,this}}const p={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var f=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r{};t=t||s,i=i||s;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var s=e.target.response;if(200===this.status){var r;try{r=JSON.parse(s)}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}t(r)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(s))}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else i(e)}),!1),r.addEventListener("error",(function(e){i(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,i){var s=e=>{};t=t||s,i=i||s;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const e=!!r[2];var o=r[3];o=window.decodeURIComponent(o),e&&(o=window.atob(o));try{const e=new ArrayBuffer(o.length),i=new Uint8Array(e);for(var n=0;n{t(e)}))}catch(e){M.scheduleTask((()=>{i(e)}))}}else{const s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i("loadArrayBuffer error : "+s.response))},s.send(null)}},queryString:m,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"==typeof e&&"number"==typeof e.length},isString:function(e){return"string"==typeof e||e instanceof String},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},isID:function(e){return _.isString(e)||_.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(_.isNumeric(e)||_.isString(e)?`${e}`:e.id)===(_.isNumeric(t)||_.isString(t)?`${t}`:t.id)},isFunction:function(e){return"function"==typeof e},isObject:function(e){const t={}.constructor;return!!e&&e.constructor===t},copy:function(e){return _.apply(e,{})},apply:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t},apply2:function(e,t){for(const i in e)e.hasOwnProperty(i)&&void 0!==e[i]&&null!==e[i]&&(t[i]=e[i]);return t},applyIf:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(void 0!==t[i]&&null!==t[i]||(t[i]=e[i]));return t},isEmptyObject:function(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return _.isNumeric(e)?`${e}`:`'${e}'`},concat:function(e,t){const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},flattenParentChildHierarchy:function(e){var t=[];return function e(i){i.id=i.uuid,delete i.oid,t.push(i);var s=i.children;if(s)for(var r=0,o=s.length;r{b.removeItem(e.id),delete M.scenes[e.id],delete v[e.id],p.components.scenes--}))},this.clear=function(){let e;for(const t in M.scenes)M.scenes.hasOwnProperty(t)&&(e=M.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete M.scenes[e.id]))},this.scheduleTask=function(e,t=null){y.push(e),y.push(t)},this.runTasks=function(e=-1){let t,i,s=(new Date).getTime(),r=0;for(;y.length>0&&(e<0||s0&&w>0){var t=1e3/w;C+=t,B.push(t),B.length>=30&&(C-=B.shift()),p.frame.fps=Math.round(C/B.length)}for(let e in M.scenes)M.scenes[e].compile();I(e),P=e};!function(e,t){let i=Date.now()+t;(function s(){const r=Date.now()-i;e(),i+=t,setTimeout(s,Math.max(0,t-r))})()}((()=>{E()}),100);const F=function(){let e=Date.now();if(w=e-P,P>0&&w>0){var t=1e3/w;C+=t,B.push(t),B.length>=30&&(C-=B.shift()),p.frame.fps=Math.round(C/B.length)}I(e),function(e){for(var t in x.time=e,M.scenes)if(M.scenes.hasOwnProperty(t)){var i=M.scenes[t];x.sceneId=t,x.startTime=i.startTime,x.deltaTime=null!=x.prevTime?x.time-x.prevTime:0,i.fire("tick",x,!0)}x.prevTime=e}(e),function(){const e=M.scenes,t=!1;let i,s,r,o,n;for(n in e)e.hasOwnProperty(n)&&(i=e[n],s=v[n],s||(s=v[n]={}),r=i.ticksPerOcclusionTest,s.ticksPerOcclusionTest!==r&&(s.ticksPerOcclusionTest=r,s.renderCountdown=r),--i.occlusionTestCountdown<=0&&(i.doOcclusionTest(),i.occlusionTestCountdown=r),o=i.ticksPerRender,s.ticksPerRender!==o&&(s.ticksPerRender=o,s.renderCountdown=o),0==--s.renderCountdown&&(i.render(t),s.renderCountdown=o))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(E):requestAnimationFrame(F)};function I(e){const t=M.runTasks(e+10),i=M.getNumTasks();p.frame.tasksRun=t,p.frame.tasksScheduled=i,p.frame.tasksBudget=10}F();class D{get type(){return"Component"}get isComponent(){return!0}constructor(e=null,t={}){if(this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=t.viewer;else{if("Scene"===e.type)this.scene=e;else{if(!(e instanceof D))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+_.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let i=e.component;const s=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(i&&(_.isNumeric(i)||_.isString(i))){const e=i;if(i=this.scene.components[e],!i)return void this.error("Component not found: "+_.inQuotes(e))}if(!i)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){i=e[t];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&(i=this.scene[t],!i))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+_.inQuotes(i.id));if(o&&!i.isType(o))return void this.error("Expected a "+o+" type or subtype: "+i.type+" "+_.inQuotes(i.id))}this._attachments||(this._attachments={});const l=this._attached[t];let A,h,c;if(l){if(i&&l.id===i.id)return;const e=this._attachments[l.id];for(A=e.subs,h=0,c=A.length;h{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():M.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}scheduleTask(e){M.scheduleTask(e,null)}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,i,s,r,o;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(t=this._attachments[e],i=t.component,s=t.subs,r=0,o=s.length;r=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class U{constructor(){this.planes=[new L,new L,new L,new L,new L,new L]}}function O(e,t,i){const s=c.mulMat4(i,t,R),r=s[0],o=s[1],n=s[2],a=s[3],l=s[4],A=s[5],h=s[6],u=s[7],d=s[8],p=s[9],f=s[10],g=s[11],m=s[12],_=s[13],v=s[14],b=s[15];e.planes[0].set(a-r,u-l,g-d,b-m),e.planes[1].set(a+r,u+l,g+d,b+m),e.planes[2].set(a-o,u-A,g-p,b-_),e.planes[3].set(a+o,u+A,g+p,b+_),e.planes[4].set(a-n,u-h,g-f,b-v),e.planes[5].set(a+n,u+h,g+f,b+v)}function k(e,t){let i=U.INSIDE;const s=S,r=T;s[0]=t[0],s[1]=t[1],s[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[s,r];for(let t=0;t<6;++t){const s=e.planes[t];if(s.normal[0]*o[s.testVertex[0]][0]+s.normal[1]*o[s.testVertex[1]][1]+s.normal[2]*o[s.testVertex[2]][2]+s.offset<0)return U.OUTSIDE;s.normal[0]*o[1-s.testVertex[0]][0]+s.normal[1]*o[1-s.testVertex[1]][1]+s.normal[2]*o[1-s.testVertex[2]][2]+s.offset<0&&(i=U.INTERSECT)}return i}U.INSIDE=0,U.INTERSECT=1,U.OUTSIDE=2;class N extends D{constructor(e={}){if(!e.viewer)throw"[MarqueePicker] Missing config: viewer";if(!e.objectsKdTree3)throw"[MarqueePicker] Missing config: objectsKdTree3";super(e.viewer.scene,e),this.viewer=e.viewer,this._objectsKdTree3=e.objectsKdTree3,this._canvasMarqueeCorner1=c.vec2(),this._canvasMarqueeCorner2=c.vec2(),this._canvasMarquee=c.AABB2(),this._marqueeFrustum=new U,this._marqueeFrustumProjMat=c.mat4(),this._pickMode=!1,this._marqueeElement=document.createElement("div"),document.body.appendChild(this._marqueeElement),this._marqueeElement.style.position="absolute",this._marqueeElement.style["z-index"]="40000005",this._marqueeElement.style.width="8px",this._marqueeElement.style.height="8px",this._marqueeElement.style.visibility="hidden",this._marqueeElement.style.top="0px",this._marqueeElement.style.left="0px",this._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",this._marqueeElement.style.opacity=1,this._marqueeElement.style["pointer-events"]="none"}setMarqueeCorner1(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarqueeCorner2(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarquee(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}setMarqueeVisible(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}getMarqueeVisible(){return this._marqueVisible}setPickMode(e){if(e!==N.PICK_MODE_INSIDE&&e!==N.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===N.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}getPickMode(){return this._pickMode}clear(){this.fire("clear",{})}pick(){this._updateMarquee(),this._buildMarqueeFrustum();const e=[],t=(i,s=U.INTERSECT)=>{if(s===U.INTERSECT&&(s=k(this._marqueeFrustum,i.aabb)),s!==U.OUTSIDE){if(i.entities){const t=i.entities;for(let i=0,s=t.length;i3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&t(this._objectsKdTree3.root),this.fire("picked",e),e}_updateMarquee(){this._canvasMarquee[0]=Math.min(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[1]=Math.min(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._canvasMarquee[2]=Math.max(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[3]=Math.max(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._marqueeElement.style.width=this._canvasMarquee[2]-this._canvasMarquee[0]+"px",this._marqueeElement.style.height=this._canvasMarquee[3]-this._canvasMarquee[1]+"px",this._marqueeElement.style.left=`${this._canvasMarquee[0]}px`,this._marqueeElement.style.top=`${this._canvasMarquee[1]}px`}_buildMarqueeFrustum(){const e=this.viewer.scene.canvas.canvas,t=e.clientWidth,i=e.clientHeight,s=e.clientLeft,r=e.clientTop,o=2/t,n=2/i,a=e.clientHeight/e.clientWidth,l=(this._canvasMarquee[0]-s)*o-1,A=(this._canvasMarquee[2]-s)*o-1,h=-(this._canvasMarquee[3]-r)*n+1,u=-(this._canvasMarquee[1]-r)*n+1,d=this.viewer.scene.camera.frustum.near*(17*a);c.frustumMat4(l,A,h*a,u*a,d,1e4,this._marqueeFrustumProjMat),O(this._marqueeFrustum,this.viewer.scene.camera.viewMatrix,this._marqueeFrustumProjMat)}destroy(){super.destroy(),this._marqueeElement.parentElement&&(this._marqueeElement.parentElement.removeChild(this._marqueeElement),this._marqueeElement=null,this._objectsKdTree3=null)}}N.PICK_MODE_INTERSECTS=0,N.PICK_MODE_INSIDE=1;class Q{constructor(e,t={}){this.viewer=e,this.scene=this.viewer.scene,this._circleDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._circleDiv,this.viewer.scene.canvas.canvas),this._circleDiv.style.backgroundColor="transparent",this._circleDiv.style.border="2px solid green",this._circleDiv.style.borderRadius="50px",this._circleDiv.style.width="50px",this._circleDiv.style.height="50px",this._circleDiv.style.margin="-200px -200px",this._circleDiv.style.zIndex="100000",this._circleDiv.style.position="absolute",this._circleDiv.style.pointerEvents="none",this._circlePos=null,this._circleMaxRadius=200,this._circleMinRadius=2,this._active=!1!==t.active,this._visible=!1,this._running=!1,this._destroyed=!1}start(e){if(this._destroyed)return;this._circlePos=e,this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius=`${this._circleRadius}px`,this._circleDiv.style.marginLeft=this._circlePos[0]-this._circleRadius+"px",this._circleDiv.style.marginTop=this._circlePos[1]-this._circleRadius+"px";const t=this._circleMaxRadius;let i;const s=e=>{if(!this._running)return;i||(i=e);const r=e-i,o=Math.min(r/300,1),n=t+(2-t)*o;this._circleRadius=n,this._circleDiv.style.width=`${this._circleRadius}px`,this._circleDiv.style.height=`${this._circleRadius}px`,this._circleDiv.style.marginLeft=this._circlePos[0]-this._circleRadius/2+"px",this._circleDiv.style.marginTop=this._circlePos[1]-this._circleRadius/2+"px",o<1&&requestAnimationFrame(s)};this._running=!0,requestAnimationFrame(s),this._circleDiv.style.visibility="visible"}stop(){this._destroyed||(this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius=`${this._circleRadius}px`,this._circleDiv.style.visibility="hidden")}set durationMs(e){this.stop(),this._durationMs=e}get durationMs(){return this._durationMs}destroy(){this._destroyed||(this.stop(),this._circleDiv.parentElement.removeChild(this._circleDiv),this._destroyed=!0)}}class V{constructor(e,t,i){this.id=i&&i.id?i.id:e,this.viewer=t,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,t.addPlugin(this)}scheduleTask(e){M.scheduleTask(e,null)}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}const H={isIphoneSafari(){const e=window.navigator.userAgent,t=/iPhone/i.test(e),i=/Safari/i.test(e)&&!/Chrome/i.test(e);return t&&i}};class j{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!1!==t.visible,this._culled=!1;var i=this._dot,s=i.style;s["border-radius"]="25px",s.border="solid 2px white",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,s.width="8px",s.height="8px",s.visibility=this._visible?"visible":"hidden",s.top="0px",s.left="0px",s["box-shadow"]="0 2px 5px 0 #182A3D;",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._dotClickable,o=r.style;o["border-radius"]="35px",o.border="solid 10px white",o.position="absolute",o["z-index"]=void 0===t.zIndex?"40000007":t.zIndex+1,o.width="8px",o.height="8px",o.visibility="visible",o.top="0px",o.left="0px",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),r.addEventListener("click",(t=>{e.dispatchEvent(new MouseEvent("mouseover",t))})),t.onMouseOver&&r.addEventListener("mouseover",(i=>{t.onMouseOver(i,this),e.dispatchEvent(new MouseEvent("mouseover",i))})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onTouchstart&&r.addEventListener("touchstart",(e=>{t.onTouchstart(e,this)})),t.onTouchmove&&r.addEventListener("touchmove",(e=>{t.onTouchmove(e,this)})),t.onTouchend&&r.addEventListener("touchend",(e=>{t.onTouchend(e,this)})),t.onContextMenu&&(H.isIphoneSafari()?(r.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),r.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):r.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")}))),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.borderColor)}setPos(e,t){this._x=e,this._y=t;var i=this._dot.style;i.left=Math.round(e)-4+"px",i.top=Math.round(t)-4+"px";var s=this._dotClickable.style;s.left=Math.round(e)-9+"px",s.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}const G=c.vec3(),z=function(){const e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,o){return o=o||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,c.transformVec4(s,t,i),c.setMat4Translation(s,i,o),o.slice()}}();function W(e,t,i){const s=Float32Array.from([e[0]])[0],r=e[0]-s,o=Float32Array.from([e[1]])[0],n=e[1]-o,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=s,t[1]=o,t[2]=a,i[0]=r,i[1]=n,i[2]=l}function K(e,t,i,s=1e3){const r=c.getPositionsCenter(e,G),o=Math.round(r[0]/s)*s,n=Math.round(r[1]/s)*s,a=Math.round(r[2]/s)*s;i[0]=o,i[1]=n,i[2]=a;const l=0!==i[0]||0!==i[1]||0!==i[2];if(l)for(let i=0,s=e.length;i0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,i=this.meshes[0]._colorize[3];let s=255;if(t){if(e<0?e=0:e>1&&(e=1),s=Math.floor(255*e),i===s)return}else if(s=255,i===s)return;for(let e=0,t=this.meshes.length;e=0&&(e+=i)}return e>0?e:-1}_getFlag(e){return!!(this._flags&e)}_finalize(){const e=this.model.scene;this._isObject&&(this.visible&&e._objectVisibilityUpdated(this),this.highlighted&&e._objectHighlightedUpdated(this),this.xrayed&&e._objectXRayedUpdated(this),this.selected&&e._objectSelectedUpdated(this));for(let e=0,t=this.meshes.length;e{this._viewPosDirty=!0,this._needUpdate()})),this._onCameraProjMatrix=this.scene.camera.on("projMatrix",(()=>{this._canvasPosDirty=!0,this._needUpdate()})),this._onEntityDestroyed=null,this._onEntityModelDestroyed=null,this._renderer.addMarker(this),this.entity=t.entity,this.worldPos=t.worldPos,this.occludable=t.occludable}_update(){if(this._viewPosDirty&&(c.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){ae.set(this._viewPos),ae[3]=1,c.transformPoint4(this.scene.camera.projMatrix,ae,le);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+le[0]/le[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-le[1]/le[3])*e[3]/2),this._canvasPosDirty=!1,this.fire("canvasPos",this._canvasPos)}}_setVisible(e){this._visible,this._visible=e,this.fire("visible",this._visible)}set entity(e){if(this._entity){if(this._entity===e)return;null!==this._onEntityDestroyed&&(this._entity.model?this._entity.model.off(this._onEntityDestroyed):this._entity.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model&&this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null)}this._entity=e,this._entity&&(this._entity instanceof ne?this._onEntityModelDestroyed=this._entity.model.on("destroyed",(()=>{this._entity=null,this._onEntityModelDestroyed=null})):this._onEntityDestroyed=this._entity.on("destroyed",(()=>{this._entity=null,this._onEntityDestroyed=null}))),this.fire("entity",this._entity,!0)}get entity(){return this._entity}set occludable(e){(e=!!e)!==this._occludable&&(this._occludable=e,this._occludable&&this._renderer.markerWorldPosUpdated(this))}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),W(this._worldPos,this._origin,this._rtcPos),this._occludable&&this._renderer.markerWorldPosUpdated(this),this._viewPosDirty=!0,this.fire("worldPos",this._worldPos),this._needUpdate()}get worldPos(){return this._worldPos}get origin(){return this._origin}get rtcPos(){return this._rtcPos}get viewPos(){return this._update(),this._viewPos}get canvasPos(){return this._update(),this._canvasPos}get visible(){return!!this._visible}destroy(){this.fire("destroyed",!0),this.scene.camera.off(this._onCameraViewMatrix),this.scene.camera.off(this._onCameraProjMatrix),this._entity&&(null!==this._onEntityDestroyed&&this._entity.model.off(this._onEntityDestroyed),null!==this._onEntityModelDestroyed&&this._entity.model.off(this._onEntityModelDestroyed)),this._renderer.removeMarker(this),super.destroy()}}const he=()=>{};function ce(e,t,i){const s=e.getBoundingClientRect(),r=t.getBoundingClientRect();i[0]+=s.left-r.left,i[1]+=s.top-r.top}class ue extends Ae{constructor(e,t,i,s={}){super(e,t);const r=(e,t)=>i=>{e&&e(i),this.fire(t,i,!0)};this._dot=new j(i,{fillColor:s.fillColor,zIndex:s.zIndex,onMouseOver:r(s.onMouseOver,"mouseover"),onMouseLeave:r(s.onMouseLeave,"mouseleave"),onMouseWheel:r(s.onMouseWheel,"wheel"),onMouseDown:r(s.onMouseDown,"mousedown"),onMouseUp:r(s.onMouseUp,"mouseup"),onMouseMove:r(s.onMouseMove,"mousemove"),onTouchstart:r(s.onTouchstart,"touchstart"),onTouchmove:r(s.onTouchmove,"touchmove"),onTouchend:r(s.onTouchend,"touchend"),onContextMenu:r(s.onContextMenu,"contextmenu")});const o=()=>{const t=this.canvasPos.slice();ce(e.canvas.canvas,i,t),this._dot.setPos(t[0],t[1])};this.on("worldPos",o);const n=e.camera.on("viewMatrix",o),a=e.camera.on("projMatrix",o);this._cleanup=()=>{e.camera.off(n),e.camera.off(a),this._dot.destroy()}}setClickable(e){this._dot.setClickable(e)}setCulled(e){this._dot.setCulled(e)}setFillColor(e){this._dot.setFillColor(e)}setHighlighted(e){this._dot.setHighlighted(e)}setOpacity(e){this._dot.setOpacity(e)}setVisible(e){this._dot.setVisible(e)}destroy(){this._cleanup(),super.destroy()}}function de(e,t){const i=function(e,i){if(e in t)return t[e];if(void 0!==i)return i;throw"config missing: "+e},s=i("viewer"),r=i("ray2WorldPos"),o=i("handleMouseEvents",!1),n=i("handleTouchEvents",!1),a=i("onStart",he),l=i("onMove",he),A=i("onEnd",he),h=s.scene,u=h.canvas.canvas,d=e=>{const t=c.vec2([e.clientX,e.clientY]);ce(u.ownerDocument.documentElement,u,t),l(t,(e=>{const t=c.vec3(),i=c.vec3();return c.canvasPosToWorldRay(u,h.camera.viewMatrix,h.camera.projMatrix,h.camera.projection,e,t,i),r(t,i,e)})(t))};let p=null;const f=function(e){const t=p.matchesEvent(e);t&&d(t)},g=function(t){const i=p.matchesEvent(t);i&&(e.setOpacity(b),p.cleanup(),d(i),A())},m=function(t,i){p&&p.cleanup(),e.setOpacity(1),e.setClickable(!1),s.cameraControl.active=!1,p={matchesEvent:t,cleanup:function(){p=null,e.setClickable(!0),s.cameraControl.active=!0,i()}},a()},_=[],v=function(t,i){const s=e.on(t,i);_.push((()=>e.off(s)))};if(o&&(v("mouseover",(()=>!p&&e.setOpacity(1))),v("mouseleave",(()=>!p&&e.setOpacity(b))),v("mousedown",(e=>{1===e.which&&(u.addEventListener("mousemove",f),u.addEventListener("mouseup",g),m((e=>1===e.which&&e),(()=>{u.removeEventListener("mousemove",f),u.removeEventListener("mouseup",g)})))}))),n){let e;v("touchstart",(t=>{t.preventDefault(),1===t.touches.length&&(e=t.touches[0].identifier,m((t=>[...t.changedTouches].find((t=>t.identifier===e))),(()=>{e=null})))})),v("touchmove",(e=>{e.preventDefault(),f(e)})),v("touchend",(e=>{e.preventDefault(),g(e)}))}const b=.8;return e.setOpacity(b),function(){p&&p.cleanup(),_.forEach((e=>e())),e.setOpacity(1)}}function pe(e){const t=function(t,i){if(t in e)return e[t];if(void 0!==i)return i;throw"config missing: "+t},i=t("viewer"),s=t("handleMouseEvents",!1),r=t("handleTouchEvents",!1),o=t("pointerLens",null),n=t("dots"),a=t("ray2WorldPos"),l=t("onEnd",he),A=o?function(e){o.visible=!!e,e&&(o.canvasPos=e)}:()=>{},h=n.map((e=>{let t;return de(e,{handleMouseEvents:s,handleTouchEvents:r,viewer:i,ray2WorldPos:(e,i,s)=>a(e,i,s)||t,onStart:()=>{t=e.worldPos.slice(),c(!1,e)},onMove:(t,i)=>{A(t),e.worldPos=i},onEnd:()=>{l(t,e)||(e.worldPos=t),A(null),c(!0,e)}})})),c=(e,t)=>n.forEach((i=>i!==t&&i.setClickable(e)));return c(!0),function(){h.forEach((e=>e())),A(null)}}const fe=function(e,t,i){return function(s,r,o){const n=e.scene,a=n.canvas.canvas,l=(e,t)=>(t[0]=e.clientX,t[1]=e.clientY,ce(a.ownerDocument.documentElement,a,t),t),A=e=>{const t=c.vec3(),s=c.vec3();return c.canvasPosToWorldRay(a,n.camera.viewMatrix,n.camera.projMatrix,n.camera.projection,e,t,s),i(t,s)};let h=null;const u=()=>{};let d,p=u;const f=function(){t.stop(),clearTimeout(h),e.cameraControl.active=!0,p=u,d=null},g=function(){f(),a.removeEventListener("touchstart",m),a.removeEventListener("touchmove",_),a.removeEventListener("touchend",v)},m=function(i){const o=i.touches;if(1!==o.length)f(),s();else{const i=o[0],s=l(i,c.vec2());A(s)&&(d=i.identifier,p=e=>{c.distVec2(s,e)>20&&f()},h=setTimeout((function(){t.start(s),h=setTimeout((function(){t.stop(),e.cameraControl.active=!1,p=e=>{r(e,A(e))},p(s)}),300)}),250))}};a.addEventListener("touchstart",m,{passive:!0});const _=function(e){const t=[...e.changedTouches].find((e=>e.identifier===d));t&&p(l(t,c.vec2()))};a.addEventListener("touchmove",_,{passive:!0});const v=function(e){const t=[...e.changedTouches].find((e=>e.identifier===d));if(t){g();const e=l(t,c.vec2());o(e,A(e))}};return a.addEventListener("touchend",v,{passive:!0}),g}};class ge{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6,this._visible=!0,this._culled=!1;var i=this._wire,s=i.style;s.border="solid "+this._thickness+"px "+this._color,s.position="absolute",s["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,s.width="0px",s.height="0px",s.visibility="visible",s.top="0px",s.left="0px",s["-webkit-transform-origin"]="0 0",s["-moz-transform-origin"]="0 0",s["-ms-transform-origin"]="0 0",s["-o-transform-origin"]="0 0",s["transform-origin"]="0 0",s["-webkit-transform"]="rotate(0deg)",s["-moz-transform"]="rotate(0deg)",s["-ms-transform"]="rotate(0deg)",s["-o-transform"]="rotate(0deg)",s.transform="rotate(0deg)",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._wireClickable,o=r.style;o.border="solid "+this._thicknessClickable+"px "+this._color,o.position="absolute",o["z-index"]=void 0===t.zIndex?"2000002":t.zIndex+1,o.width="0px",o.height="0px",o.visibility="visible",o.top="0px",o.left="0px",o["-webkit-transform-origin"]="0 0",o["-moz-transform-origin"]="0 0",o["-ms-transform-origin"]="0 0",o["-o-transform-origin"]="0 0",o["transform-origin"]="0 0",o["-webkit-transform"]="rotate(0deg)",o["-moz-transform"]="rotate(0deg)",o["-ms-transform"]="rotate(0deg)",o["-o-transform"]="rotate(0deg)",o.transform="rotate(0deg)",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),t.onMouseOver&&r.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&(H.isIphoneSafari()?(r.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),r.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):r.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")}))),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}get visible(){return"visible"===this._wire.style.visibility}_update(){var e=Math.abs(Math.sqrt((this._x1-this._x2)*(this._x1-this._x2)+(this._y1-this._y2)*(this._y1-this._y2))),t=180*Math.atan2(this._y2-this._y1,this._x2-this._x1)/Math.PI,i=this._wire.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)";var s=this._wireClickable.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)"}setStartAndEnd(e,t,i,s){this._x1=e,this._y1=t,this._x2=i,this._y2=s,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class me{constructor(e,t={}){this._highlightClass="viewer-ruler-label-highlighted",this._prefix=t.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label",this._timeout=null;var i=this._label,s=i.style;s["border-radius"]="5px",s.color="white",s.padding="4px",s.border="solid 1px",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,s.width="auto",s.height="auto",s.visibility="visible",s.top="0px",s.left="0px",s["pointer-events"]="all",s.opacity=1,t.onContextMenu,i.innerText="",e.appendChild(i),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&i.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&i.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&i.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&i.addEventListener("mousedown",(e=>{t.onMouseDown(e,this),e.stopPropagation()})),t.onMouseUp&&i.addEventListener("mouseup",(e=>{t.onMouseUp(e,this),e.stopPropagation()})),t.onMouseMove&&i.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&(H.isIphoneSafari()?(i.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),i.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):i.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")})))}setPos(e,t){this._x=e,this._y=t;var i=this._label.style;i.left=Math.round(e)-20+"px",i.top=Math.round(t)-12+"px"}setPosOnWire(e,t,i,s){var r=e+.5*(i-e),o=t+.5*(s-t),n=this._label.style;n.left=Math.round(r)-20+"px",n.top=Math.round(o)-12+"px"}setPosBetweenWires(e,t,i,s,r,o){var n=(e+i+r)/3,a=(t+s+o)/3,l=this._label.style;l.left=Math.round(n)-20+"px",l.top=Math.round(a)-12+"px"}setText(e){this._label.innerHTML=this._prefix+(e||"")}setFillColor(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}setBorderColor(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}setOpacity(e){this._label.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}setClickable(e){this._label.style["pointer-events"]=e?"all":"none"}setPrefix(e){this._prefix!==e&&(this._prefix=e)}destroy(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}var _e=c.vec3(),ve=c.vec3();class be extends D{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._color=t.color||e.defaultColor;var i=this.plugin.viewer.scene;this._originWorld=c.vec3(),this._cornerWorld=c.vec3(),this._targetWorld=c.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},l=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))};this._originDot=new ue(i,t.origin,this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._cornerDot=new ue(i,t.corner,this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetDot=new ue(i,t.target,this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._originWire=new ge(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetWire=new ge(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._angleLabel=new me(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._cornerVisible=!1,this._targetVisible=!1,this._originWireVisible=!1,this._targetWireVisible=!1,this._angleVisible=!1,this._labelsVisible=!1,this._clickable=!1,this._originDot.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._cornerDot.on("worldPos",(e=>{this._cornerWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetDot.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(c.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){const d=-.3,p=this._originDot.viewPos[2],f=this._cornerDot.viewPos[2],g=this._targetDot.viewPos[2];if(p>d||f>d||g>d)return this._originDot.setVisible(!1),this._cornerDot.setVisible(!1),this._targetDot.setVisible(!1),this._originWire.setVisible(!1),this._targetWire.setVisible(!1),void this._angleLabel.setCulled(!0);c.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,i=this._cp,s=e.canvas.canvas.getBoundingClientRect();const m=this._container.getBoundingClientRect();for(var r=s.top-m.top,o=s.left-m.left,n=e.canvas.boundary,a=n[2],l=n[3],A=0,h=0,u=t.length;he.offsetTop+(e.offsetParent&&e.offsetParent!==t.parentNode&&h(e.offsetParent)),u=e=>e.offsetLeft+(e.offsetParent&&e.offsetParent!==t.parentNode&&u(e.offsetParent)),d=c.vec2(),p=e=>{e.snappedToVertex||e.snappedToEdge?(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.canvasPos,s.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red");const i=e.snappedCanvasPos||e.canvasPos;switch(r=!0,o=e.entity,l.set(e.worldPos),A.set(i),this._mouseState){case 0:this._canvasToPagePos?(this._canvasToPagePos(t,i,d),this.markerDiv.style.left=d[0]-5+"px",this.markerDiv.style.top=d[1]-5+"px"):(this.markerDiv.style.left=u(t)+i[0]-5+"px",this.markerDiv.style.top=h(t)+i[1]-5+"px");break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos,this._currentAngleMeasurement.corner.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos,this._currentAngleMeasurement.target.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer"}};this._onHoverSnapOrSurface=i.on("hoverSnapOrSurface",(e=>{this._snapping&&p(e)})),this._onHoverSurface=i.on("hoverSurface",(e=>{this._snapping||p(e)})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(n=e.clientX,a=e.clientY)}),t.addEventListener("mouseup",this._onMouseUp=e=>{if(1===e.which&&!(e.clientX>n+20||e.clientXa+20||e.clientY{if(r=!1,s&&(s.visible=!0,s.pointerPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!1),this.markerDiv.style.left="-100px",this.markerDiv.style.top="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}};this._onHoverSnapOrSurfaceOff=i.on("hoverSnapOrSurfaceOff",(e=>{this._snapping&&f(e)})),this._onHoverOff=i.on("hoverOff",(e=>{this._snapping||f(e)})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onHoverSnapOrSurface),t.off(this._onHoverSurface),t.off(this._onHoverSnapOrSurfaceOff),t.off(this._onHoverOff),this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}get currentMeasurement(){return this._currentAngleMeasurement}destroy(){this.deactivate(),super.destroy()}}class Be extends D{constructor(e,t,i,s){const r=e.plugin.viewer;super(r.scene);const o=pe({viewer:r,handleMouseEvents:i,handleTouchEvents:s,pointerLens:t.pointerLens,dots:[e.origin,e.corner,e.target],ray2WorldPos:(e,i,s)=>{const o=e=>{const t=r.scene.pick({canvasPos:s,snapToEdge:e,snapToVertex:e,pickSurface:!0});return t&&t.worldPos?t.worldPos:e&&o(!1)};return o(!!t.snapping)},onEnd:(e,t)=>{const i=!c.compareVec3(e,t.worldPos);return i&&this.fire("edited"),i}}),n=e.on("destroyed",o);this._deactivate=function(){e.off("destroyed",n),o()}}deactivate(){this._deactivate(),super.destroy()}}const we=c.vec3(),Pe=c.vec3(),Ce=c.vec3();class Me extends Ae{constructor(e,t){if(super(e,t),this.plugin=t.plugin,this._container=t.container,!this._container)throw"config missing: container";if(!t.markerElement&&!t.markerHTML)throw"config missing: need either markerElement or markerHTML";if(!t.labelElement&&!t.labelHTML)throw"config missing: need either labelElement or labelHTML";this._htmlDirty=!1,t.markerElement?(this._marker=t.markerElement,this._marker.addEventListener("click",this._onMouseClickedExternalMarker=()=>{this.plugin.fire("markerClicked",this)}),this._marker.addEventListener("contextmenu",this._onContextMenuExtenalMarker=()=>{this.plugin.fire("contextmenu",this)}),this._marker.addEventListener("mouseenter",this._onMouseEnterExternalMarker=()=>{this.plugin.fire("markerMouseEnter",this)}),this._marker.addEventListener("mouseleave",this._onMouseLeaveExternalMarker=()=>{this.plugin.fire("markerMouseLeave",this)}),this._markerExternal=!0):(this._markerHTML=t.markerHTML,this._htmlDirty=!0,this._markerExternal=!1),t.labelElement?(this._label=t.labelElement,this._labelExternal=!0):(this._labelHTML=t.labelHTML,this._htmlDirty=!0,this._labelExternal=!1),this._markerShown=!!t.markerShown,this._labelShown=!!t.labelShown,this._values=t.values||{},this._layoutDirty=!0,this._visibilityDirty=!0,this._labelPosition=24,this._buildHTML(),this._onTick=this.scene.on("tick",(()=>{this._htmlDirty&&(this._buildHTML(),this._htmlDirty=!1,this._layoutDirty=!0,this._visibilityDirty=!0),(this._layoutDirty||this._visibilityDirty)&&(this._markerShown||this._labelShown)&&(this._updatePosition(),this._layoutDirty=!1),this._visibilityDirty&&(this._marker.style.visibility=this.visible&&this._markerShown?"visible":"hidden",this._label.style.visibility=this.visible&&this._markerShown&&this._labelShown?"visible":"hidden",this._visibilityDirty=!1)})),this.on("canvasPos",(()=>{this._layoutDirty=!0})),this.on("visible",(()=>{this._visibilityDirty=!0})),this.setMarkerShown(!1!==t.markerShown),this.setLabelShown(t.labelShown),this.eye=t.eye?t.eye.slice():null,this.look=t.look?t.look.slice():null,this.up=t.up?t.up.slice():null,this.projection=t.projection}_buildHTML(){if(!this._markerExternal){this._marker&&(this._container.removeChild(this._marker),this._marker=null);let e=this._markerHTML||"

";_.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e.trim());const t=document.createRange().createContextualFragment(e);this._marker=t.firstChild,this._container.appendChild(this._marker),this._marker.style.visibility=this._markerShown?"visible":"hidden",this._marker.addEventListener("click",(()=>{this.plugin.fire("markerClicked",this)})),this._marker.addEventListener("contextmenu",(e=>{e.preventDefault(),this.plugin.fire("contextmenu",this)})),this._marker.addEventListener("mouseenter",(()=>{this.plugin.fire("markerMouseEnter",this)})),this._marker.addEventListener("mouseleave",(()=>{this.plugin.fire("markerMouseLeave",this)})),this._marker.addEventListener("wheel",(e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))}))}if(!this._labelExternal){this._label&&(this._container.removeChild(this._label),this._label=null);let e=this._labelHTML||"

";_.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e.trim());const t=document.createRange().createContextualFragment(e);this._label=t.firstChild,this._container.appendChild(this._label),this._label.style.visibility=this._markerShown&&this._labelShown?"visible":"hidden",this._label.addEventListener("wheel",(e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))}))}}_updatePosition(){const e=e=>e+"px",t=this.scene.canvas.boundary,i=t[0]+this.canvasPos[0],s=t[1]+this.canvasPos[1],r=this._marker.getBoundingClientRect().width,o=i+("right"===this._markerAlign?-1:"center"===this._markerAlign?0:1)*(r/2-12);this._marker.style.left=e(o-r/2),this._marker.style.top=e(s-12),this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;const n=this._label.getBoundingClientRect().width,a=Math.sign(this._labelPosition);this._label.style.left=e(o+a*(r/2+Math.abs(this._labelPosition)+n/2)-n/2),this._label.style.top=e(s-17),this._label.style["z-index"]=90005+Math.floor(this._viewPos[2])+1}_renderTemplate(e){for(var t in this._values)if(this._values.hasOwnProperty(t)){const i=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),i)}return e}setFromPickResult(e){if(e.worldPos&&e.worldNormal){const t=c.normalizeVec3(e.worldNormal,we),i=this.plugin&&this.plugin.surfaceOffset||0,s=c.mulVec3Scalar(t,i,Pe),r=c.addVec3(e.worldPos,s,Ce);this.entity=e.entity,this.worldPos=r}else this.error("Param 'pickResult' does not have both worldPos and worldNormal")}setMarkerAlign(e){const t=["left","center","right"];t.includes(e)?(this._markerAlign=e,this._updatePosition()):this.error("Param 'align' should be one of: "+JSON.stringify(t))}setLabelPosition(e){"number"!=typeof e?this.error("Param 'position' is not a number"):0===e?this.error("Param 'position' is zero"):(this._labelPosition=e,this._updatePosition())}setMarkerShown(e){e=!!e,this._markerShown!==e&&(this._markerShown=e,this._visibilityDirty=!0)}getMarkerShown(){return this._markerShown}setLabelShown(e){e=!!e,this._labelShown!==e&&(this._labelShown=e,this._visibilityDirty=!0)}getLabelShown(){return this._labelShown}setField(e,t){this._values[e]=t||"",this._htmlDirty=!0}getField(e){return this._values[e]}setValues(e){for(var t in e)if(e.hasOwnProperty(t)){const i=e[t];this.setField(t,i)}}getValues(){return this._values}destroy(){this._marker&&(this._markerExternal?(this._marker.removeEventListener("click",this._onMouseClickedExternalMarker),this._marker.removeEventListener("contextmenu",this._onContextMenuExtenalMarker),this._marker.removeEventListener("mouseenter",this._onMouseEnterExternalMarker),this._marker.removeEventListener("mouseleave",this._onMouseLeaveExternalMarker),this._marker=null):(this._marker.parentNode.removeChild(this._marker),this._marker=null)),this._label&&(this._labelExternal||this._label.parentNode.removeChild(this._label),this._label=null),this.scene.off(this._onTick),super.destroy()}}class Ee extends D{get type(){return"Spinner"}constructor(e,t={}){super(e,t),this._canvas=t.canvas,this._element=null,this._isCustom=!1,t.elementId&&(this._element=document.getElementById(t.elementId),this._element?this._adjustPosition():this.error("Can't find given Spinner HTML element: '"+t.elementId+"' - will automatically create default element")),this._element||this._createDefaultSpinner(),this.processes=0}_createDefaultSpinner(){this._injectDefaultCSS();const e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='
',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){const e="xeokit-spinner-css";if(document.getElementById(e))return;const t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}_adjustPosition(){if(this._isCustom)return;const e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const Fe=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class Ie extends D{constructor(e,t={}){super(e,t),this._backgroundColor=c.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const i=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),i.scene._webglContextLost(),i.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){i._initWebGL(),i.gl&&(i.scene._webglContextRestored(i.gl),i.fire("webglcontextrestored",i.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let s=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(s=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{s&&(s=!1,i.canvas.width=Math.round(i.canvas.clientWidth*i._resolutionScale),i.canvas.height=Math.round(i.canvas.clientHeight*i._resolutionScale),i.boundary[0]=i.canvas.offsetLeft,i.boundary[1]=i.canvas.offsetTop,i.boundary[2]=i.canvas.clientWidth,i.boundary[3]=i.canvas.clientHeight,i.fire("boundary",i.boundary))})),this._spinner=new Ee(this.scene,{canvas:this.canvas,elementId:t.spinnerElementId})}get type(){return"Canvas"}get backgroundColorFromAmbientLight(){return this._backgroundColorFromAmbientLight}set backgroundColorFromAmbientLight(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}get backgroundColor(){return this._backgroundColor}set backgroundColor(e){e?(this._backgroundColor[0]=e[0],this._backgroundColor[1]=e[1],this._backgroundColor[2]=e[2]):(this._backgroundColor[0]=1,this._backgroundColor[1]=1,this._backgroundColor[2]=1),this.glRedraw()}get resolutionScale(){return this._resolutionScale}set resolutionScale(e){if((e=e||1)===this._resolutionScale)return;this._resolutionScale=e;const t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}get spinner(){return this._spinner}_createCanvas(){const e="xeokit-canvas-"+c.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+='',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&&e0?Se.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?Se.FS_MAX_FLOAT_PRECISION="mediump":Se.FS_MAX_FLOAT_PRECISION="lowp":Se.FS_MAX_FLOAT_PRECISION="mediump",Se.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),Se.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),Se.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),Se.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),Se.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),Se.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),Se.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),Se.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),Se.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),Se.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){Se.SUPPORTED_EXTENSIONS[e]=!0})))}class Re{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get snappedCanvasPos(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null}set snappedCanvasPos(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}get worldPos(){return this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}get snapped(){return this.snappedToEdge||this.snappedToVertex}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}class Le{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;e0&&"/"===i.charAt(s+1)&&(i=i.substring(0,s)),t.push(i);return t.join("\n")}function Qe(e){console.error(e.join("\n"))}class Ve{constructor(e,t){this.id=ke.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 Le(e,e.VERTEX_SHADER,Ne(this.source.vertex)),this._fragmentShader=new Le(e,e.FRAGMENT_SHADER,Ne(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void Qe(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void Qe(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void Qe(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void Qe(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 Qe(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;ithis.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}setData(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}bind(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}unbind(){this.allocated&&this._gl.bindBuffer(this.type,null)}destroy(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}class je{constructor(e,t){this.scene=e,this.aabb=c.AABB3(),this.origin=c.vec3(t),this.originHash=this.origin.join(),this.numMarkers=0,this.markers={},this.markerList=[],this.markerIndices={},this.positions=[],this.indices=[],this.positionsBuf=null,this.lenPositionsBuf=0,this.indicesBuf=null,this.sectionPlanesActive=[],this.culledBySectionPlanes=!1,this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.aabbDirty=!1,this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!1}addMarker(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}markerWorldPosUpdated(e){if(!this.markers[e.id])return;const t=this.markerIndices[e.id];this.positions[3*t+0]=e.worldPos[0],this.positions[3*t+1]=e.worldPos[1],this.positions[3*t+2]=e.worldPos[2],this.positionsDirty=!0}removeMarker(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}update(){this.markerListDirty&&(this._buildMarkerList(),this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0),this.positionsDirty&&(this._buildPositions(),this.positionsDirty=!1,this.aabbDirty=!0,this.vbosDirty=!0),this.aabbDirty&&(this._buildAABB(),this.aabbDirty=!1),this.vbosDirty&&(this._buildVBOs(),this.vbosDirty=!1),this.occlusionTestListDirty&&this._buildOcclusionTestList(),this._updateActiveSectionPlanes()}_buildMarkerList(){for(var e in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(e)&&(this.markerList[this.numMarkers]=this.markers[e],this.markerIndices[e]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers}_buildPositions(){let e=0;for(let t=0;t-t){i._setVisible(!1);continue}const n=i.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>s||l-10>r?i._setVisible(!1):!i.entity||i.entity.visible?i.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=i,this.pixels[o++]=a,this.pixels[o++]=l):i._setVisible(!0):i._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let i=0;i{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i||(i=new je(this._scene,e.origin),this._occlusionLayers[i.originHash]=i,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return;const i=e.origin.join();if(i!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let s=this._occlusionLayers[i];s||(s=new je(this._scene,e.origin),this._occlusionLayers[i]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.originHash],this._occlusionLayersListDirty=!0):i.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e0,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):e.markerZOffset<0&&i.push("clipPos.z += "+e.markerZOffset+";"),i.push(" gl_Position = clipPos;"),i.push("}"),i}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// OcclusionTester fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Ve(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e0){const e=s.sectionPlanes;for(let s=0;s{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=c.mat4();return()=>(e&&c.inverseMat4(s.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,i=this._program,s=this._scene,r=s.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=s.camera.project._state,l=a.near,A=a.far,h=a.matrix,u=this._getInverseProjectMat(),d=Math.random(),p="perspective"===s.camera.projection;Ke[0]=o,Ke[1]=n,t.viewport(0,0,o,n),t.clearColor(0,0,0,1),t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.frontFace(t.CCW),t.clear(t.COLOR_BUFFER_BIT),i.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,A),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,h),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,u),t.uniform1i(this._uPerspective,p),t.uniform1f(this._uScale,r.scale*(A/5)),t.uniform1f(this._uIntensity,r.intensity),t.uniform1f(this._uBias,r.bias),t.uniform1f(this._uKernelRadius,r.kernelRadius),t.uniform1f(this._uMinResolution,r.minResolution),t.uniform2fv(this._uViewport,Ke),t.uniform1f(this._uRandomSeed,d);const f=e.getDepthTexture();i.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e)return;const i=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new Ve(i,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),o=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new He(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new He(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new He(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const Je=new Float32Array(tt(17,[0,1])),Ye=new Float32Array(tt(17,[1,0])),Ze=new Float32Array(function(e,t){const i=[];for(let s=0;s<=e;s++)i.push(et(s,t));return i}(17,4)),qe=new Float32Array(2);class $e{constructor(e){this._scene=e,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._uViewport=null,this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new Ve(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS 16\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new He(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new He(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new He(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,i){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=c.mat4();return()=>(e&&c.inverseMat4(o.camera.projMatrix,t),t)})());const s=this._scene.canvas.gl,r=this._program,o=this._scene,n=s.drawingBufferWidth,a=s.drawingBufferHeight,l=o.camera.project._state,A=l.near,h=l.far;s.viewport(0,0,n,a),s.clearColor(0,0,0,1),s.enable(s.DEPTH_TEST),s.disable(s.BLEND),s.frontFace(s.CCW),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),r.bind(),qe[0]=n,qe[1]=a,s.uniform2fv(this._uViewport,qe),s.uniform1f(this._uCameraNear,A),s.uniform1f(this._uCameraFar,h),s.uniform1f(this._uDepthCutoff,.01),0===i?s.uniform2fv(this._uSampleOffsets,Ye):s.uniform2fv(this._uSampleOffsets,Je),s.uniform1fv(this._uSampleWeights,Ze);const u=e.getDepthTexture(),d=t.getTexture();r.bindTexture(this._uDepthTexture,u,0),r.bindTexture(this._uOcclusionTexture,d,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),s.drawElements(s.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function et(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function tt(e,t){const i=[];for(let s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}class it{constructor(e,t,i){i=i||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=i.size,this._hasDepthTexture=!!i.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(...e){if(this._touch(...e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}createTexture(e,t,i=null){const s=this.gl,r=s.createTexture();return s.bindTexture(s.TEXTURE_2D,r),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),i?s.texStorage2D(s.TEXTURE_2D,1,i,e,t):s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null),r}_touch(...e){let t,i;const s=this.gl;if(this.size?(t=this.size[0],i=this.size[1]):(t=s.drawingBufferWidth,i=s.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===i)return;this.buffer.textures.forEach((e=>s.deleteTexture(e))),s.deleteFramebuffer(this.buffer.framebuf),s.deleteRenderbuffer(this.buffer.renderbuf)}const r=[];let o;e.length>0?r.push(...e.map((e=>this.createTexture(t,i,e)))):r.push(this.createTexture(t,i)),this._hasDepthTexture&&(o=s.createTexture(),s.bindTexture(s.TEXTURE_2D,o),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,s.DEPTH_COMPONENT32F,t,i,0,s.DEPTH_COMPONENT,s.FLOAT,null));const n=s.createRenderbuffer();s.bindRenderbuffer(s.RENDERBUFFER,n),s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT32F,t,i);const a=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,a);for(let e=0;e0&&s.drawBuffers(r.map(((e,t)=>s.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,o,0):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,n),s.bindTexture(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,a),!s.isFramebuffer(a))throw"Invalid framebuffer";s.bindFramebuffer(s.FRAMEBUFFER,null);const l=s.checkFramebufferStatus(s.FRAMEBUFFER);switch(l){case s.FRAMEBUFFER_COMPLETE:break;case s.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case s.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:a,renderbuf:n,texture:r[0],textures:r,depthTexture:o,width:t,height:i},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,i=null,s=null,r=Uint8Array,o=4,n=0){const a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,A=new r(o),h=this.gl;return h.readBuffer(h.COLOR_ATTACHMENT0+n),h.readPixels(a,l,1,1,i||h.RGBA,s||h.UNSIGNED_BYTE,A,0),A}readArray(e=null,t=null,i=Uint8Array,s=4,r=0){const o=new i(this.buffer.width*this.buffer.height*s),n=this.gl;return n.readBuffer(n.COLOR_ATTACHMENT0+r),n.readPixels(0,0,this.buffer.width,this.buffer.height,e||n.RGBA,t||n.UNSIGNED_BYTE,o,0),o}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),i=t.pixelData,s=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,A=4*n,h=new Uint8Array(4*n);for(let e=0;ee.deleteTexture(t))),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}class st{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let s=i[e];return s||(s=new it(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=s),s}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}function rt(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}const ot=function(t,i){i=i||{};const s=new De(t),r=t.canvas.canvas,o=t.canvas.gl,n=!!i.transparent,a=i.alphaDepthMask,l=new e({});let A={},h={},u=[],d=[],f=!0,g=!0,m=!0,_=!0,v=!0,b=!0,y=!0,x=!0;const B=new st(t);let w=!1;const P=new Xe(t),C=new $e(t);function M(){f&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableMap,s=t.drawableListPreCull;let r=0;for(let e in i)i.hasOwnProperty(e)&&(s[r++]=i[e]);s.length=r}}(),f=!1,g=!0),g&&(!function(){let e=0;for(let t in A)if(A.hasOwnProperty(t)){const i=A[t].drawableListPreCull;for(let t=0,s=i.length;te.renderOrder-t.renderOrder))}(),g=!1,m=!0),m&&function(){let e=0;for(let t=0,i=u.length;t0)for(s.withSAO=!0,S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||H>0||O>0||k>0){if(o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):(o.blendEquation(o.FUNC_ADD),o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA)),s.backfaces=!1,a||o.depthMask(!1),(O>0||k>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),k>0)for(S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||G>0){if(s.lastProgramId=null,t.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),G>0)for(S=0;S0)for(S=0;S0||W>0||j>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),o.enable(o.CULL_FACE),W>0)for(S=0;S0)for(S=0;S0||X>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),X>0)for(S=0;S0)for(S=0;S0||Y>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),Y>0)for(S=0;S0)for(S=0;S0){const t=Math.floor(e/4),i=_.size[0],s=t%i-Math.floor(i/2),r=Math.floor(t/i)-Math.floor(i/2),o=Math.sqrt(Math.pow(s,2)+Math.pow(r,2));U.push({x:s,y:r,dist:o,isVertex:p&&f?x[e+3]>y.length/2:p,result:[x[e+0],x[e+1],x[e+2],x[e+3]],normal:[w[e+0],w[e+1],w[e+2],w[e+3]],id:[P[e+0],P[e+1],P[e+2],P[e+3]]})}let O=null,k=null,N=null,Q=null;if(U.length>0){U.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),Q=U[0].isVertex?"vertex":"edge";const e=U[0].result,t=U[0].normal,i=U[0].id,s=y[e[3]],r=s.origin,o=s.coordinateScale;k=c.normalizeVec3([t[0]/c.MAX_INT,t[1]/c.MAX_INT,t[2]/c.MAX_INT]),O=[e[0]*o[0]+r[0],e[1]*o[1]+r[1],e[2]*o[2]+r[2]],N=l.items[i[0]+(i[1]<<8)+(i[2]<<16)+(i[3]<<24)]}if(null===C&&null==O)return null;let V=null;null!==O&&(V=t.camera.projectWorldPos(O));const H=N&&N.delegatePickedEntity?N.delegatePickedEntity():N;return!H&&E&&(E=E.delegatePickedEntity?E.delegatePickedEntity():E),r.reset(),r.snappedToEdge="edge"===Q,r.snappedToVertex="vertex"===Q,r.worldPos=O||C,r.worldNormal=k||M,r.entity=H||E,r.canvasPos=n||t.camera.projectWorldPos(C||O),r.snappedCanvasPos=V||n,r}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new We(t,B),this._occlusionTester.addMarker(e),t.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){M(),this._occlusionTester.bindRenderBuf(),s.reset(),s.backfaces=!0,s.frontface=!0,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e=0,t=d.length;e{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!0:e.keyCode===this.KEY_ALT?this.altDown=!0:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!0),this.keyDown[e.keyCode]=!0,this.fire("keydown",e.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!1:e.keyCode===this.KEY_ALT?this.altDown=!1:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!1),this.keyDown[e.keyCode]=!1,this.fire("keyup",e.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=e=>{this.enabled&&(this.mouseover=!0,this._getMouseCanvasPos(e),this.fire("mouseenter",this.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=e=>{this.enabled&&(this.mouseover=!1,this._getMouseCanvasPos(e),this.fire("mouseleave",this.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!0;break;case 2:this.mouseDownMiddle=!0;break;case 3:this.mouseDownRight=!0}this._getMouseCanvasPos(e),this.element.focus(),this.fire("mousedown",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownRight=!1}this.fire("mouseup",this.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("click",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("dblclick",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}});const e=this.scene.tickify((()=>this.fire("mousemove",this.mouseCanvasPos,!0)));this.element.addEventListener("mousemove",this._mouseMoveListener=t=>{this.enabled&&(this._getMouseCanvasPos(t),e(),this.mouseover&&t.preventDefault())}),this.element.addEventListener("contextmenu",this._contextmenuListener=e=>{this.enabled&&(this._getMouseCanvasPos(e),this.fire("contextmenu",this.mouseCanvasPos,!0))});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,i)=>{if(!this.enabled)return;const s=Math.max(-1,Math.min(1,40*-e.deltaY));t(s)},{passive:!0});{let e,t;const i=2;this.on("mousedown",(i=>{e=i[0],t=i[1]})),this.on("mouseup",(s=>{e>=s[0]-i&&e<=s[0]+i&&t>=s[1]-i&&t<=s[1]+i&&this.fire("mouseclicked",s,!0)}))}this.element.addEventListener("touchstart",this._touchstartListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchstart",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this.element.addEventListener("touchend",this._touchendListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchend",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this._eventsBound=!0}_unbindEvents(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("contextmenu",this._contextmenuListener),this.element.removeEventListener("wheel",this._mouseWheelListener),this.element.removeEventListener("touchstart",this._touchstartListener),this.element.removeEventListener("touchend",this._touchendListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getTouchCanvasPos(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;return[e.pageX-i,e.pageY-s]}_getMouseCanvasPos(e){if(e){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()}}const at=new e({});class lt{constructor(e){this.id=at.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){at.removeItem(this.id)}}class At extends D{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new lt({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 ht extends D{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new lt({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.canvas.boundary,t=e[2]/e[3],i=this._fovAxis;let s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),c.perspectiveMat4(s*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class ct extends D{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new lt({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,i=e.canvas.boundary,s=i[2],r=i[3],o=s/r;let n,a,l,A;s>r?(n=-t,a=t,l=t/o,A=-t/o):(n=-t*o,a=t*o,l=t,A=-t),c.orthoMat4c(n,a,A,l,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class ut extends D{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new lt({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.mat4(),near:.1,far:1e4}),this._left=-1,this._right=1,this._bottom=-1,this._top=1,this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.left=t.left,this.right=t.right,this.bottom=t.bottom,this.top=t.top,this.near=t.near,this.far=t.far}_update(){c.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set left(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}get left(){return this._left}set right(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}get right(){return this._right}set top(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}get top(){return this._top}set bottom(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}get bottom(){return this._bottom}set near(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}get near(){return this._state.near}set far(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class dt extends D{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new lt({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.mat4()}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!1,this.matrix=t.matrix}set matrix(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}get matrix(){return this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy()}}const pt=c.vec3(),ft=c.vec3(),gt=c.vec3(),mt=c.vec3(),_t=c.vec3(),vt=c.vec3(),bt=c.vec4(),yt=c.vec4(),xt=c.vec4(),Bt=c.mat4(),wt=c.mat4(),Pt=c.vec3(),Ct=c.vec3(),Mt=c.vec3(),Et=c.vec3();class Ft extends D{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new lt({deviceMatrix:c.mat4(),hasDeviceMatrix:!1,matrix:c.mat4(),normalMatrix:c.mat4(),inverseMatrix:c.mat4()}),this._perspective=new ht(this),this._ortho=new ct(this),this._frustum=new ut(this),this._customProjection=new dt(this),this._project=this._perspective,this._eye=c.vec3([0,0,10]),this._look=c.vec3([0,0,0]),this._up=c.vec3([0,1,0]),this._worldUp=c.vec3([0,1,0]),this._worldRight=c.vec3([1,0,0]),this._worldForward=c.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?(c.subVec3(this._eye,this._look,Pt),c.normalizeVec3(Pt,Ct),c.mulVec3Scalar(Ct,1e3,Mt),c.addVec3(this._look,Mt,Et),t=Et):t=this._eye,e.hasDeviceMatrix?(c.lookAtMat4v(t,this._look,this._up,wt),c.mulMat4(e.deviceMatrix,wt,e.matrix)):c.lookAtMat4v(t,this._look,this._up,e.matrix),c.inverseMat4(this._state.matrix,this._state.inverseMatrix),c.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}orbitYaw(e){let t=c.subVec3(this._eye,this._look,pt);c.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,Bt),t=c.transformPoint3(Bt,t,ft),this.eye=c.addVec3(this._look,t,gt),this.up=c.transformPoint3(Bt,this._up,mt)}orbitPitch(e){if(this._constrainPitch&&(e=c.dotVec3(this._up,this._worldUp)/c.DEGTORAD)<1)return;let t=c.subVec3(this._eye,this._look,pt);const i=c.cross3Vec3(c.normalizeVec3(t,ft),c.normalizeVec3(this._up,gt));c.rotationMat4v(.0174532925*e,i,Bt),t=c.transformPoint3(Bt,t,mt),this.up=c.transformPoint3(Bt,this._up,_t),this.eye=c.addVec3(t,this._look,vt)}yaw(e){let t=c.subVec3(this._look,this._eye,pt);c.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,Bt),t=c.transformPoint3(Bt,t,ft),this.look=c.addVec3(t,this._eye,gt),this._gimbalLock&&(this.up=c.transformPoint3(Bt,this._up,mt))}pitch(e){if(this._constrainPitch&&(e=c.dotVec3(this._up,this._worldUp)/c.DEGTORAD)<1)return;let t=c.subVec3(this._look,this._eye,pt);const i=c.cross3Vec3(c.normalizeVec3(t,ft),c.normalizeVec3(this._up,gt));c.rotationMat4v(.0174532925*e,i,Bt),this.up=c.transformPoint3(Bt,this._up,vt),t=c.transformPoint3(Bt,t,mt),this.look=c.addVec3(t,this._eye,_t)}pan(e){const t=c.subVec3(this._eye,this._look,pt),i=[0,0,0];let s;if(0!==e[0]){const r=c.cross3Vec3(c.normalizeVec3(t,[]),c.normalizeVec3(this._up,ft));s=c.mulVec3Scalar(r,e[0]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]}0!==e[1]&&(s=c.mulVec3Scalar(c.normalizeVec3(this._up,gt),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=c.mulVec3Scalar(c.normalizeVec3(t,mt),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=c.addVec3(this._eye,i,_t),this.look=c.addVec3(this._look,i,vt)}zoom(e){const t=c.subVec3(this._eye,this._look,pt),i=Math.abs(c.lenVec3(t,ft)),s=Math.abs(i+e);if(s<.5)return;const r=c.normalizeVec3(t,gt);this.eye=c.addVec3(this._look,c.mulVec3Scalar(r,s),mt)}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=c.vec3(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}get worldAxis(){return this._worldAxis}get worldUp(){return this._worldUp}get xUp(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}get yUp(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}get zUp(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}get worldRight(){return this._worldRight}get worldForward(){return this._worldForward}set gimbalLock(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}get gimbalLock(){return this._gimbalLock}set constrainPitch(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}get eyeLookDist(){return c.lenVec3(c.subVec3(this._look,this._eye,pt))}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get viewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get normalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get viewNormalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get inverseViewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}get projMatrix(){return this[this.projection].matrix}get perspective(){return this._perspective}get ortho(){return this._ortho}get frustum(){return this._frustum}get customProjection(){return this._customProjection}set projection(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}get projection(){return this._projectionType}get project(){return this._project}projectWorldPos(e){const t=bt,i=yt,s=xt;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,c.mulMat4v4(this.viewMatrix,t,i),c.mulMat4v4(this.projMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[s[0]*o+o,s[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}class It extends D{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class Dt extends It{get type(){return"DirLight"}constructor(e,t={}){super(e,t),this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const i=this.scene.camera,s=this.scene.canvas;this._onCameraViewMatrix=i.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=i.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=s.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new lt({type:"dir",dir:c.vec3([1,1,1]),color:c.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=c.identityMat4());const e=this.scene.camera,t=this._state.dir,i=e.look,s=[i[0]-t[0],i[1]-t[1],i[2]-t[2]],r=[0,1,0];c.lookAtMat4v(s,i,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=c.identityMat4()),c.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new it(this.scene.canvas.canvas,this.scene.canvas.gl,{size:[1024,1024]})),this._shadowRenderBuf)}),this.dir=t.dir,this.color=t.color,this.intensity=t.intensity,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set dir(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get dir(){return this._state.dir}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}class St extends It{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:c.vec3([.7,.7,.7]),intensity:1},this.color=t.color,this.intensity=t.intensity,this.scene._lightCreated(this)}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}get intensity(){return this._state.intensity}destroy(){super.destroy(),this.scene._lightDestroyed(this)}}class Tt extends D{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),p.memory.meshes++}destroy(){super.destroy(),p.memory.meshes--}}var Rt=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=c.vec3(),h=c.vec3(),u=c.vec3(),d=c.vec3(),p=c.vec3(),f=c.vec3(),g=c.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;ux)||(T=i[F.index1],R=i[F.index2],(!L&&T>65535||R>65535)&&(L=!0),y.push(T),y.push(R));return L?new Uint32Array(y):new Uint16Array(y)}}();const Lt=function(){const e=c.mat4(),t=c.mat4();return function(i,s){s=s||c.mat4();const r=i[0],o=i[1],n=i[2],a=i[3]-r,l=i[4]-o,A=i[5]-n,h=65535;return c.identityMat4(e),c.translationMat4v(i,e),c.identityMat4(t),c.scalingMat4v([a/h,l/h,A/h],t),c.mulMat4(e,t,s),s}}();var Ut=function(){const e=c.mat4(),t=c.mat4();return function(i,s,r){const o=new Uint16Array(i.length),n=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);let a;for(a=0;a=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 Nt(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 Qt(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}const Vt={getPositionsBounds:function(e){const t=new Float32Array(3),i=new Float32Array(3);let s,r;for(s=0;s<3;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;sn&&(r=i,n=o),i=kt(e,a,"floor","ceil"),s=Nt(i),o=Qt(e,a,s),o>n&&(r=i,n=o),i=kt(e,a,"ceil","ceil"),s=Nt(i),o=Qt(e,a,s),o>n&&(r=i,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t},decompressNormal:function(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t}},Ht=p.memory,jt=c.AABB3();class Gt extends Tt{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new lt({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=Vt.getPositionsBounds(t.positions),s=Vt.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=Vt.getUVBounds(t.uv),s=Vt.compressUVs(t.uv,e.min,e.max);i.uv=s.quantized,i.uvDecodeMatrix=s.decodeMatrix}else i.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?i.normals=Vt.compressNormals(t.normals):i.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(i.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)),this._buildHash(),Ht.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new He(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),Ht.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new He(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),Ht.positions+=e.positionsBuf.numItems),e.normals){let i=e.compressGeometry;e.normalsBuf=new He(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),Ht.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new He(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),Ht.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new He(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),Ht.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=Rt(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new He(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),Ht.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=c.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new He(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new He(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),Ht.positions+=this._pickTrianglePositionsBuf.numItems,Ht.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),Vt.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=Vt.getPositionsBounds(e),s=Vt.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),Vt.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),Vt.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=c.AABB3()),c.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=c.OBB3()),c.positions3ToAABB3(this._state.positions,jt,this._state.positionsDecodeMatrix),c.AABB3ToOBB3(jt,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(),Ht.meshes--}}function zt(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return _.apply(e,{positions:[c,u,d,l,u,d,l,A,d,c,A,d,c,u,d,c,A,d,c,A,h,c,u,h,c,u,d,c,u,h,l,u,h,l,u,d,l,u,d,l,u,h,l,A,h,l,A,d,l,A,h,c,A,h,c,A,d,l,A,d,c,A,h,l,A,h,l,u,h,c,u,h],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 Wt extends D{get type(){return"Material"}constructor(e,t={}){super(e,t),p.memory.materials++}destroy(){super.destroy(),p.memory.materials--}}const Kt={opaque:0,mask:1,blend:2},Xt=["opaque","mask","blend"];class Jt extends Wt{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new lt({type:"PhongMaterial",ambient:c.vec3([1,1,1]),diffuse:c.vec3([1,1,1]),specular:c.vec3([1,1,1]),emissive:c.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.ambient=t.ambient,this.diffuse=t.diffuse,this.specular=t.specular,this.emissive=t.emissive,this.alpha=t.alpha,this.shininess=t.shininess,this.reflectivity=t.reflectivity,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,t.ambientMap&&(this._ambientMap=this._checkComponent("Texture",t.ambientMap)),t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.reflectivityMap&&(this._reflectivityMap=this._checkComponent("Texture",t.reflectivityMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.diffuseFresnel&&(this._diffuseFresnel=this._checkComponent("Fresnel",t.diffuseFresnel)),t.specularFresnel&&(this._specularFresnel=this._checkComponent("Fresnel",t.specularFresnel)),t.emissiveFresnel&&(this._emissiveFresnel=this._checkComponent("Fresnel",t.emissiveFresnel)),t.alphaFresnel&&(this._alphaFresnel=this._checkComponent("Fresnel",t.alphaFresnel)),t.reflectivityFresnel&&(this._reflectivityFresnel=this._checkComponent("Fresnel",t.reflectivityFresnel)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this._makeHash()}_makeHash(){const e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}set shininess(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}get shininess(){return this._state.shininess}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set reflectivity(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}get reflectivity(){return this._state.reflectivity}get normalMap(){return this._normalMap}get ambientMap(){return this._ambientMap}get diffuseMap(){return this._diffuseMap}get specularMap(){return this._specularMap}get emissiveMap(){return this._emissiveMap}get alphaMap(){return this._alphaMap}get reflectivityMap(){return this._reflectivityMap}get occlusionMap(){return this._occlusionMap}get diffuseFresnel(){return this._diffuseFresnel}get specularFresnel(){return this._specularFresnel}get emissiveFresnel(){return this._emissiveFresnel}get alphaFresnel(){return this._alphaFresnel}get reflectivityFresnel(){return this._reflectivityFresnel}set alphaMode(e){let t=Kt[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" - defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return Xt[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}destroy(){super.destroy(),this._state.destroy()}}const Yt={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}};class Zt extends Wt{get type(){return"EmphasisMaterial"}get presets(){return Yt}constructor(e,t={}){super(e,t),this._state=new lt({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),this._preset="default",t.preset?(this.preset=t.preset,void 0!==t.fill&&(this.fill=t.fill),t.fillColor&&(this.fillColor=t.fillColor),void 0!==t.fillAlpha&&(this.fillAlpha=t.fillAlpha),void 0!==t.edges&&(this.edges=t.edges),t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth),void 0!==t.backfaces&&(this.backfaces=t.backfaces),void 0!==t.glowThrough&&(this.glowThrough=t.glowThrough)):(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.backfaces=t.backfaces,this.glowThrough=t.glowThrough)}set fill(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}get fill(){return this._state.fill}set fillColor(e){let t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}get fillColor(){return this._state.fillColor}set fillAlpha(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}get fillAlpha(){return this._state.fillAlpha}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set glowThrough(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}get glowThrough(){return this._state.glowThrough}set preset(e){if(e=e||"default",this._preset===e)return;const t=Yt[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Yt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const qt={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 $t extends Wt{get type(){return"EdgeMaterial"}get presets(){return qt}constructor(e,t={}){super(e,t),this._state=new lt({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),this._preset="default",t.preset?(this.preset=t.preset,t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth)):(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth),this.edges=!1!==t.edges}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=qt[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(qt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const ei={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 ti extends D{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=c.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return ei}set units(e){e||(e="meters");ei[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=c.vec3(3)){t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}realToWorldPos(e,t=c.vec3(3)){return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}class ii extends D{constructor(e,t={}){super(e,t),this._supported=Se.SUPPORTED_EXTENSIONS.OES_standard_derivatives,this.enabled=t.enabled,this.kernelRadius=t.kernelRadius,this.intensity=t.intensity,this.bias=t.bias,this.scale=t.scale,this.minResolution=t.minResolution,this.numSamples=t.numSamples,this.blur=t.blur,this.blendCutoff=t.blendCutoff,this.blendFactor=t.blendFactor}get supported(){return this._supported}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}get enabled(){return this._enabled}get possible(){if(!this._supported)return!1;if(!this._enabled)return!1;const e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}get active(){return this._active}set kernelRadius(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}get kernelRadius(){return this._kernelRadius}set intensity(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}get intensity(){return this._intensity}set bias(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}get bias(){return this._bias}set scale(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}get scale(){return this._scale}set minResolution(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}get minResolution(){return this._minResolution}set numSamples(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}get numSamples(){return this._numSamples}set blur(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}get blur(){return this._blur}set blendCutoff(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}get blendCutoff(){return this._blendCutoff}set blendFactor(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}get blendFactor(){return this._blendFactor}destroy(){super.destroy()}}class si extends D{constructor(e,t={}){super(e,t),this.sliceColor=t.sliceColor,this.sliceThickness=t.sliceThickness}set sliceThickness(e){null==e&&(e=0),this._sliceThickness!==e&&(this._sliceThickness=e,this.glRedraw())}get sliceThickness(){return this._sliceThickness}set sliceColor(e){null==e&&(e=[0,0,0,1]),this._sliceColor!==e&&(this._sliceColor=e,this.glRedraw())}get sliceColor(){return this._sliceColor}destroy(){super.destroy()}}const ri={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class oi extends Wt{get type(){return"PointsMaterial"}get presets(){return ri}constructor(e,t={}){super(e,t),this._state=new lt({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),t.preset?(this.preset=t.preset,void 0!==t.pointSize&&(this.pointSize=t.pointSize),void 0!==t.roundPoints&&(this.roundPoints=t.roundPoints),void 0!==t.perspectivePoints&&(this.perspectivePoints=t.perspectivePoints),void 0!==t.minPerspectivePointSize&&(this.minPerspectivePointSize=t.minPerspectivePointSize),void 0!==t.maxPerspectivePointSize&&(this.maxPerspectivePointSize=t.minPerspectivePointSize)):(this._preset="default",this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize),this.filterIntensity=t.filterIntensity,this.minIntensity=t.minIntensity,this.maxIntensity=t.maxIntensity}set pointSize(e){this._state.pointSize=e||2,this.glRedraw()}get pointSize(){return this._state.pointSize}set roundPoints(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}get roundPoints(){return this._state.roundPoints}set perspectivePoints(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}get perspectivePoints(){return this._state.perspectivePoints}set minPerspectivePointSize(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}get minPerspectivePointSize(){return this._state.minPerspectivePointSize}set maxPerspectivePointSize(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}get maxPerspectivePointSize(){return this._state.maxPerspectivePointSize}set filterIntensity(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}get filterIntensity(){return this._state.filterIntensity}set minIntensity(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}get minIntensity(){return this._state.minIntensity}set maxIntensity(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}get maxIntensity(){return this._state.maxIntensity}set preset(e){if(e=e||"default",this._preset===e)return;const t=ri[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(ri).join(", "))}get preset(){return this._preset}get hash(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}destroy(){super.destroy(),this._state.destroy()}}const ni={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class ai extends Wt{get type(){return"LinesMaterial"}get presets(){return ni}constructor(e,t={}){super(e,t),this._state=new lt({type:"LinesMaterial",lineWidth:null}),t.preset?(this.preset=t.preset,void 0!==t.lineWidth&&(this.lineWidth=t.lineWidth)):(this._preset="default",this.lineWidth=t.lineWidth)}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=ni[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(ni).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function li(e,t){const i={};let s,r;for(let o=0,n=t.length;o{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new ot(this,{transparent:s,alphaDepthMask:r}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;let e=null;this.getHash=function(){if(e)return e;const t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";const i=[];for(let e=0,s=t;ethis._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},this._sectionPlanesState.setNumCachedSectionPlanes(t.numCachedSectionPlanes||0),this._lightsState=new function(){const e=c.vec4([0,0,0,0]),t=c.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let i=null,s=null;this.getHash=function(){if(i)return i;const e=[],t=this.lights;let s;for(let i=0,r=t.length;i0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),i=e.join(""),i},this.addLight=function(e){this.lights.push(e),s=null,i=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t{this._renderer.imageDirty()}))}_initDefaults(){}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+_.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=c.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],_.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}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_deRegisterVisibleObject(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_deRegisterXRayedObject(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}_objectHighlightedUpdated(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}_deRegisterHighlightedObject(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_deRegisterSelectedObject(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_deRegisterColorizedObject(e){delete this.colorizedObjects[e.id],this._numColorizedObjects--,this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_deRegisterOpacityObject(e){delete this.opacityObjects[e.id],this._numOpacityObjects--,this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_deRegisterOffsetObject(e){delete this.offsetObjects[e.id],this._numOffsetObjects--,this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get readableGeometryEnabled(){return this._readableGeometry}get pickSurfacePrecisionEnabled(){return this._readableGeometry}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set numCachedSectionPlanes(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}get numCachedSectionPlanes(){return this._sectionPlanesState.getNumCachedSectionPlanes()}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}get markerZOffset(){return null==this._markerZOffset?-.001:this._markerZOffset}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&M.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const i=this._passes,s=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),A=!0}A||(t=-100,i=-100,s=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=n,this._aabbDirty=!1,this._center=null}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const i=e.includeEntities||e.include;i&&(e.includeEntityIds=li(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=li(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){if(void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),e.canvasPos)return this._renderer.snapPick(e);this.error("Scene.snapPick() canvasPos parameter expected")}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,i=e.length;t{if(e.collidable){const l=e.aabb;l[0]o&&(o=l[3]),l[4]>n&&(n=l[4]),l[5]>a&&(a=l[5]),t=!0}})),t){const e=c.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=o,e[4]=n,e[5]=a,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const i=e.visible!==t;return e.visible=t,i}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const i=e.collidable!==t;return e.collidable=t,i}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const i=e.culled!==t;return e.culled=t,i}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const i=e.selected!==t;return e.selected=t,i}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const i=e.highlighted!==t;return e.highlighted=t,i}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const i=e.xrayed!==t;return e.xrayed=t,i}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const i=e.edges!==t;return e.edges=t,i}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const i=e.opacity!==t;return e.opacity=t,i}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const i=e.pickable!==t;return e.pickable=t,i}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){_.isString(e)&&(e=[e]);let i=!1;for(let s=0,r=e.length;s{r>s&&(s=r,e(...i))}));return this._tickifiedFunctions[t]={tickSubId:n,wrapperFunc:o},o}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const hi=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene._lightsState,r=e._geometry._state,o=e._state.billboard,n=e._state.stationary,a=i.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,A=[];A.push("#version 300 es"),A.push("// Lambertian drawing vertex shader"),A.push("in vec3 position;"),A.push("uniform mat4 modelMatrix;"),A.push("uniform mat4 viewMatrix;"),A.push("uniform mat4 projMatrix;"),A.push("uniform vec4 colorize;"),A.push("uniform vec3 offset;"),l&&A.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(A.push("uniform float logDepthBufFC;"),A.push("out float vFragDepth;"),A.push("bool isPerspectiveMatrix(mat4 m) {"),A.push(" return (m[2][3] == - 1.0);"),A.push("}"),A.push("out float isPerspective;"));a&&A.push("out vec4 vWorldPosition;");if(A.push("uniform vec4 lightAmbient;"),A.push("uniform vec4 materialColor;"),A.push("uniform vec3 materialEmissive;"),r.normalsBuf){A.push("in vec3 normal;"),A.push("uniform mat4 modelNormalMatrix;"),A.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),A.push(" }"),A.push(" return normalize(v);"),A.push("}"))}A.push("out vec4 vColor;"),"points"===r.primitiveName&&A.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(A.push("void billboard(inout mat4 mat) {"),A.push(" mat[0][0] = 1.0;"),A.push(" mat[0][1] = 0.0;"),A.push(" mat[0][2] = 0.0;"),"spherical"===o&&(A.push(" mat[1][0] = 0.0;"),A.push(" mat[1][1] = 1.0;"),A.push(" mat[1][2] = 0.0;")),A.push(" mat[2][0] = 0.0;"),A.push(" mat[2][1] = 0.0;"),A.push(" mat[2][2] =1.0;"),A.push("}"));A.push("void main(void) {"),A.push("vec4 localPosition = vec4(position, 1.0); "),A.push("vec4 worldPosition;"),l&&A.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?A.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):A.push("vec4 localNormal = vec4(normal, 0.0); "),A.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),A.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));A.push("mat4 viewMatrix2 = viewMatrix;"),A.push("mat4 modelMatrix2 = modelMatrix;"),n&&A.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(A.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),A.push("billboard(modelMatrix2);"),A.push("billboard(viewMatrix2);"),A.push("billboard(modelViewMatrix);"),r.normalsBuf&&(A.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),A.push("billboard(modelNormalMatrix2);"),A.push("billboard(viewNormalMatrix2);"),A.push("billboard(modelViewNormalMatrix);")),A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&A.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(A.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),A.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),A.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=s.lights.length;e0,o=t.gammaOutput,n=[];n.push("#version 300 es"),n.push("// Lambertian drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));if(r){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}"points"===s.primitiveName&&(n.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push("float r = dot(cxy, cxy);"),n.push("if (r > 1.0) {"),n.push(" discard;"),n.push("}"));t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");o?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(e)):(this.vertex=function(e){const t=e.scene;e._material;const i=e._state,s=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=i.billboard,l=i.background,A=i.stationary,h=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),c=di(e),u=s.getNumAllocatedSectionPlanes()>0,d=ui(e),p=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),p&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),u&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));o.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(c){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(let e=0,t=o.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}h&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),p&&f.push("uniform mat3 uvDecodeMatrix;"));r.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===r.primitiveName&&f.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = 1.0;"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===a&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = 1.0;"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(d){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(let e=0,t=o.lights.length;e0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(let e=0,t=o.lights.length;e0,l=di(e),A=s.uvBuf,h="PhongMaterial"===n.type,c="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,d=ui(e);t.gammaInput;const p=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));d&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),p&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var g=0;g0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),o.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),h&&((o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = "+ci[o.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(c||u)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),o.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+ci[o.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),s.colors&&f.push("in vec4 vColor;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._occlusionMap||i._alphaMap)&&f.push("in vec2 vUV;");l&&(o.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));n.ambient&&f.push("uniform vec3 materialAmbient;");n.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==n.alpha&&null!==n.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");n.emissive&&f.push("uniform vec3 materialEmissive;");n.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==n.glossiness&&null!==n.glossiness&&f.push("uniform float materialGlossiness;");void 0!==n.shininess&&null!==n.shininess&&f.push("uniform float materialShininess;");n.specular&&f.push("uniform vec3 materialSpecular;");void 0!==n.metallic&&null!==n.metallic&&f.push("uniform float materialMetallic;");void 0!==n.roughness&&null!==n.roughness&&f.push("uniform float materialRoughness;");void 0!==n.specularF0&&null!==n.specularF0&&f.push("uniform float materialSpecularF0;");A&&i._ambientMap&&(f.push("uniform sampler2D ambientMap;"),i._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));A&&i._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),i._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));A&&i._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),i._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));A&&i._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),i._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&A&&i._metallicMap&&(f.push("uniform sampler2D metallicMap;"),i._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&A&&i._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),i._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&A&&i._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),i._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&i._normalMap&&(f.push("uniform sampler2D normalMap;"),i._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));A&&i._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),i._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));A&&i._alphaMap&&(f.push("uniform sampler2D alphaMap;"),i._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&A&&i._specularMap&&(f.push("uniform sampler2D specularMap;"),i._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&A&&i._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),i._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&A&&i._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),i._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(i._diffuseFresnel||i._specularFresnel||i._alphaFresnel||i._emissiveFresnel||i._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),i._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),i._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),i._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),i._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),i._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(let e=0,t=o.lights.length;e 0.0) { discard; }"),f.push("}")}"points"===s.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),n.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");n.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):n.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");s.colors&&f.push("diffuseColor *= vColor.rgb;");n.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");n.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==n.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");s.colors&&f.push("alpha *= vColor.a;");void 0!==n.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==n.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==n.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==n.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._occlusionMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));A&&i._ambientMap&&(i._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+ci[i._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));A&&i._diffuseMap&&(i._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+ci[i._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));A&&i._baseColorMap&&(i._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+ci[i._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));A&&i._emissiveMap&&(i._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+ci[i._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));A&&i._alphaMap&&(i._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));A&&i._occlusionMap&&(i._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(o.lights.length>0||o.lightMaps.length>0||o.reflectionMaps.length>0)){A&&i._normalMap?(i._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),A&&i._specularMap&&(i._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),A&&i._glossinessMap&&(i._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),A&&i._specularGlossinessMap&&(i._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),A&&i._metallicMap&&(i._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),A&&i._roughnessMap&&(i._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),A&&i._metallicRoughnessMap&&(i._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),i._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),i._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),i._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),i._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),h&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),u&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),c&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),o.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),h&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(u||c)&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(let e=0,t=o.lights.length;e0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(h=0,c=o.sectionPlanes.length;h0&&r.lightMaps[0].texture&&this._uLightMap&&(a.bindTexture(this._uLightMap,r.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),r.reflectionMaps.length>0&&r.reflectionMaps[0].texture&&this._uReflectionMap&&(a.bindTexture(this._uReflectionMap,r.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor),this._baseTextureUnit=e.textureUnit};class _i{constructor(e){this.vertex=function(e){const t=e.scene,i=t._lightsState,s=function(e){const t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),r=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,o=!!e._geometry._state.compressGeometry,n=e._state.billboard,a=e._state.stationary,l=[];l.push("#version 300 es"),l.push("// EmphasisFillShaderSource vertex shader"),l.push("in vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),l.push("uniform vec3 offset;"),o&&l.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;"));r&&l.push("out vec4 vWorldPosition;");if(l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),s){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"))}l.push("out vec4 vColor;"),("spherical"===n||"cylindrical"===n)&&(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = 1.0;"),l.push(" mat[0][1] = 0.0;"),l.push(" mat[0][2] = 0.0;"),"spherical"===n&&(l.push(" mat[1][0] = 0.0;"),l.push(" mat[1][1] = 1.0;"),l.push(" mat[1][2] = 0.0;")),l.push(" mat[2][0] = 0.0;"),l.push(" mat[2][1] = 0.0;"),l.push(" mat[2][2] =1.0;"),l.push("}"));l.push("void main(void) {"),l.push("vec4 localPosition = vec4(position, 1.0); "),l.push("vec4 worldPosition;"),o&&l.push("localPosition = positionsDecodeMatrix * localPosition;");s&&(o?l.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):l.push("vec4 localNormal = vec4(normal, 0.0); "),l.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),l.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));l.push("mat4 viewMatrix2 = viewMatrix;"),l.push("mat4 modelMatrix2 = modelMatrix;"),a&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===n||"cylindrical"===n?(l.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),l.push("billboard(modelMatrix2);"),l.push("billboard(viewMatrix2);"),l.push("billboard(modelViewMatrix);"),s&&(l.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),l.push("billboard(modelNormalMatrix2);"),l.push("billboard(viewNormalMatrix2);"),l.push("billboard(modelViewNormalMatrix);")),l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),s)for(let e=0,t=i.lights.length;e0,o=[];o.push("#version 300 es"),o.push("// Lambertian drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}"points"===e._geometry._state.primitiveName&&(o.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("float r = dot(cxy, cxy);"),o.push("if (r > 1.0) {"),o.push(" discard;"),o.push("}"));t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const vi=new e({}),bi=c.vec3(),yi=function(e,t){this.id=vi.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new _i(t),this._allocate(t)},xi={};yi.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=xi[t];return i||(i=new yi(t,e),xi[t]=i,p.memory.programs++),i._useCount++,i},yi.prototype.put=function(){0==--this._useCount&&(vi.removeItem(this.id),this._program&&this._program.destroy(),delete xi[this._hash],p.memory.programs--)},yi.prototype.webglContextRestored=function(){this._program=null},yi.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl,n=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,A=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,A?e.getRTCViewMatrix(a.originHash,A):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Edges drawing vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec4 edgeColor;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));i&&n.push("out vec4 vWorldPosition;");n.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n.push("vColor = edgeColor;"),i&&n.push("vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.getNumAllocatedSectionPlanes()>0,o=[];o.push("#version 300 es"),o.push("// Edges drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const wi=new e({}),Pi=c.vec3(),Ci=function(e,t){this.id=wi.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Bi(t),this._allocate(t)},Mi={};Ci.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=Mi[t];return i||(i=new Ci(t,e),Mi[t]=i,p.memory.programs++),i._useCount++,i},Ci.prototype.put=function(){0==--this._useCount&&(wi.removeItem(this.id),this._program&&this._program.destroy(),delete Mi[this._hash],p.memory.programs--)},Ci.prototype.webglContextRestored=function(){this._program=null},Ci.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl;let n;const a=t._state,l=t._geometry,A=l._state,h=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(a.originHash,h):r.viewMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh picking vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("out vec4 vViewPosition;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("uniform vec2 pickClipPos;"),n.push("vec4 remapClipPos(vec4 clipPos) {"),n.push(" clipPos.xy /= clipPos.w;"),n.push(" clipPos.xy -= pickClipPos;"),n.push(" clipPos.xy *= clipPos.w;"),n.push(" return clipPos;"),n.push("}"),n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==r&&"cylindrical"!==r||(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"));n.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = remapClipPos(clipPos);"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(r.push("uniform vec4 pickColor;"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = pickColor; "),r.push("}"),r}(e)}}const Fi=c.vec3(),Ii=function(e,t){this._hash=e,this._shaderSource=new Ei(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Di={};Ii.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=Di[t];if(!i){if(i=new Ii(t,e),i.errors)return console.log(i.errors.join("\n")),null;Di[t]=i,p.memory.programs++}return i._useCount++,i},Ii.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Di[this._hash],p.memory.programs--)},Ii.prototype.webglContextRestored=function(){this._program=null},Ii.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t>24&255,h=l>>16&255,c=l>>8&255,u=255&l;s.uniform4f(this._uPickColor,u/255,c/255,h/255,A/255),s.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(s.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&s.drawArrays(s.TRIANGLES,0,n.positions.numItems)},Ii.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Ve(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0,s=!!e._geometry._state.compressGeometry,r=[];r.push("#version 300 es"),r.push("// Surface picking vertex shader"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),i&&(r.push("uniform bool clippable;"),r.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));r.push("uniform vec2 pickClipPos;"),r.push("vec4 remapClipPos(vec4 clipPos) {"),r.push(" clipPos.xy /= clipPos.w;"),r.push(" clipPos.xy -= pickClipPos;"),r.push(" clipPos.xy *= clipPos.w;"),r.push(" return clipPos;"),r.push("}"),r.push("out vec4 vColor;"),s&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),s&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),i&&r.push(" vWorldPosition = worldPosition;");r.push(" vColor = color;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = remapClipPos(clipPos);"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Surface picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),r.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = vColor;"),r.push("}"),r}(e)}}const Ti=c.vec3(),Ri=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Si(t),this._allocate(t)},Li={};Ri.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=Li[t];if(!i){if(i=new Ri(t,e),i.errors)return console.log(i.errors.join("\n")),null;Li[t]=i,p.memory.programs++}return i._useCount++,i},Ri.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Li[this._hash],p.memory.programs--)},Ri.prototype.webglContextRestored=function(){this._program=null},Ri.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,A=o.backfaces,h=o.frontface,c=i.camera.project,u=n._getPickTrianglePositions(),d=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,i.logarithmicDepthBufferEnabled){const e=2/(Math.log(c.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}if(s.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh occlusion vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push("}"),r}(e)}}const Oi=c.vec3(),ki=function(e,t){this._hash=e,this._shaderSource=new Ui(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ni={};ki.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let i=Ni[t];if(!i){if(i=new ki(t,e),i.errors)return console.log(i.errors.join("\n")),null;Ni[t]=i,p.memory.programs++}return i._useCount++,i},ki.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ni[this._hash],p.memory.programs--)},ki.prototype.webglContextRestored=function(){this._program=null},ki.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._material._state,o=t._state,n=t._geometry._state,a=t.origin;if(r.alpha<1)return;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){const t=r.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=r.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),this._lastMaterialId=r.id}const l=i.camera;if(s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!e._geometry._state.compressGeometry,s=[];s.push("// Mesh shadow vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),s.push("uniform vec3 offset;"),i&&s.push("uniform mat4 positionsDecodeMatrix;");t&&s.push("out vec4 vWorldPosition;");s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),s.push("vec4 worldPosition;"),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;");s.push("worldPosition = modelMatrix * localPosition;"),s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&s.push("vWorldPosition = worldPosition;");return s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(e)}}const Vi=function(e,t){this._hash=e,this._shaderSource=new Qi(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Hi={};Vi.get=function(e){const t=e.scene,i=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=Hi[i];if(!s){if(s=new Vi(i,e),s.errors)return console.log(s.errors.join("\n")),null;Hi[i]=s,p.memory.programs++}return s._useCount++,s},Vi.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Hi[this._hash],p.memory.programs--)},Vi.prototype.webglContextRestored=function(){this._program=null},Vi.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene.canvas.gl,s=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.id!==this._lastMaterialId){const t=s.backfaces;e.backfaces!==t&&(t?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const r=s.frontface;e.frontface!==r&&(r?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=r),e.lineWidth!==s.lineWidth&&(i.lineWidth(s.lineWidth),e.lineWidth=s.lineWidth),this._uPointSize&&i.uniform1i(this._uPointSize,s.pointSize),this._lastMaterialId=s.id}if(i.uniformMatrix4fv(this._uModelMatrix,i.FALSE,t.worldMatrix),r.combineGeometry){const s=t.vertexBufs;s.id!==this._lastVertexBufsId&&(s.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(s.positionsBuf,s.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),this._lastVertexBufsId=s.id)}this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),i.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(i.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(i.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(i.drawArrays(i.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},Vi.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Ve(i,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a0)for(let i=0;i0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const ts=function(){const e=c.vec3(),t=c.vec3(),i=c.vec3(),s=c.vec3(),r=c.vec3(),o=c.vec3(),n=c.vec4(),a=c.vec3(),l=c.vec3(),A=c.vec3(),h=c.vec3(),u=c.vec3(),d=c.vec3(),p=c.vec3(),f=c.vec3(),g=c.vec3(),m=c.vec4(),_=c.vec4(),v=c.vec4(),b=c.vec3(),y=c.vec3(),x=c.vec3(),B=c.vec3(),w=c.vec3(),P=c.vec3(),C=c.vec3(),M=c.vec3(),E=c.vec3(),F=c.vec3(),I=c.vec3();return function(D,S,T,R,L){var U=L.primIndex;if(null!=U&&U>-1){const Q=D.geometry._state,V=D.scene,H=V.camera,j=V.canvas;if("triangles"===Q.primitiveName){L.primitive="triangle";const V=U,G=Q.indices,W=Q.positions;let K,X,J;if(G){var O=G[V+0],k=G[V+1],N=G[V+2];o[0]=O,o[1]=k,o[2]=N,L.indices=o,K=3*O,X=3*k,J=3*N}else K=3*V,X=K+3,J=X+3;if(i[0]=W[K+0],i[1]=W[K+1],i[2]=W[K+2],s[0]=W[X+0],s[1]=W[X+1],s[2]=W[X+2],r[0]=W[J+0],r[1]=W[J+1],r[2]=W[J+2],Q.compressGeometry){const e=Q.positionsDecodeMatrix;e&&(Vt.decompressPosition(i,e,i),Vt.decompressPosition(s,e,s),Vt.decompressPosition(r,e,r))}L.canvasPos?c.canvasPosToLocalRay(j.canvas,D.origin?z(S,D.origin):S,T,R,D.worldMatrix,L.canvasPos,e,t):L.origin&&L.direction&&c.worldRayToLocalRay(D.worldMatrix,L.origin,L.direction,e,t),c.normalizeVec3(t),c.rayPlaneIntersect(e,t,i,s,r,n),L.localPos=n,L.position=n,m[0]=n[0],m[1]=n[1],m[2]=n[2],m[3]=1,c.transformVec4(D.worldMatrix,m,_),a[0]=_[0],a[1]=_[1],a[2]=_[2],L.canvasPos&&D.origin&&(a[0]+=D.origin[0],a[1]+=D.origin[1],a[2]+=D.origin[2]),L.worldPos=a,c.transformVec4(H.matrix,_,v),l[0]=v[0],l[1]=v[1],l[2]=v[2],L.viewPos=l,c.cartesianToBarycentric(n,i,s,r,A),L.bary=A;const Y=Q.normals;if(Y){if(Q.compressGeometry){const e=3*O,t=3*k,i=3*N;Vt.decompressNormal(Y.subarray(e,e+2),h),Vt.decompressNormal(Y.subarray(t,t+2),u),Vt.decompressNormal(Y.subarray(i,i+2),d)}else h[0]=Y[K],h[1]=Y[K+1],h[2]=Y[K+2],u[0]=Y[X],u[1]=Y[X+1],u[2]=Y[X+2],d[0]=Y[J],d[1]=Y[J+1],d[2]=Y[J+2];const e=c.addVec3(c.addVec3(c.mulVec3Scalar(h,A[0],b),c.mulVec3Scalar(u,A[1],y),x),c.mulVec3Scalar(d,A[2],B),w);L.worldNormal=c.normalizeVec3(c.transformVec3(D.worldNormalMatrix,e,P))}const Z=Q.uv;if(Z){if(p[0]=Z[2*O],p[1]=Z[2*O+1],f[0]=Z[2*k],f[1]=Z[2*k+1],g[0]=Z[2*N],g[1]=Z[2*N+1],Q.compressGeometry){const e=Q.uvDecodeMatrix;e&&(Vt.decompressUV(p,e,p),Vt.decompressUV(f,e,f),Vt.decompressUV(g,e,g))}L.uv=c.addVec3(c.addVec3(c.mulVec2Scalar(p,A[0],C),c.mulVec2Scalar(f,A[1],M),E),c.mulVec2Scalar(g,A[2],F),I)}}}}}();function is(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);let s=e.height||1;s<0&&(console.error("negative height not allowed - will invert"),s*=-1);let r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<3&&(r=3);let o=e.heightSegments||1;o<0&&(console.error("negative heightSegments not allowed - will invert"),o*=-1),o<1&&(o=1);const n=!!e.openEnded;let a=e.center;const l=a?a[0]:0,A=a?a[1]:0,h=a?a[2]:0,c=s/2,u=s/o,d=2*Math.PI/r,p=1/r,f=(t-i)/o,g=[],m=[],v=[],b=[];let y,x,B,w,P,C,M,E,F,I,D;const S=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(y=0;y<=o;y++)for(P=t-y*f,C=c-y*u,x=0;x<=r;x++)B=Math.sin(x*d),w=Math.cos(x*d),m.push(P*B),m.push(S),m.push(P*w),v.push(x*p),v.push(1*y/o),g.push(P*B+l),g.push(C+A),g.push(P*w+h);for(y=0;y0){for(F=g.length/3,m.push(0),m.push(1),m.push(0),v.push(.5),v.push(.5),g.push(0+l),g.push(c+A),g.push(0+h),x=0;x<=r;x++)B=Math.sin(x*d),w=Math.cos(x*d),I=.5*Math.sin(x*d)+.5,D=.5*Math.cos(x*d)+.5,m.push(t*B),m.push(1),m.push(t*w),v.push(I),v.push(D),g.push(t*B+l),g.push(c+A),g.push(t*w+h);for(x=0;x0){for(F=g.length/3,m.push(0),m.push(-1),m.push(0),v.push(.5),v.push(.5),g.push(0+l),g.push(0-c+A),g.push(0+h),x=0;x<=r;x++)B=Math.sin(x*d),w=Math.cos(x*d),I=.5*Math.sin(x*d)+.5,D=.5*Math.cos(x*d)+.5,m.push(i*B),m.push(-1),m.push(i*w),v.push(I),v.push(D),g.push(i*B+l),g.push(0-c+A),g.push(i*w+h);for(x=0;x":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function os(e={}){var t=e.origin||[0,0,0],i=t[0],s=t[1],r=t[2],o=e.size||1,n=[],a=[],l=e.text;_.isNumeric(l)&&(l=""+l);for(var A,h,c,u,d,p,f,g,m,v=(l||"").split("\n"),b=0,y=0,x=.04,B=0;B0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let i=0,s=e.length;i1;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);const o=ws(i,this.wrapS);o&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,o);const n=ws(i,this.wrapT);if(n&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,n),this.type===i.TEXTURE_3D||this.type===i.TEXTURE_2D_ARRAY){const e=ws(i,this.wrapR);e&&i.texParameteri(this.target,i.TEXTURE_WRAP_R,e),i.texParameteri(this.type,i.TEXTURE_WRAP_R,e)}r?(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,Es(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,Es(i,this.magFilter))):(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,ws(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,ws(i,this.magFilter)));const a=ws(i,this.format,this.encoding),l=ws(i,this.type),A=Ms(i,this.internalFormat,a,l,this.encoding,!1);i.texStorage2D(i.TEXTURE_2D,s,A,e[0].width,e[0].height);for(let t=0,s=e.length;t>t;return e+1}class Ss extends D{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new lt({texture:new Cs({gl:this.scene.canvas.gl}),matrix:c.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=c.vec2([0,0]),this._scale=c.vec2([1,1]),this._rotate=c.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),p.memory.textures++}_checkMinFilter(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}_checkMagFilter(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}_checkWrapS(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkWrapT(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this._state.texture=new Cs({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,i;0===this._translate[0]&&0===this._translate[1]||(t=c.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(i=c.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?c.mulMat4(t,i):i),0!==this._rotate&&(i=c.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?c.mulMat4(t,i):i),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=Fs(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let i=new Image;i.onload=function(){i=Fs(i),t._state.texture.setImage(i,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),p.memory.textures--}}const Ts=p.memory,Rs=c.AABB3();class Ls extends Tt{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new lt({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._aabb=null,this._obb=c.OBB3();const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=Vt.getPositionsBounds(t.positions),o=Vt.compressPositions(t.positions,e.min,e.max);r=o.quantized,i.positionsDecodeMatrix=o.decodeMatrix,i.positionsBuf=new He(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),Ts.positions+=i.positionsBuf.numItems,c.positions3ToAABB3(t.positions,this._aabb),c.positions3ToAABB3(r,Rs,i.positionsDecodeMatrix),c.AABB3ToOBB3(Rs,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);i.colorsBuf=new He(s,s.ARRAY_BUFFER,e,e.length,4,s.STATIC_DRAW),Ts.colors+=i.colorsBuf.numItems}if(t.uv){const e=Vt.getUVBounds(t.uv),r=Vt.compressUVs(t.uv,e.min,e.max),o=r.quantized;i.uvDecodeMatrix=r.decodeMatrix,i.uvBuf=new He(s,s.ARRAY_BUFFER,o,o.length,2,s.STATIC_DRAW),Ts.uvs+=i.uvBuf.numItems}if(t.normals){const e=Vt.compressNormals(t.normals);let r=i.compressGeometry;i.normalsBuf=new He(s,s.ARRAY_BUFFER,e,e.length,3,s.STATIC_DRAW,r),Ts.normals+=i.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);i.indicesBuf=new He(s,s.ELEMENT_ARRAY_BUFFER,e,e.length,1,s.STATIC_DRAW),Ts.indices+=i.indicesBuf.numItems;const o=Rt(r,e,i.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new He(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),Ts.meshes++}else this.error("Config expected: indices");else this.error("Config expected: positions")}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positionsBuf&&t.push("p"),e.colorsBuf&&t.push("c"),(e.normalsBuf||e.autoVertexNormals)&&t.push("n"),e.uvBuf&&t.push("u"),t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf}get primitive(){return this._state.primitiveName}get aabb(){return this._aabb}get obb(){return this._obb}get numTriangles(){return this._numTriangles}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),e.destroy(),Ts.meshes--}}var Us={};function Os(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return _.apply(e,{primitive:"lines",positions:[l,A,h,l,A,d,l,u,h,l,u,d,c,A,h,c,A,d,c,u,h,c,u,d],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function ks(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let i=e.divisions||1;i<0&&(console.error("negative divisions not allowed - will invert"),i*=-1),i<1&&(i=1),t=t||10,i=i||10;const s=t/i,r=t/2,o=[],n=[];let a=0;for(let e=0,t=-r;e<=i;e++,t+=s)o.push(-r),o.push(0),o.push(t),o.push(r),o.push(0),o.push(t),o.push(t),o.push(0),o.push(-r),o.push(t),o.push(0),o.push(r),n.push(a++),n.push(a++),n.push(a++),n.push(a++);return _.apply(e,{primitive:"lines",positions:o,indices:n})}function Ns(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);let s=e.xSegments||1;s<0&&(console.error("negative xSegments not allowed - will invert"),s*=-1),s<1&&(s=1);let r=e.xSegments||1;r<0&&(console.error("negative zSegments not allowed - will invert"),r*=-1),r<1&&(r=1);const o=e.center,n=o?o[0]:0,a=o?o[1]:0,l=o?o[2]:0,A=t/2,h=i/2,c=Math.floor(s)||1,u=Math.floor(r)||1,d=c+1,p=u+1,f=t/c,g=i/u,m=new Float32Array(d*p*3),v=new Float32Array(d*p*3),b=new Float32Array(d*p*2);let y,x,B,w,P,C,M,E=0,F=0;for(y=0;y65535?Uint32Array:Uint16Array)(c*u*6);for(y=0;y360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const A=n?n[2]:0,h=[],u=[],d=[],p=[];let f,g,m,v,b,y,x,B,w,P,C,M;for(B=0;B<=r;B++)for(x=0;x<=s;x++)f=x/s*o,g=.785398+B/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),m=(t+i*Math.cos(g))*Math.cos(f),v=(t+i*Math.cos(g))*Math.sin(f),b=i*Math.sin(g),h.push(m+a),h.push(v+l),h.push(b+A),d.push(1-x/s),d.push(B/r),y=c.normalizeVec3(c.subVec3([m,v,b],[a,l,A],[]),[]),u.push(y[0]),u.push(y[1]),u.push(y[2]);for(B=1;B<=r;B++)for(x=1;x<=s;x++)w=(s+1)*B+x-1,P=(s+1)*(B-1)+x-1,C=(s+1)*(B-1)+x,M=(s+1)*B+x,p.push(w),p.push(P),p.push(C),p.push(C),p.push(M),p.push(w);return _.apply(e,{positions:h,normals:u,uv:d,indices:p})}function Vs(e={}){if(e.points.length%3!=0)throw"Size of points array for given polyline should be divisible by 3";let t=e.points.length/3;if(t<2)throw"There should be at least 2 points to create a polyline";let i=[];for(let e=0;e>8},Us.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},Us.parse={},Us.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",s=0;sr&&(r=l),Ao&&(o=A),hn&&(n=h)}return{min:{x:t,y:i,z:s},max:{x:r,y:o,z:n}}};class Hs extends D{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=c.vec3(t.pos||[0,0,0]),this._up=c.vec3(t.up||[0,1,0]),this._normal=c.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=c.vec3(),this._rtcPos=c.vec3(),this._imageSize=c.vec2(),this._texture=new Ss(this,{flipY:!0}),this._image=new Image,"jpg"!==this._type&&"png"!==this._type&&(this.error('Unsupported type - defaulting to "jpg"'),this._type="jpg"),this._node=new gs(this,{matrix:c.inverseMat4(c.lookAtMat4v(this._pos,c.subVec3(this._pos,this._normal,c.mat4()),this._up,c.mat4())),children:[this._bitmapMesh=new es(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new Gt(this,Ns({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Jt(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0})})]}),t.image?this.image=t.image:t.src?this.src=t.src:t.imageData&&(this.imageData=t.imageData),this.scene._bitmapCreated(this)}set visible(e){this._bitmapMesh.visible=e}get visible(){return this._bitmapMesh.visible}set image(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}get image(){return this._image}set src(e){if(e){this._image.onload=()=>{this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale()},this._image.src=e;switch(e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}}get src(){return this._image.src}set imageData(e){this._image.onload=()=>{this._texture.image=image,this._imageSize[0]=image.width,this._imageSize[1]=image.height,this._updateBitmapMeshScale()},this._image.src=e}get imageData(){const e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")}set type(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}get type(){return this._type}get pos(){return this._pos}get normal(){return this._normal}get up(){return this._up}set height(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}get height(){return this._height}set collidable(e){this._bitmapMesh.collidable=!1!==e}get collidable(){return this._bitmapMesh.collidable}set clippable(e){this._bitmapMesh.clippable=!1!==e}get clippable(){return this._bitmapMesh.clippable}set pickable(e){this._bitmapMesh.pickable=!1!==e}get pickable(){return this._bitmapMesh.pickable}set opacity(e){this._bitmapMesh.opacity=e}get opacity(){return this._bitmapMesh.opacity}destroy(){super.destroy(),this.scene._bitmapDestroyed(this)}_updateBitmapMeshScale(){const e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height/e,1,this._height]}}const js=(e,t)=>{const i=[];let s=[];function r(e,i){let s,r;for(let o=0;o<3;o++)if(s=t[3*e+o],r=t[3*i+o],s!==r)return r-s;return 0}let o=e.slice().sort(r),n=null;for(let e=0,t=o.length;eo&&r>n?o>n?(a=r,l=o,A=n):(a=r,l=n,A=o):o>r&&o>n?r>n?(a=o,l=r,A=n):(a=o,l=n,A=r):n>r&&n>o&&(r>o?(a=n,l=r,A=o):(a=n,l=o,A=r)),s[t+0]=[a,l],s[t+1]=[l,A],a>A){const e=A;A=a,a=e}s[t+2]=[A,a]}function a(e,t){let i,s;for(let r=0;r<2;r++)if(i=e[r],s=t[r],s!==i)return s-i;return 0}s=s.slice(0,e.length),s.sort(a);let l=0;for(let e=0;e0&&2!==l)},Gs=c.vec3(),zs=c.vec3(),Ws=c.vec3();class Ks{constructor(){this.vertices=[],this.indices=[],this.reset()}reset(){this.lenVertices=0,this.lenIndices=0,this.primitive=null}setPrimitive(e){this.primitive=e}addVertex(e){this.vertices[this.lenVertices++]=e[0],this.vertices[this.lenVertices++]=e[1],this.vertices[this.lenVertices++]=e[2]}addIndex(e){this.indices[this.lenIndices++]=e}get volume(){const e=this.vertices,t=this.indices;if("solid"!==this.primitive&&"surface"!==this.primitive&&"triangles"!==this.primitive)return-1;if("solid"!==this.primitive&&!js(t,e))return-1;let i=0;for(let s=0;s{Xs.addVertex(e)})),this.getEachIndex((e=>{Xs.addIndex(e)})),this._volume=Xs.volume;break;default:this._volume=0}return this._volume}get surfaceArea(){if(null!==this._surfaceArea)return this._surfaceArea;switch(this.layer.primitive){case"solid":case"surface":case"triangles":ir.reset(),this.getEachVertex((e=>{ir.addVertex(e)})),this.getEachIndex((e=>{ir.addIndex(e)})),this._surfaceArea=ir.surfaceArea;break;default:this._surfaceArea=0}return this._surfaceArea}set aabb(e){if(this._aabbLocal=e,this.origin){this._aabbLocal=e.slice(0);const t=this.origin;this._aabbLocal[0]+=t[0],this._aabbLocal[1]+=t[1],this._aabbLocal[2]+=t[2],this._aabbLocal[3]+=t[0],this._aabbLocal[4]+=t[1],this._aabbLocal[5]+=t[2]}}get aabb(){return this._aabbWorldDirty&&(c.AABB3ToOBB3(this._aabbLocal,sr),this.transform?(c.transformOBB3(this.transform.worldMatrix,sr,rr),c.transformOBB3(this.model.worldMatrix,rr,or),c.OBB3ToAABB3(or,this._aabbWorld)):(c.transformOBB3(this.model.worldMatrix,sr,rr),c.OBB3ToAABB3(rr,this._aabbWorld)),this._aabbWorldDirty=!1),this._aabbWorld}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const ar=new class{constructor(){this._uint8Arrays={},this._float32Arrays={}}_clear(){this._uint8Arrays={},this._float32Arrays={}}getUInt8Array(e){let t=this._uint8Arrays[e];return t||(t=new Uint8Array(e),this._uint8Arrays[e]=t),t}getFloat32Array(e){let t=this._float32Arrays[e];return t||(t=new Float32Array(e),this._float32Arrays[e]=t),t}};let lr=0;const Ar={NOT_RENDERED:0,COLOR_OPAQUE:1,COLOR_TRANSPARENT:2,SILHOUETTE_HIGHLIGHTED:3,SILHOUETTE_SELECTED:4,SILHOUETTE_XRAYED:5,EDGES_COLOR_OPAQUE:6,EDGES_COLOR_TRANSPARENT:7,EDGES_HIGHLIGHTED:8,EDGES_SELECTED:9,EDGES_XRAYED:10,PICK:11},hr=new Float32Array([1,1,1,1]),cr=new Float32Array([0,0,0,1]),ur=c.vec4(),dr=c.vec3(),pr=c.vec3(),fr=c.mat4();class gr{constructor(e,t=!1,{instancing:i=!1,edges:s=!1,useAlphaCutoff:r=!1}={}){this._scene=e,this._withSAO=t,this._instancing=i,this._edges=s,this._useAlphaCutoff=r,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}_getHash(){return this._scene._sectionPlanesState.getHash()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){return[""]}_buildFragmentShader(){return[""]}_addMatricesUniformBlockLines(e,t=!1){return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}_addRemapClipPosLines(e,t=1){return e.push("uniform vec2 drawingBufferSize;"),e.push("uniform vec2 pickClipPos;"),e.push("vec4 remapClipPos(vec4 clipPos) {"),e.push(" clipPos.xy /= clipPos.w;"),1===t?e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"):e.push(` clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(${t}));`),e.push(" clipPos.xy *= clipPos.w;"),e.push(" return clipPos;"),e.push("}"),e}getValid(){return this._hash===this._getHash()}setSectionPlanesStateUniforms(e){const t=this._scene,{gl:i}=t.canvas,{model:s,layerIndex:r}=e,o=t._sectionPlanesState.getNumAllocatedSectionPlanes(),n=t._sectionPlanesState.sectionPlanes.length;if(o>0){const a=t._sectionPlanesState.sectionPlanes,l=r*n,A=s.renderFlags;t.crossSections&&(i.uniform4fv(this._uSliceColor,t.crossSections.sliceColor),i.uniform1f(this._uSliceThickness,t.crossSections.sliceThickness));for(let t=0;t0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0&&p.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,p.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),p.lightMaps.length>0&&p.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,p.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const i=a.drawingBufferWidth,s=a.drawingBufferHeight;ur[0]=i,ur[1]=s,ur[2]=t.blendCutoff,ur[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,ur),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(this._useAlphaCutoff&&a.uniform1f(this._alphaCutoffLocation,h.alphaCutoff),s){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(i===Ar[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const i=n.xrayMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===Ar[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const i=n.highlightMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===Ar[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const i=n.selectedMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else a.uniform4fv(this._uColor,this._edges?cr:hr)}this._draw({state:l,frameCtx:e,incrementDrawState:r}),a.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,p.memory.programs--}}class mr extends gr{constructor(e,t,{edges:i=!1,useAlphaCutoff:s=!1}={}){super(e,t,{instancing:!1,edges:i,useAlphaCutoff:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;if(this._edges)t.drawElements(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0);else{const e=s.pickElementsCount||i.indicesBuf.numItems,o=s.pickElementsOffset?s.pickElementsOffset*i.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,i.indicesBuf.itemType,o),r&&s.drawElements++}}}class _r extends mr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r;const o=[];o.push("#version 300 es"),o.push("// Triangles batching draw vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;")),o.push("out vec4 vColor;"),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching draw fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class vr extends mr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._lightsState,i=e._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching flat-shading draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),s){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e sliceThickness) { "),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" newColor = sliceColor;"),r.push(" }"),r.push("}")}r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;"),r.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),r.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),r.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,i=t.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching silhouette fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r){for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" newColor = sliceColor;"),o.push(" }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = newColor;"),o.push("}"),o}}class yr extends mr{constructor(e){super(e,!1,{instancing:!1,edges:!0})}}class xr extends yr{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Br extends yr{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class wr extends mr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class Pr extends mr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Cr extends mr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec3 worldNormal = octDecode(normal.xy); "),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class Mr extends mr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching occlusion vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class Er extends mr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching depth fragment shader"),s.push("precision highp float;"),s.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),s.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),s.push("}"),s}}class Fr extends mr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class Ir extends mr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry shadow vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" int colorFlag = int(flags) & 0xF;"),i.push(" bool visible = (colorFlag > 0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}}class Dr extends mr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Triangles batching quality draw vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),o.push("vFragDepth = 1.0 + clipPos.w;")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Triangles batching quality draw fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),n.push("uniform sampler2D uAOMap;"),n.push("in vec4 vViewPosition;"),n.push("in vec3 vViewNormal;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("in vec2 vMetallicRoughness;"),s.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick flat normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick flat normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class Tr extends mr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching color texture vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=this._useAlphaCutoff,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching color texture fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Qr=c.vec3(),Vr=c.vec3(),Hr=c.vec3(),jr=c.vec3(),Gr=c.mat4();class zr extends gr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Qr;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Vr;if(l){const e=Hr;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=z(p,t,Gr),m=jr,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElements(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Wr{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._colorTextureRendererAlphaCutoff&&!this._colorTextureRendererAlphaCutoff.getValid()&&(this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererAlphaCutoff=null),this._colorTextureRendererWithSAOAlphaCutoff&&!this._colorTextureRendererWithSAOAlphaCutoff.getValid()&&(this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new br(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new wr(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new Pr(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Nr(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new zr(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new _r(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new _r(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new vr(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new vr(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Tr(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Tr(this._scene,!0)),this._colorTextureRendererWithSAO}get colorTextureRendererAlphaCutoff(){return this._colorTextureRendererAlphaCutoff||(this._colorTextureRendererAlphaCutoff=new Tr(this._scene,!1,{useAlphaCutoff:!0})),this._colorTextureRendererAlphaCutoff}get colorTextureRendererWithSAOAlphaCutoff(){return this._colorTextureRendererWithSAOAlphaCutoff||(this._colorTextureRendererWithSAOAlphaCutoff=new Tr(this._scene,!0,{useAlphaCutoff:!0})),this._colorTextureRendererWithSAOAlphaCutoff}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new Dr(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Dr(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new br(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Er(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Fr(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new xr(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Br(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new wr(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Cr(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Sr(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Pr(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Mr(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Ir(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new zr(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Nr(this._scene)),this._snapInitRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererAlphaCutoff&&this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff&&this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Kr={};let Xr=65536,Jr=5e6;class Yr{constructor(){}set doublePrecisionEnabled(e){c.setDoublePrecisionEnabled(e)}get doublePrecisionEnabled(){return c.getDoublePrecisionEnabled()}set maxDataTextureHeight(e){(e=1024*Math.ceil(e/1024))>4096?e=4096:e<1024&&(e=1024),Xr=e}get maxDataTextureHeight(){return Xr}set maxGeometryBatchSize(e){e<1e5?e=1e5:e>5e6&&(e=5e6),Jr=e}get maxGeometryBatchSize(){return Jr}}const Zr=new Yr;class qr{constructor(e=Zr.maxGeometryBatchSize){this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const $r=c.mat4(),eo=c.mat4();function to(e,t,i){const s=e.length,r=new Uint16Array(s),o=t[0],n=t[1],a=t[2],l=t[3]-o,A=t[4]-n,h=t[5]-a,u=65525,d=u/l,p=u/A,f=u/h,g=e=>e>=0?e:0;for(let t=0;t=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 ro(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}const oo=c.mat4(),no=c.mat4(),ao=c.vec4([0,0,0,1]),lo=c.vec3(),Ao=c.vec3(),ho=c.vec3(),co=c.vec3(),uo=c.vec3(),po=c.vec3(),fo=c.vec3();class go{constructor(e){this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Kr[t];return i||(i=new Wr(e),Kr[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Kr[t],i._destroy()}))),i}(e.model.scene),this._buffer=new qr(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new lt({origin:c.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:e.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=c.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=c.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=c.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.solid=!!e.solid,this.primitive=e.primitive}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)for(let e=0,t=o.length;e0){const e=oo;m?c.inverseMat4(c.transposeMat4(m,no),e):c.identityMat4(e,e),function(e,t,i,s,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,A,h,u,d=new Float32Array([0,0,0,0]),p=new Float32Array([0,0,0,0]);for(u=0;uh&&(l=n,h=A),n=so(p,"floor","ceil"),a=ro(n),A=o(p,a),A>h&&(l=n,h=A),n=so(p,"ceil","ceil"),a=ro(n),A=o(p,a),A>h&&(l=n,h=A),s[r+u+0]=l[0],s[r+u+1]=l[1],s[r+u+2]=0}(e,r,r.length,b.normals,b.normals.length)}if(l)for(let e=0,t=l.length;e0)for(let e=0,t=n.length;e0)for(let e=0,t=a.length;e0){const s=this._state.positionsDecodeMatrix?new Uint16Array(i.positions):to(i.positions,this._modelAABB,this._state.positionsDecodeMatrix=c.mat4());if(e.positionsBuf=new He(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this.model.scene.readableGeometryEnabled)for(let e=0,t=this._portions.length;e0){const s=new Int8Array(i.normals);let r=!0;e.normalsBuf=new He(t,t.ARRAY_BUFFER,s,i.normals.length,3,t.STATIC_DRAW,r)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new He(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.uv.length>0)if(e.uvDecodeMatrix){let s=!1;e.uvBuf=new He(t,t.ARRAY_BUFFER,i.uv,i.uv.length,2,t.STATIC_DRAW,s)}else{const s=Vt.getUVBounds(i.uv),r=Vt.compressUVs(i.uv,s.min,s.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=c.mat3(r.decodeMatrix),e.uvBuf=new He(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(i.metallicRoughness.length>0){const s=new Uint8Array(i.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new He(t,t.ARRAY_BUFFER,s,i.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s),o=!1;e.flagsBuf=new He(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new He(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new He(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new He(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){const s=new Uint32Array(i.edgeIndices);e.edgeIndicesBuf=new He(t,t.ELEMENT_ARRAY_BUFFER,s,i.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,i){t&J&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&te&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ee&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ie&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&q&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&se&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&Z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Y&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&q?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&Y?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=e,s=this._portions[i],r=4*s.vertsBaseIndex,o=4*s.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],A=t[2],h=t[3];for(let e=0;e_)&&(_=e,s.set(v),r&&c.triangleNormal(p,f,g,r),m=!0)}}return m&&r&&(c.transformVec3(this.model.worldNormalMatrix,r,r),c.normalizeVec3(r)),m}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}class mo extends gr{constructor(e,t,{edges:i=!1,useAlphaCutoff:s=!1}={}){super(e,t,{instancing:!0,edges:i,useAlphaCutoff:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;this._edges?t.drawElementsInstanced(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0,i.numInstances):(t.drawElementsInstanced(t.TRIANGLES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),r&&s.drawElements++)}}class _o extends mo{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r,o,n;const a=[];for(a.push("#version 300 es"),a.push("// Instancing geometry drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec2 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;"),r=0,o=i.lights.length;r= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),s&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),a.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),r=0,o=i.lights.length;r0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class vo extends mo{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry flat-shading drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState;let s,r;const o=t.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry flat-shading drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),o){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}for(n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),s=0,r=i.lights.length;s0,i=[];return i.push("#version 300 es"),i.push("// Instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing fill fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = newColor;"),s.push("}"),s}}class yo extends mo{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class xo extends yo{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Bo extends yo{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesColorRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class wo extends mo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class Po extends mo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Co extends mo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec2 normal;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("in vec4 modelNormalMatrixCol0;"),i.push("in vec4 modelNormalMatrixCol1;"),i.push("in vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class Mo extends mo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class Eo extends mo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Instancing geometry depth drawing fragment shader"),o.push("precision highp float;"),o.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),o.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),o.push("}"),o}}class Fo extends mo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class Io extends mo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const Do={3e3:"linearToLinear",3001:"sRGBToLinear"};class So extends mo{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Instancing geometry quality drawing vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),o.push("in vec4 modelMatrixCol0;"),o.push("in vec4 modelMatrixCol1;"),o.push("in vec4 modelMatrixCol2;"),o.push("in vec4 modelNormalMatrixCol0;"),o.push("in vec4 modelNormalMatrixCol1;"),o.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),o.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),o.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Instancing geometry quality drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),n.push("#define PI 3.14159265359"),n.push("#define RECIPROCAL_PI 0.31830988618"),n.push("#define RECIPROCAL_PI2 0.15915494"),n.push("#define EPSILON 1e-6"),n.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),n.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),n.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),n.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),n.push(" return normalize(surf_norm );"),n.push(" }"),n.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),n.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),n.push(" vec2 st0 = dFdx( uv.st );"),n.push(" vec2 st1 = dFdy( uv.st );"),n.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),n.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),n.push(" vec3 N = normalize( surf_norm );"),n.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),n.push(" mat3 tsn = mat3( S, T, N );"),n.push(" return normalize( tsn * mapN );"),n.push("}"),n.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),n.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),n.push("}"),n.push("struct IncidentLight {"),n.push(" vec3 color;"),n.push(" vec3 direction;"),n.push("};"),n.push("struct ReflectedLight {"),n.push(" vec3 diffuse;"),n.push(" vec3 specular;"),n.push("};"),n.push("struct Geometry {"),n.push(" vec3 position;"),n.push(" vec3 viewNormal;"),n.push(" vec3 worldNormal;"),n.push(" vec3 viewEyeDir;"),n.push("};"),n.push("struct Material {"),n.push(" vec3 diffuseColor;"),n.push(" float specularRoughness;"),n.push(" vec3 specularColor;"),n.push(" float shine;"),n.push("};"),n.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),n.push(" float r = ggxRoughness + 0.0001;"),n.push(" return (2.0 / (r * r) - 2.0);"),n.push("}"),n.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),n.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),n.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),n.push("}"),s.reflectionMaps.length>0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = "+Do[s.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = "+Do[s.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&i.push("out float vFlags;"),i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&i.push("vFlags = flags;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class Ro extends mo{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=this._useAlphaCutoff,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Vo=c.vec3(),Ho=c.vec3(),jo=c.vec3(),Go=c.vec3(),zo=c.mat4();class Wo extends gr{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Vo;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Ho;if(l){const e=c.transformPoint3(h,l,jo);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=z(p,t,zo),m=Go,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0,a.numInstances),a.edgeIndicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Ko{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._colorTextureRendererAlphaCutoff&&!this._colorTextureRendererAlphaCutoff.getValid()&&(this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererAlphaCutoff=null),this._colorTextureRendererWithSAOAlphaCutoff&&!this._colorTextureRendererWithSAOAlphaCutoff.getValid()&&(this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new bo(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new wo(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new Po(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Qo(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Wo(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new _o(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new _o(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new vo(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new vo(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Ro(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Ro(this._scene,!0)),this._colorTextureRendererWithSAO}get colorTextureRendererAlphaCutoff(){return this._colorTextureRendererAlphaCutoff||(this._colorTextureRendererAlphaCutoff=new Ro(this._scene,!1,{useAlphaCutoff:!0})),this._colorTextureRendererAlphaCutoff}get colorTextureRendererWithSAOAlphaCutoff(){return this._colorTextureRendererWithSAOAlphaCutoff||(this._colorTextureRendererWithSAOAlphaCutoff=new Ro(this._scene,!0,{useAlphaCutoff:!0})),this._colorTextureRendererWithSAOAlphaCutoff}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new So(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new So(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new bo(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Eo(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Fo(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new xo(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Bo(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new wo(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Co(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new To(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Po(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Mo(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Io(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Wo(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Qo(this._scene)),this._snapInitRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererAlphaCutoff&&this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff&&this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Xo={};const Jo=new Uint8Array(4),Yo=new Float32Array(1),Zo=c.vec4([0,0,0,1]),qo=new Float32Array(3),$o=c.vec3(),en=c.vec3(),tn=c.vec3(),sn=c.vec3(),rn=c.vec3(),on=c.vec3(),nn=c.vec3(),an=new Float32Array(4);class ln{constructor(e){this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Xo[t];return i||(i=new Ko(e),Xo[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Xo[t],i._destroy()}))),i}(e.model.scene),this._aabb=c.collapseAABB3(),this._state=new lt({numInstances:0,obb:c.OBB3(),origin:c.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrix=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.solid=!!e.solid,this.numIndices=e.geometry.numIndices,this.primitive=e.geometry.primitive}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;e.colorsBuf=new He(s,s.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,s.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let i=!1;e.metallicRoughnessBuf=new He(s,s.ARRAY_BUFFER,t,this._metallicRoughness.length,2,s.STATIC_DRAW,i)}if(o>0){let t=!1;e.flagsBuf=new He(s,s.ARRAY_BUFFER,new Float32Array(o),o,1,s.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new He(s,s.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,s.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const i=!1;e.positionsBuf=new He(s,s.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,s.STATIC_DRAW,i),e.positionsDecodeMatrix=c.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const i=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new He(s,s.ARRAY_BUFFER,i,i.length,4,s.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const i=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new He(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new He(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,s.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new He(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,s.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new He(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelMatrixCol1Buf=new He(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelMatrixCol2Buf=new He(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new He(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new He(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new He(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new He(s,s.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,s.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&i&&i.colorTexture&&i.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!i&&!!i.colorTexture,this.model.scene.readableGeometryEnabled||(this._state.geometry=null),this._finalized=!0}initFlags(e,t,i){t&J&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&te&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ee&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ie&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&q&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&se&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&Z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Y&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&q?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&Y?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";Jo[0]=t[0],Jo[1]=t[1],Jo[2]=t[2],Jo[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(Jo,4*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&J),r=!!(t&ee),o=!!(t&te),n=!!(t&ie),a=!!(t&se),l=!!(t&Z),A=!!(t&Y);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Ar.NOT_RENDERED:i?Ar.COLOR_TRANSPARENT:Ar.COLOR_OPAQUE,c=!s||A?Ar.NOT_RENDERED:n?Ar.SILHOUETTE_SELECTED:o?Ar.SILHOUETTE_HIGHLIGHTED:r?Ar.SILHOUETTE_XRAYED:Ar.NOT_RENDERED;let u=0;u=!s||A?Ar.NOT_RENDERED:n?Ar.EDGES_SELECTED:o?Ar.EDGES_HIGHLIGHTED:r?Ar.EDGES_XRAYED:a?i?Ar.EDGES_COLOR_TRANSPARENT:Ar.EDGES_COLOR_OPAQUE:Ar.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Ar.PICK:Ar.NOT_RENDERED)<<12,d|=(t&q?1:0)<<16,Yo[0]=d,this._state.flagsBuf&&this._state.flagsBuf.setData(Yo,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(qo[0]=t[0],qo[1]=t[1],qo[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(qo,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.readableGeometryEnabled)return!1;const i=this._state,s=i.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=s.positionsCompressed,n=i.origin,a=n[0],l=n[1],A=n[2],h=Zo,u=r.matrix,d=this.model.matrix,p=i.positionsDecodeMatrix;for(let e=0,i=o.length;ev)&&(v=e,s.set(b),r&&c.triangleNormal(f,g,m,r),_=!0)}}return _&&r&&(c.transformVec3(a.normalMatrix,r,r),c.transformVec3(this.model.worldNormalMatrix,r,r),c.normalizeVec3(r)),_}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}class An extends gr{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawElements(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0),r&&s.drawElements++}}class hn extends An{drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class cn extends An{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const un=c.vec3(),dn=c.vec3(),pn=c.vec3(),fn=c.vec3(),gn=c.mat4();class mn extends gr{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=un;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=dn;if(l){const e=pn;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=z(p,t,gn),m=fn,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const _n=c.vec3(),vn=c.vec3(),bn=c.vec3(),yn=c.vec3(),xn=c.mat4();class Bn extends gr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=_n;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=vn;if(l){const e=bn;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=z(p,t,xn),m=yn,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class wn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new hn(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new cn(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new mn(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Bn(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Pn={};class Cn{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}class Mn{constructor(e){this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Pn[t];return i||(i=new wn(e),Pn[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Pn[t],i._destroy()}))),i}(e.model.scene),this.model=e.model,this._buffer=new Cn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new lt({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:c.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=c.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=c.vec3(e.origin)),this.primitive=e.primitive}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new He(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=to(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new He(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new He(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.colors.length>0){const s=i.colors.length/4,r=new Float32Array(s);let o=!1;e.flagsBuf=new He(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new He(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new He(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&J&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&te&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ee&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ie&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&q&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&se&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&Z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Y&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&q?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&Y?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],A=t[3];for(let e=0;e0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 lightAmbient;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Lines instancing color fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),o.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):o.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class In extends En{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const Dn=c.vec3(),Sn=c.vec3(),Tn=c.vec3();c.vec3();const Rn=c.mat4();class Ln extends gr{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Dn;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Sn;if(l){const e=c.transformPoint3(h,l,Tn);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=z(p,t,Rn),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),a.indicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Un=c.vec3(),On=c.vec3(),kn=c.vec3();c.vec3();const Nn=c.mat4();class Qn extends gr{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Un;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=On;if(l){const e=c.transformPoint3(h,l,kn);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=z(p,t,Nn),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Vn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._snapInitRenderer||(this._snapInitRenderer=new Ln(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Qn(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Fn(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new In(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Ln(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Qn(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Hn={};const jn=new Uint8Array(4),Gn=new Float32Array(1),zn=new Float32Array(3),Wn=new Float32Array(4);class Kn{constructor(e){this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Hn[t];return i||(i=new Vn(e),Hn[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Hn[t],i._destroy()}))),i}(e.model.scene),this._aabb=c.collapseAABB3(),this._state=new lt({obb:c.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,e.origin&&(this._state.origin=c.vec3(e.origin)),this._finalized=!1,this.primitive=e.primitive}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;this._state.colorsBuf=new He(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(r>0){let t=!1;this._state.flagsBuf=new He(e,e.ARRAY_BUFFER,new Float32Array(r),r,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new He(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.colorsCompressed&&i.colorsCompressed.length>0){const s=new Uint8Array(i.colorsCompressed),r=!1;t.colorsBuf=new He(e,e.ARRAY_BUFFER,s,s.length,4,e.STATIC_DRAW,r)}if(i.positionsCompressed&&i.positionsCompressed.length>0){const s=!1;t.positionsBuf=new He(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,s),t.positionsDecodeMatrix=c.mat4(i.positionsDecodeMatrix)}if(i.indices&&i.indices.length>0&&(t.indicesBuf=new He(e,e.ELEMENT_ARRAY_BUFFER,new Uint32Array(i.indices),i.indices.length,1,e.STATIC_DRAW),t.numIndices=i.indices.length),this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new He(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new He(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new He(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this.model.scene.readableGeometryEnabled||(this._state.geometry=null),this._finalized=!0}initFlags(e,t,i){t&J&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&te&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ee&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ie&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&q&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&se&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&Z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Y&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&q?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&Y?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";jn[0]=t[0],jn[1]=t[1],jn[2]=t[2],jn[3]=t[3],this._state.colorsBuf.setData(jn,4*e,4)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&J),r=!!(t&ee),o=!!(t&te),n=!!(t&ie),a=!!(t&se),l=!!(t&Z),A=!!(t&Y);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Ar.NOT_RENDERED:i?Ar.COLOR_TRANSPARENT:Ar.COLOR_OPAQUE,c=!s||A?Ar.NOT_RENDERED:n?Ar.SILHOUETTE_SELECTED:o?Ar.SILHOUETTE_HIGHLIGHTED:r?Ar.SILHOUETTE_XRAYED:Ar.NOT_RENDERED;let u=0;u=!s||A?Ar.NOT_RENDERED:n?Ar.EDGES_SELECTED:o?Ar.EDGES_HIGHLIGHTED:r?Ar.EDGES_XRAYED:a?i?Ar.EDGES_COLOR_TRANSPARENT:Ar.EDGES_COLOR_OPAQUE:Ar.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Ar.PICK:Ar.NOT_RENDERED)<<12,d|=(t&q?255:0)<<16,Gn[0]=d,this._state.flagsBuf.setData(Gn,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(zn[0]=t[0],zn[1]=t[1],zn[2]=t[2],this._state.offsetsBuf.setData(zn,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;Wn[0]=t[0],Wn[1]=t[4],Wn[2]=t[8],Wn[3]=t[12],this._state.modelMatrixCol0Buf.setData(Wn,i),Wn[0]=t[1],Wn[1]=t[5],Wn[2]=t[9],Wn[3]=t[13],this._state.modelMatrixCol1Buf.setData(Wn,i),Wn[0]=t[2],Wn[1]=t[6],Wn[2]=t[10],Wn[3]=t[14],this._state.modelMatrixCol2Buf.setData(Wn,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ar.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ar.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ar.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ar.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ar.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Ar.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Ar.PICK)}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class Xn extends gr{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,i.positionsBuf.numItems),r&&s.drawArrays++}}class Jn extends Xn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial,s=[];return s.push("#version 300 es"),s.push("// Points batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Yn extends Xn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points batching silhouette vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = color;"),o.push("}"),o}}class Zn extends Xn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class qn extends Xn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batched pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batched pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class $n extends Xn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push(" gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}const ea=c.vec3(),ta=c.vec3(),ia=c.vec3(),sa=c.vec3(),ra=c.mat4();class oa extends gr{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=ea;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=ta;if(l){const e=ia;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=z(p,t,ra),m=sa,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const na=c.vec3(),aa=c.vec3(),la=c.vec3(),Aa=c.vec3(),ha=c.mat4();class ca extends gr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=na;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=aa;if(l){const e=la;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=z(p,t,ha),m=Aa,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class ua{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Jn(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Yn(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Zn(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new qn(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new $n(this._scene)),this._occlusionRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new oa(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new ca(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const da={};class pa{constructor(e){this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=da[t];return i||(i=new ua(e),da[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete da[t],i._destroy()}))),i}(e.model.scene);const t=e.maxGeometryBatchSize||5e6,i=function(){const e=[];return{append:function(t,i=1,s=1){e.push({data:t,times:i,denormalizeScale:s})},compileBuffer:function(t){let i=0;e.forEach((e=>{i+=e.times*e.data.length}));const s=new t(i);let r=0;return e.forEach((e=>{const t=e.data,i=e.denormalizeScale,o=s.subarray(r);if(1===i)o.set(t,0);else for(let e=0;ee.length>0?new He(t,t.ARRAY_BUFFER,e,e.length,i,s):null,r=this._preCompressedPositionsExpected?i.positions.compileBuffer(Uint16Array):to(i.positions.compileBuffer(Float32Array),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=s(r,3,t.STATIC_DRAW),e.flagsBuf=s(new Float32Array(this._buffer.vertsIndex),1,t.DYNAMIC_DRAW),e.colorsBuf=s(i.colors.compileBuffer(Uint8Array),4,t.STATIC_DRAW),e.pickColorsBuf=s(i.pickColors.compileBuffer(Uint8Array),4,t.STATIC_DRAW),e.offsetsBuf=this.model.scene.entityOffsetsEnabled?s(new Float32Array(3*this._buffer.vertsIndex),3,t.DYNAMIC_DRAW):null,this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&J&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&te&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ee&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ie&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&q&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Y&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&q?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&Y?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class ma extends fa{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 silhouetteColor;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class _a extends fa{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick mesh fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class va extends fa{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class ba extends fa{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class ya extends fa{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points instancing depth vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return o.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class xa extends fa{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("gl_PointSize = pointSize;"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const Ba=c.vec3(),wa=c.vec3(),Pa=c.vec3();c.vec3();const Ca=c.mat4();class Ma extends gr{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Ba;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=wa;if(l){const e=c.transformPoint3(h,l,Pa);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=z(p,t,Ca),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ea=c.vec3(),Fa=c.vec3(),Ia=c.vec3();c.vec3();const Da=c.mat4();class Sa extends gr{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Ea;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Fa;if(l){const e=c.transformPoint3(h,l,Ia);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=z(p,t,Da),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Ta{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new ga(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new ma(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new ya(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new _a(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new va(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new ba(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new xa(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Ma(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Sa(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Ra={};const La=new Uint8Array(4),Ua=new Float32Array(1),Oa=new Float32Array(3),ka=new Float32Array(4);class Na{constructor(e){this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Ra[t];return i||(i=new Ta(e),Ra[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Ra[t],i._destroy()}))),i}(e.model.scene),this._aabb=c.collapseAABB3(),this._state=new lt({obb:c.OBB3(),numInstances:0,origin:e.origin?c.vec3(e.origin):null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,this.primitive=e.geometry.primitive}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let s=!1;i.flagsBuf=new He(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,s)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;i.offsetsBuf=new He(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(s.positionsCompressed&&s.positionsCompressed.length>0){const t=!1;i.positionsBuf=new He(e,e.ARRAY_BUFFER,s.positionsCompressed,s.positionsCompressed.length,3,e.STATIC_DRAW,t),i.positionsDecodeMatrix=c.mat4(s.positionsDecodeMatrix)}if(s.colorsCompressed&&s.colorsCompressed.length>0){const t=new Uint8Array(s.colorsCompressed),r=!1;i.colorsBuf=new He(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;i.modelMatrixCol0Buf=new He(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),i.modelMatrixCol1Buf=new He(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),i.modelMatrixCol2Buf=new He(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;i.pickColorsBuf=new He(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}i.geometry=null,this._finalized=!0}initFlags(e,t,i){t&J&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&te&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ee&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ie&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&q&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&se&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&Z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Y&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&q?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&Y?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";La[0]=t[0],La[1]=t[1],La[2]=t[2],this._state.colorsBuf.setData(La,3*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&J),r=!!(t&ee),o=!!(t&te),n=!!(t&ie),a=!!(t&se),l=!!(t&Z),A=!!(t&Y);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Ar.NOT_RENDERED:i?Ar.COLOR_TRANSPARENT:Ar.COLOR_OPAQUE,c=!s||A?Ar.NOT_RENDERED:n?Ar.SILHOUETTE_SELECTED:o?Ar.SILHOUETTE_HIGHLIGHTED:r?Ar.SILHOUETTE_XRAYED:Ar.NOT_RENDERED;let u=0;u=!s||A?Ar.NOT_RENDERED:n?Ar.EDGES_SELECTED:o?Ar.EDGES_HIGHLIGHTED:r?Ar.EDGES_XRAYED:a?i?Ar.EDGES_COLOR_TRANSPARENT:Ar.EDGES_COLOR_OPAQUE:Ar.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Ar.PICK:Ar.NOT_RENDERED)<<12,d|=(t&q?255:0)<<16,Ua[0]=d,this._state.flagsBuf.setData(Ua,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Oa[0]=t[0],Oa[1]=t[1],Oa[2]=t[2],this._state.offsetsBuf.setData(Oa,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;ka[0]=t[0],ka[1]=t[4],ka[2]=t[8],ka[3]=t[12],this._state.modelMatrixCol0Buf.setData(ka,i),ka[0]=t[1],ka[1]=t[5],ka[2]=t[9],ka[3]=t[13],this._state.modelMatrixCol1Buf.setData(ka,i),ka[0]=t[2],ka[1]=t[6],ka[2]=t[10],ka[3]=t[14],this._state.modelMatrixCol2Buf.setData(ka,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ar.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ar.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ar.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ar.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ar.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Ar.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Ar.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Ar.PICK)}drawPickNormals(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Ar.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Ar.PICK)}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}const Qa=c.vec3(),Va=c.vec3(),Ha=c.mat4();class ja{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uPerObjectDecodeMatrix,this._uPerVertexPosition,this.uPerObjectColorAndFlags,this._uPerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=Qa;if(g){const t=c.transformPoint3(u,A,Va);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=z(p,e,Ha)}else f=p;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,8),n.drawArrays(n.LINES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,16),n.drawArrays(n.LINES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,32),n.drawArrays(n.LINES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// LinesDataTextureColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uPerObjectDecodeMatrix;"),i.push("uniform highp sampler2D uPerObjectMatrix;"),i.push("uniform lowp usampler2D uPerObjectColorAndFlags;"),i.push("uniform mediump usampler2D uPerVertexPosition;"),i.push("uniform highp usampler2D uPerLineIndices;"),i.push("uniform mediump usampler2D uPerLineObject;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push(" int lineIndex = gl_VertexID / 2;"),i.push(" int h_packed_object_id_index = (lineIndex >> 3) & 4095;"),i.push(" int v_packed_object_id_index = (lineIndex >> 3) >> 12;"),i.push(" int objectIndex = int(texelFetch(uPerLineObject, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push(" ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" } else {"),i.push(" ivec4 packedVertexBase = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push(" ivec4 packedLineIndexBaseOffset = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push(" int lineIndexBaseOffset = (packedLineIndexBaseOffset.r << 24) + (packedLineIndexBaseOffset.g << 16) + (packedLineIndexBaseOffset.b << 8) + packedLineIndexBaseOffset.a;"),i.push(" int h_index = (lineIndex - lineIndexBaseOffset) & 4095;"),i.push(" int v_index = (lineIndex - lineIndexBaseOffset) >> 12;"),i.push(" ivec3 vertexIndices = ivec3(texelFetch(uPerLineIndices, ivec2(h_index, v_index), 0));"),i.push(" ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push(" int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push(" int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push(" mat4 objectInstanceMatrix = mat4 (texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" vec3 position = vec3(texelFetch(uPerVertexPosition, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" uvec4 color = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push(" if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" };"),i.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push(" vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push(" vFragDepth = 1.0 + clipPos.w;"),i.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push(" gl_Position = clipPos;"),i.push(" vec4 rgb = vec4(color.rgba);"),i.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// LinesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Ga{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null)}eagerCreateRenders(){}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new ja(this._scene,!1)),this._colorRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy()}}const za={};class Wa{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perLineNumberPortionId8Bits=[],this.perLineNumberPortionId16Bits=[],this.perLineNumberPortionId32Bits=[]}}class Ka{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerLineIdPortionIds8Bits=null,this.texturePerLineIdPortionIds16Bits=null,this.texturePerLineIdPortionIds32Bits=null,this.texturePerLineIdIndices8Bits=null,this.texturePerLineIdIndices16Bits=null,this.texturePerLineIdIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerLineIdIndices8Bits,16:this.texturePerLineIdIndices16Bits,32:this.texturePerLineIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerLineIdPortionIds8Bits,16:this.texturePerLineIdPortionIds16Bits,32:this.texturePerLineIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindLineIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}}class Xa{constructor(e,t,i,s,r=null){this._gl=e,this._texture=t,this._textureWidth=i,this._textureHeight=s,this._textureData=r}bindTexture(e,t,i){return e.bindTexture(t,this,i)}bind(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}unbind(e){}}const Ja={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalLines:0,totalLines8Bits:0,totalLines16Bits:0,totalLines32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(Ja,null,4));let e=0;Object.keys(Ja).forEach((t=>{t.startsWith("size")&&(e+=Ja[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/Ja.totalLines).toFixed(2)}`);let t={};Object.keys(Ja).forEach((i=>{i.startsWith("size")&&(t[i]=`${(Ja[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class Ya{disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}generateTextureForColorsAndFlags(e,t,i,s,r){const o=t.length;this.numPortions=o;const n=4096,a=Math.ceil(o/512);if(0===a)throw"texture height===0";const l=new Uint8Array(16384*a);Ja.sizeDataColorsAndFlags+=l.byteLength,Ja.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),l.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20);const A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,n,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,a,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Xa(e,A,n,a,l)}generateTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);Ja.sizeDataTextureOffsets+=r.byteLength,Ja.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Xa(e,o,i,s,r)}generateTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);Ja.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete za[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new Wa,this._dataTextureState=new Ka,this._dataTextureGenerator=new Ya,this._state=new lt({origin:c.vec3(t.origin),textureState:this._dataTextureState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this.primitive=t.primitive,this._finalized=!1}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&Ja.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/2})),(this._state.numVertices+s>4096*qa||t+r>4096*qa)&&Ja.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*qa&&t+r<=4096*qa}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/2/8)*2;Ja.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}const i=t.positionsCompressed,s=t.indices,r=this._buffer;r.positionsCompressed.push(i);const o=r.lenPositionsCompressed/3,n=i.length/3;let a;r.lenPositionsCompressed+=i.length;let l=0;if(s){let e;l=s.length/2,n<=256?(e=r.indices8Bits,a=r.lenIndices8Bits/2,r.lenIndices8Bits+=s.length):n<=65536?(e=r.indices16Bits,a=r.lenIndices16Bits/2,r.lenIndices16Bits+=s.length):(e=r.indices32Bits,a=r.lenIndices32Bits/2,r.lenIndices32Bits+=s.length),e.push(s)}this._state.numVertices+=n,Ja.numberOfGeometries++;return{vertexBase:o,numVertices:n,numLines:l,indicesBase:a}}_createSubPortion(e,t){const i=e.color,s=e.colors,r=e.opacity,o=e.meshMatrix,n=e.pickColor,a=this._buffer,l=this._state;a.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),a.perObjectInstancePositioningMatrices.push(o||sl),a.perObjectSolid.push(!!e.solid),s?a.perObjectColors.push([255*s[0],255*s[1],255*s[2],255]):i&&a.perObjectColors.push([i[0],i[1],i[2],r]),a.perObjectPickColors.push(n),a.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?l.numIndices8Bits:t.numVertices<=65536?l.numIndices16Bits:l.numIndices32Bits,a.perObjectIndexBaseOffsets.push(e/2-t.indicesBase)}const A=this._subPortions.length;if(t.numLines>0){let e,i=2*t.numLines;t.numVertices<=256?(e=a.perLineNumberPortionId8Bits,l.numIndices8Bits+=i,Ja.totalLines8Bits+=t.numLines):t.numVertices<=65536?(e=a.perLineNumberPortionId16Bits,l.numIndices16Bits+=i,Ja.totalLines16Bits+=t.numLines):(e=a.perLineNumberPortionId32Bits,l.numIndices32Bits+=i,Ja.totalLines32Bits+=t.numLines),Ja.totalLines+=t.numLines;for(let i=0;i0&&(t.texturePerLineIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerLineIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerLineIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}initFlags(e,t,i){t&J&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&te&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ee&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ie&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&q&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Y&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&q?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&Y?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,el))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),c.bindTexture(c.TEXTURE_2D,h.texturePerObjectColorsAndFlags._texture),c.texSubImage2D(c.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,c.RGBA_INTEGER,c.UNSIGNED_BYTE,el))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,el))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,tl))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,$a))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ar.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ar.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){}drawSilhouetteHighlighted(e,t){}drawSilhouetteSelected(e,t){}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}setPickMatrices(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawSnapInit(e,t){}drawSnap(e,t){}drawPickNormals(e,t){}destroy(){if(this._destroyed)return;const e=this._state;this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}const ol=c.vec3(),nl=c.vec3(),al=c.vec3();c.vec3();const ll=c.vec4(),Al=c.mat4();class hl{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=ol;if(g){const t=c.transformPoint3(u,A,nl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=z(r.viewMatrix,e,Al),f=al,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(let e=0,t=r.length;e0;let r;const o=[];o.push("#version 300 es"),o.push("// TrianglesDataTextureColorRenderer vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("uniform mat4 sceneModelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),o.push("uniform highp sampler2D uTexturePerObjectMatrix;"),o.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),o.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),o.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),o.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),o.push("uniform vec3 uCameraEyeRtc;"),o.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("out float isPerspective;")),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e> 3) & 4095;"),o.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),o.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),o.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),o.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),o.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),o.push("if (int(flags.x) != renderPass) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("} else {"),o.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),o.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),o.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),o.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),o.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),o.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),o.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),o.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),o.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),o.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),o.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),o.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),o.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),o.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),o.push("if (color.a == 0u) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("};"),o.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),o.push("vec3 position;"),o.push("position = positions[gl_VertexID % 3];"),o.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),o.push("if (solid != 1u) {"),o.push("if (isPerspectiveMatrix(projMatrix)) {"),o.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),o.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("} else {"),o.push("if (viewNormal.z < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("}"),o.push("}"),o.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const cl=new Float32Array([1,1,1]),ul=c.vec3(),dl=c.vec3(),pl=c.vec3();c.vec3();const fl=c.mat4();class gl{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=ul;if(A){const t=dl;c.transformPoint3(u,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=z(p,e,fl),g=pl,g[0]=r.eye[0]-e[0],g[1]=r.eye[1]-e[1],g[2]=r.eye[2]-e[2]}else f=p,g=r.eye;if(n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),i===Ar.SILHOUETTE_XRAYED){const e=s.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Ar.SILHOUETTE_HIGHLIGHTED){const e=s.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Ar.SILHOUETTE_SELECTED){const e=s.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,cl);if(s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(m>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,r=o.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = color;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ml=new Float32Array([0,0,0,1]),_l=c.vec3(),vl=c.vec3();c.vec3();const bl=c.mat4();class yl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=_l;if(g){const t=c.transformPoint3(u,A,vl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=z(p,e,bl)}else f=p;if(n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),i===Ar.EDGES_XRAYED){const e=r.xrayMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Ar.EDGES_HIGHLIGHTED){const e=r.highlightMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Ar.EDGES_SELECTED){const e=r.selectedMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,ml);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const xl=c.vec3(),Bl=c.vec3(),wl=c.mat4();class Pl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=xl;if(g){const t=c.transformPoint3(u,A,Bl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=z(p,e,wl)}else f=p;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uObjectPerObjectOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Cl=c.vec3(),Ml=c.vec3(),El=c.vec3(),Fl=c.mat4();class Il{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=e.pickViewMatrix||o.viewMatrix,f=e.pickProjMatrix||o.projMatrix,g=e.pickOrigin||o.eye,m=e.pickProjMatrix?e.pickZFar:o.project.far;let _,v;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const b=0!==A[0]||0!==A[1]||0!==A[2],y=0!==h[0]||0!==h[1]||0!==h[2];if(b||y){const e=Cl;if(b){const t=c.transformPoint3(u,A,Ml);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],_=z(p,e,Fl),v=El,v[0]=g[0]-e[0],v[1]=g[1]-e[1],v[2]=g[2]-e[2]}else _=p,v=g;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,_),n.uniformMatrix4fv(this._uProjMatrix,!1,f),n.uniform3fv(this._uCameraEyeRtc,v),n.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(m+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const x=r._sectionPlanesState.getNumAllocatedSectionPlanes(),B=r._sectionPlanesState.sectionPlanes.length;if(x>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*B,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var s=0;s 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Dl=c.vec3(),Sl=c.vec3(),Tl=c.vec3();c.vec3();const Rl=c.mat4();class Ll{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=e.pickViewMatrix||o.viewMatrix,f=e.pickProjMatrix||o.projMatrix,g=e.pickOrigin||o.eye,m=e.pickProjMatrix?e.pickZFar:o.project.far;let _,v;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const t=Dl;if(A){const e=Sl;c.transformPoint3(u,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],_=z(p,t,Rl),v=Tl,v[0]=g[0]-t[0],v[1]=g[1]-t[1],v[2]=g[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else _=p,v=g,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(n.uniform3fv(this._uCameraEyeRtc,v),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniform1f(this._uPickZNear,e.pickZNear),n.uniform1f(this._uPickZFar,e.pickZFar),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,_),n.uniformMatrix4fv(this._uProjMatrix,!1,f),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(m+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const b=r._sectionPlanesState.getNumAllocatedSectionPlanes(),y=r._sectionPlanesState.sectionPlanes.length;if(b>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*y,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0;s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outPackedDepth = packDepth(zNormalizedDepth); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ul=c.vec3(),Ol=c.vec3(),kl=c.vec3(),Nl=c.vec3();c.vec3();const Ql=c.mat4();class Vl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=Ul;let m,_;g[0]=c.safeInv(p[3]-p[0])*c.MAX_INT,g[1]=c.safeInv(p[4]-p[1])*c.MAX_INT,g[2]=c.safeInv(p[5]-p[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(g[0]),e.snapPickCoordinateScale[1]=c.safeInv(g[1]),e.snapPickCoordinateScale[2]=c.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=Ol;if(v){const e=c.transformPoint3(u,A,kl);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=z(f,t,Ql),_=Nl,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),x=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*x,o=s.renderFlags;for(let t=0;t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(B,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(B,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(B,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uSnapVectorA;"),i.push("uniform vec2 uSnapInvVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),i.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("}"),i.push("{"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vViewPosition = clipPos;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Hl=c.vec3(),jl=c.vec3(),Gl=c.vec3(),zl=c.vec3();c.vec3();const Wl=c.mat4();class Kl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=Hl;let m,_;g[0]=c.safeInv(p[3]-p[0])*c.MAX_INT,g[1]=c.safeInv(p[4]-p[1])*c.MAX_INT,g[2]=c.safeInv(p[5]-p[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(g[0]),e.snapPickCoordinateScale[1]=c.safeInv(g[1]),e.snapPickCoordinateScale[2]=c.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=jl;if(v){const e=Gl;c.transformPoint3(u,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=z(f,t,Wl),_=zl,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this._uVectorA,e.snapVectorA),n.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),x=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*x,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uVectorAB;"),i.push("uniform vec2 uInverseVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),i.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("}"),i.push("{"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" } else {"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Xl=c.vec3(),Jl=c.vec3(),Yl=c.vec3();c.vec3();const Zl=c.mat4();class ql{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=e.pickViewMatrix||o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=Xl;if(A){const t=Jl;c.transformPoint3(u,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=z(p,e,Zl),g=Yl,g[0]=o.eye[0]-e[0],g[1]=o.eye[1]-e[1],g[2]=o.eye[2]-e[2]}else f=p,g=o.eye;n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureOcclusionRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" } else {"),i.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureColorRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const $l=c.vec3(),eA=c.vec3(),tA=c.vec3();c.vec3();const iA=c.mat4();class sA{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=$l;if(g){const t=c.transformPoint3(u,A,eA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=z(r.viewMatrix,e,iA),f=tA,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const rA=c.vec3(),oA=c.vec3(),nA=c.vec3();c.vec3();const aA=c.mat4();class lA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));const g=0!==l[0]||0!==l[1]||0!==l[2],m=0!==A[0]||0!==A[1]||0!==A[2];if(g||m){const e=rA;if(g){const t=oA;c.transformPoint3(h,l,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=A[0],e[1]+=A[1],e[2]+=A[2],p=z(d,e,aA),f=nA,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=d,f=o.eye;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),n.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&Se.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),Se.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out vec4 vFlags2;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(Se.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&Se.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&Se.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&Se.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const AA=c.vec3(),hA=c.vec3(),cA=c.vec3();c.vec3(),c.vec4();const uA=c.mat4();class dA{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a));const p=e.pickViewMatrix||r.viewMatrix,f=e.pickProjMatrix||r.projMatrix,g=e.pickOrigin||r.eye,m=e.pickProjMatrix?e.pickZFar:r.project.far;let _,v;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const b=0!==A[0]||0!==A[1]||0!==A[2],y=0!==h[0]||0!==h[1]||0!==h[2];if(b||y){const e=AA;if(b){const t=c.transformPoint3(u,A,hA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],_=z(p,e,uA),v=cA,v[0]=g[0]-e[0],v[1]=g[1]-e[1],v[2]=g[2]-e[2]}else _=p,v=g;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,_),n.uniformMatrix4fv(this._uProjMatrix,!1,f),n.uniform3fv(this._uCameraEyeRtc,v),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const e=2/(Math.log(m+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const x=s._sectionPlanesState.getNumAllocatedSectionPlanes(),B=s._sectionPlanesState.sectionPlanes.length;if(x>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*B,r=o.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ve(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// trianglesDatatextureNormalsRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTexturePickNormalsRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class pA{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new gl(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Il(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new Ll(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new dA(this._scene)),this._snapRenderer||(this._snapRenderer=new Vl(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Kl(this._scene)),this._snapRenderer||(this._snapRenderer=new Vl(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new hl(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new hl(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new gl(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new sA(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new lA(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new yl(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Pl(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Il(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new dA(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new dA(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Ll(this._scene)),this._pickDepthRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Vl(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Kl(this._scene)),this._snapInitRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new ql(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const fA={};class gA{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}class mA{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindTriangleIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}bindEdgeIndicesTextures(e,t,i,s){this.edgeIndicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[s].bindTexture(e,i,6)}}const _A={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(_A,null,4));let e=0;Object.keys(_A).forEach((t=>{t.startsWith("size")&&(e+=_A[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/_A.totalPolygons).toFixed(2)}`);let t={};Object.keys(_A).forEach((i=>{i.startsWith("size")&&(t[i]=`${(_A[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class vA{constructor(){}disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}createTextureForColorsAndFlags(e,t,i,s,r,o,n){const a=t.length;this.numPortions=a;const l=4096,A=Math.ceil(a/512);if(0===A)throw"texture height===0";const h=new Uint8Array(16384*A);_A.sizeDataColorsAndFlags+=h.byteLength,_A.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),h.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20),h.set([o[e]>>24&255,o[e]>>16&255,o[e]>>8&255,255&o[e]],32*e+24),h.set([n[e]?1:0,0,0,0],32*e+28);const c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,A),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,A,e.RGBA_INTEGER,e.UNSIGNED_BYTE,h,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Xa(e,c,l,A,h)}createTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);_A.sizeDataTextureOffsets+=r.byteLength,_A.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Xa(e,o,i,s,r)}createTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);_A.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete fA[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new gA,this._dtxState=new mA,this._dtxTextureFactory=new vA,this._state=new lt({origin:c.vec3(t.origin),metallicRoughnessBuf:null,textureState:this._dtxState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numEdgeIndices8Bits:0,numEdgeIndices16Bits:0,numEdgeIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this.model.scene.readableGeometryEnabled&&(this._subPortionReadableGeometries={}),this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this.primitive=t.primitive,this._finalized=!1}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&_A.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/3})),(this._state.numVertices+s>4096*yA||t+r>4096*yA)&&_A.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*yA&&t+r<=4096*yA}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/3/8)*3;_A.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}if(t.edgeIndices){const e=8*Math.ceil(t.edgeIndices.length/2/8)*2;_A.overheadSizeAlignementEdgeIndices+=2*(e-t.edgeIndices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.edgeIndices),t.edgeIndices=i}const i=t.positionsCompressed,s=t.indices,r=t.edgeIndices,o=this._buffer;o.positionsCompressed.push(i);const n=o.lenPositionsCompressed/3,a=i.length/3;let l;o.lenPositionsCompressed+=i.length;let A,h=0;if(s){let e;h=s.length/3,a<=256?(e=o.indices8Bits,l=o.lenIndices8Bits/3,o.lenIndices8Bits+=s.length):a<=65536?(e=o.indices16Bits,l=o.lenIndices16Bits/3,o.lenIndices16Bits+=s.length):(e=o.indices32Bits,l=o.lenIndices32Bits/3,o.lenIndices32Bits+=s.length),e.push(s)}let c=0;if(r){let e;c=r.length/2,a<=256?(e=o.edgeIndices8Bits,A=o.lenEdgeIndices8Bits/2,o.lenEdgeIndices8Bits+=r.length):a<=65536?(e=o.edgeIndices16Bits,A=o.lenEdgeIndices16Bits/2,o.lenEdgeIndices16Bits+=r.length):(e=o.edgeIndices32Bits,A=o.lenEdgeIndices32Bits/2,o.lenEdgeIndices32Bits+=r.length),e.push(r)}this._state.numVertices+=a,_A.numberOfGeometries++;return{vertexBase:n,numVertices:a,numTriangles:h,numEdges:c,indicesBase:l,edgeIndicesBase:A}}_createSubPortion(e,t,i,s){const r=e.color;e.metallic,e.roughness;const o=e.colors,n=e.opacity,a=e.meshMatrix,l=e.pickColor,A=this._buffer,h=this._state;A.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),A.perObjectInstancePositioningMatrices.push(a||MA),A.perObjectSolid.push(!!e.solid),o?A.perObjectColors.push([255*o[0],255*o[1],255*o[2],255]):r&&A.perObjectColors.push([r[0],r[1],r[2],n]),A.perObjectPickColors.push(l),A.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?h.numIndices8Bits:t.numVertices<=65536?h.numIndices16Bits:h.numIndices32Bits,A.perObjectIndexBaseOffsets.push(e/3-t.indicesBase)}{let e;e=t.numVertices<=256?h.numEdgeIndices8Bits:t.numVertices<=65536?h.numEdgeIndices16Bits:h.numEdgeIndices32Bits,A.perObjectEdgeIndexBaseOffsets.push(e/2-t.edgeIndicesBase)}const c=this._subPortions.length;if(t.numTriangles>0){let e,i=3*t.numTriangles;t.numVertices<=256?(e=A.perTriangleNumberPortionId8Bits,h.numIndices8Bits+=i,_A.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(e=A.perTriangleNumberPortionId16Bits,h.numIndices16Bits+=i,_A.totalPolygons16Bits+=t.numTriangles):(e=A.perTriangleNumberPortionId32Bits,h.numIndices32Bits+=i,_A.totalPolygons32Bits+=t.numTriangles),_A.totalPolygons+=t.numTriangles;for(let i=0;i0){let e,i=2*t.numEdges;t.numVertices<=256?(e=A.perEdgeNumberPortionId8Bits,h.numEdgeIndices8Bits+=i,_A.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(e=A.perEdgeNumberPortionId16Bits,h.numEdgeIndices16Bits+=i,_A.totalEdges16Bits+=t.numEdges):(e=A.perEdgeNumberPortionId32Bits,h.numEdgeIndices32Bits+=i,_A.totalEdges32Bits+=t.numEdges),_A.totalEdges+=t.numEdges;for(let i=0;i0&&(t.texturePerEdgeIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId8Bits)),s.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId16Bits)),s.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId32Bits)),s.lenIndices8Bits>0&&(t.texturePerPolygonIdIndices8Bits=this._dtxTextureFactory.createTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerPolygonIdIndices16Bits=this._dtxTextureFactory.createTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerPolygonIdIndices32Bits=this._dtxTextureFactory.createTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),s.lenEdgeIndices8Bits>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this._dtxTextureFactory.createTextureFor8BitsEdgeIndices(i,s.edgeIndices8Bits,s.lenEdgeIndices8Bits)),s.lenEdgeIndices16Bits>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this._dtxTextureFactory.createTextureFor16BitsEdgeIndices(i,s.edgeIndices16Bits,s.lenEdgeIndices16Bits)),s.lenEdgeIndices32Bits>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this._dtxTextureFactory.createTextureFor32BitsEdgeIndices(i,s.edgeIndices32Bits,s.lenEdgeIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}isEmpty(){return 0===this._numPortions}initFlags(e,t,i){t&J&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&te&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ee&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ie&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&q&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&se&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&Z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Y&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&q?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dtxState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&Y?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,wA))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),g.bindTexture(g.TEXTURE_2D,f.texturePerObjectColorsAndFlags._texture),g.texSubImage2D(g.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,g.RGBA_INTEGER,g.UNSIGNED_BYTE,wA))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,wA))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,PA))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,BA))}getEachVertex(e,t){if(!this.model.scene.readableGeometryEnabled)return;const i=this._state,s=this._portionToSubPortionsMap[e];if(s)for(let e=0,r=s.length;e{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==LA[e])return void LA[e].push({onLoad:t,onProgress:i,onError:s});LA[e]=[],LA[e].push({onLoad:t,onProgress:i,onError:s});const o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),n=this.mimeType,a=this.responseType;fetch(o).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;const i=LA[e],s=t.body.getReader(),r=t.headers.get("Content-Length"),o=r?parseInt(r):0,n=0!==o;let a=0;const l=new ReadableStream({start(e){!function t(){s.read().then((({done:s,value:r})=>{if(s)e.close();else{a+=r.byteLength;const s=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=i.length;e{switch(a){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,n)));case"json":return e.json();default:if(void 0===n)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(n),i=t&&t[1]?t[1].toLowerCase():void 0,s=new TextDecoder(i);return e.arrayBuffer().then((e=>s.decode(e)))}}})).then((t=>{DA.add(e,t);const i=LA[e];delete LA[e];for(let e=0,s=i.length;e{const i=LA[e];if(void 0===i)throw this.manager.itemError(e),t;delete LA[e];for(let e=0,s=i.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class OA{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e{const s=this._getIdleWorker();-1!==s?(this._initWorker(s),this.workerStatus|=1<e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let kA=0;class NA{constructor({viewer:e,transcoderPath:t,workerLimit:i}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new OA,this._workerSourceURL="",i&&this._workerPool.setWorkerLimit(i);const s=e.capabilities;this._workerConfig={astcSupported:s.astcSupported,etc1Supported:s.etc1Supported,etc2Supported:s.etc2Supported,dxtSupported:s.dxtSupported,bptcSupported:s.bptcSupported,pvrtcSupported:s.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new UA;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),i=new UA;i.setPath(this._transcoderPath),i.setResponseType("arraybuffer"),i.setWithCredentials(this.withCredentials);const s=i.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,s]).then((([e,t])=>{const i=NA.BasisWorker.toString(),s=["/* constants */","let _EngineFormat = "+JSON.stringify(NA.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(NA.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(NA.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([s])),this._transcoderBinary=t,this._workerPool.setWorkerCreator((()=>{const e=new Worker(this._workerSourceURL),t=this._transcoderBinary.slice(0);return e.postMessage({type:"init",config:this._workerConfig,transcoderBinary:t},[t]),e}))})),kA>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),kA++}return this._transcoderPending}transcode(e,t,i={}){return new Promise(((s,r)=>{const o=i;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const i=e.data,{mipmaps:o,width:n,height:a,format:l,type:A,error:h,dfdTransferFn:c,dfdFlags:u}=i;if("error"===A)return r(h);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?1006:1008,magFilter:1===o.length?1006:1008,encoding:2===c?3001:3e3,premultiplyAlpha:!!(1&u)}}),s()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),kA--}}NA.BasisFormat={ETC1S:0,UASTC_4x4:1},NA.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16},NA.EngineFormat={RGBAFormat:1023,RGBA_ASTC_4x4_Format:37808,RGBA_BPTC_Format:36492,RGBA_ETC2_EAC_Format:37496,RGBA_PVRTC_4BPPV1_Format:35842,RGBA_S3TC_DXT5_Format:33779,RGB_ETC1_Format:36196,RGB_ETC2_Format:37492,RGB_PVRTC_4BPPV1_Format:35840,RGB_S3TC_DXT1_Format:33776},NA.BasisWorker=function(){let e,t,i;const s=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const h=n.data;switch(h.type){case"init":e=h.config,c=h.transcoderBinary,t=new Promise((e=>{i={wasmBinary:c,onRuntimeInitialized:e},BASIS(i)})).then((()=>{i.initializeBasis(),void 0===i.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:c,mipmaps:u,format:d,dfdTransferFn:p,dfdFlags:f}=function(t){const n=new i.KTX2File(new Uint8Array(t));function h(){n.close(),n.delete()}if(!n.isValid())throw h(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const c=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),d=n.getHeight(),p=n.getLevels(),f=n.getHasAlpha(),g=n.getDFDTransferFunc(),m=n.getDFDFlags(),{transcoderFormat:_,engineFormat:v}=function(t,i,n,h){let c,u;const d=t===o.ETC1S?a:l;for(let s=0;s{delete QA[t],i.destroy()}))),i} /** * @author https://github.com/tmarti, with support from https://tribia.com/ * @license MIT @@ -14,7 +14,7 @@ /** * @author https://github.com/tmarti, with support from https://tribia.com/ * @license MIT - **/let WA=null;function KA(e,t){const i=3*e,s=3*t;let r,o,n,a,l,A;const h=Math.min(r=WA[i],o=WA[i+1],n=WA[i+2]),c=Math.min(a=WA[s],l=WA[s+1],A=WA[s+2]);if(h!==c)return h-c;const u=Math.max(r,o,n),d=Math.max(a,l,A);return u!==d?u-d:0}let XA=null;function JA(e,t){let i=XA[2*e]-XA[2*t];return 0!==i?i:XA[2*e+1]-XA[2*t+1]}function YA(e,t,i=!1){const s=e.positionsCompressed||[],r=function(e,t){const i=new Int32Array(e.length/3);for(let e=0,t=i.length;e>t;i.sort(KA);const s=new Int32Array(e.length);for(let t=0,r=i.length;te[t+1]){let i=e[t];e[t]=e[t+1],e[t+1]=i}XA=new Int32Array(e),t.sort(JA);const i=new Int32Array(e.length);for(let s=0,r=t.length;st){let i=e;e=t,t=i}function i(i,s){return i!==e?e-i:s!==t?t-s:0}let s=0,r=(o.length>>1)-1;for(;s<=r;){const e=r+s>>1,t=i(o[2*e],o[2*e+1]);if(t>0)s=e+1;else{if(!(t<0))return e;r=e-1}}return-s-1}const a=new Int32Array(o.length/2);a.fill(0);const l=s.length/3;if(l>8*(1<u.maxNumPositions&&(u=c()),u.bucketNumber>8)return[e];let p;-1===A[l]&&(A[l]=u.numPositions++,u.positionsCompressed.push(s[3*l]),u.positionsCompressed.push(s[3*l+1]),u.positionsCompressed.push(s[3*l+2])),-1===A[h]&&(A[h]=u.numPositions++,u.positionsCompressed.push(s[3*h]),u.positionsCompressed.push(s[3*h+1]),u.positionsCompressed.push(s[3*h+2])),-1===A[d]&&(A[d]=u.numPositions++,u.positionsCompressed.push(s[3*d]),u.positionsCompressed.push(s[3*d+1]),u.positionsCompressed.push(s[3*d+2])),u.indices.push(A[l]),u.indices.push(A[h]),u.indices.push(A[d]),(p=n(l,h))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(l,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(h,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]]))}const d=t/8*2,p=t/8,f=2*s.length+(r.length+o.length)*d;let g=0,m=-s.length/3;return h.forEach((e=>{g+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*p,m+=e.positionsCompressed.length/3})),g>f?[e]:(i&&function(e,t){const i={},s={};let r=0;e.forEach((e=>{const t=e.indices,o=e.edgeIndices,n=e.positionsCompressed;for(let e=0,s=t.length;e0){const e=t._meshes;for(let t=0,i=e.length;t0){const e=this._meshes;for(let t=0,i=e.length;t{this._viewMatrixDirty=!0})),this._meshesWithDirtyMatrices=[],this._numMeshesWithDirtyMatrices=0,this._onTick=this.scene.on("tick",(()=>{for(;this._numMeshesWithDirtyMatrices>0;)this._meshesWithDirtyMatrices[--this._numMeshesWithDirtyMatrices]._updateMatrix()})),this._createDefaultTextureSet(),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.backfaces=t.backfaces}_meshMatrixDirty(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}_createDefaultTextureSet(){const e=new IA({id:"defaultColorTexture",texture:new Cs({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new IA({id:"defaultMetalRoughTexture",texture:new Cs({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new IA({id:"defaultNormalsTexture",texture:new Cs({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),s=new IA({id:"defaultEmissiveTexture",texture:new Cs({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new IA({id:"defaultOcclusionTexture",texture:new Cs({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=s,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new FA({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:s,occlusionTexture:r})}get isPerformanceModel(){return!0}get transforms(){return this._transforms}get textures(){return this._textures}get textureSets(){return this._textureSets}get meshes(){return this._meshes}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),c.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),c.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||ch),c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),c.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),c.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get matrix(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),c.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),c.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}get rotationMatrixConjugate(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0,this._aabbDirty=!0}_transformDirty(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}_sceneModelDirty(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(let e=0,t=this._entityList.length;e0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,i=this._entityList.length;t0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._entityList.length;t0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._entityList.length;t0}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._entityList.length;t0}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._entityList.length;t0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._entityList.length;t0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,i=new Uint8Array(t.length);for(let e=0,s=t.length;e{l.setImage(A,{minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a}),this.glRedraw()},A.src=e.src;break;default:this._textureTranscoder?_.loadArraybuffer(e.src,(e=>{e.byteLength?this._textureTranscoder.transcode([e],l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'src': file data is zero length")}),(function(e){this.error(`[createTexture] Can't create texture from 'src': ${e}`)})):this.error(`[createTexture] Can't create texture from 'src' - SceneModel needs to be configured with a TextureTranscoder for this file type ('${t}')`)}}else e.buffers&&(this._textureTranscoder?this._textureTranscoder.transcode(e.buffers,l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'buffers' - SceneModel needs to be configured with a TextureTranscoder for this option"));this._textures[t]=new IA({id:t,texture:l})}createTextureSet(e){const t=e.id;if(null==t)return void this.error("[createTextureSet] Config missing: id");if(this._textureSets[t])return void this.error(`[createTextureSet] Texture set already created: ${t}`);let i,s,r,o,n;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(i=this._textures[e.colorTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.colorTextureId} - ensure that you create it first with createTexture()`)}else i=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(s=this._textures[e.metallicRoughnessTextureId],!s)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else s=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(r=this._textures[e.normalsTextureId],!r)return void this.error(`[createTextureSet] Texture not found: ${e.normalsTextureId} - ensure that you create it first with createTexture()`)}else r=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(o=this._textures[e.emissiveTextureId],!o)return void this.error(`[createTextureSet] Texture not found: ${e.emissiveTextureId} - ensure that you create it first with createTexture()`)}else o=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(n=this._textures[e.occlusionTextureId],!n)return void this.error(`[createTextureSet] Texture not found: ${e.occlusionTextureId} - ensure that you create it first with createTexture()`)}else n=this._textures.defaultOcclusionTexture;const a=new FA({id:t,model:this,colorTexture:i,alphaCutoff:e.alphaCutoff,metallicRoughnessTexture:s,normalsTexture:r,emissiveTexture:o,occlusionTexture:n});return this._textureSets[t]=a,a}createTransform(e){if(void 0===e.id||null===e.id)return void this.error("[createTransform] SceneModel.createTransform() config missing: id");if(this._transforms[e.id])return void this.error(`[createTransform] SceneModel already has a transform with this ID: ${e.id}`);let t;if(e.parentTransformId&&(t=this._transforms[e.parentTransformId],!t))return void this.error("[createTransform] SceneModel.createTransform() config missing: id");const i=new rh({id:e.id,model:this,parent:t,matrix:e.matrix,position:e.position,scale:e.scale,rotation:e.rotation,quaternion:e.quaternion});return this._transforms[i.id]=i,i}createMesh(e){if(void 0===e.id||null===e.id)return this.error("[createMesh] SceneModel.createMesh() config missing: id"),!1;if(this._meshes[e.id])return this.error(`[createMesh] SceneModel already has a mesh with this ID: ${e.id}`),!1;if(!(void 0!==e.geometryId)){if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"!==e.primitive&&"lines"!==e.primitive&&"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)return this.error(`Unsupported value for 'primitive': '${primitive}' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.`),!1;if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),!1;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),!1;if(!(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){const t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return e.indices=this._createDefaultIndices(numIndices),this.error(`Param expected: indices (required for '${e.primitive}' primitive type)`),!1;if((e.matrix||e.position||e.rotation||e.scale)&&(e.positionsCompressed||e.positionsDecodeBoundary))return this.error("Unexpected params: 'matrix', 'rotation', 'scale', 'position' not allowed with 'positionsCompressed'"),!1;const t=!(!this._dtxEnabled||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||e.textureSetId);if(e.origin=e.origin?c.addVec3(this._origin,e.origin,c.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){const t=e.scale||lh,i=e.position||Ah;e.rotation?(c.eulerToQuaternion(e.rotation,"XYZ",ah),e.meshMatrix=c.composeMat4(i,ah,t,c.mat4())):e.meshMatrix=c.composeMat4(i,e.quaternion||hh,t,c.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=io(e.positionsDecodeBoundary,c.mat4())),t){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):uh,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=c.vec3(),i=[];K(e.positions,i,t)&&(e.positions=i,e.origin=c.addVec3(e.origin,t,t))}if(e.positions){const t=c.collapseAABB3();e.positionsDecodeMatrix=c.mat4(),c.expandAABB3Points3(t,e.positions),e.positionsCompressed=to(e.positions,t,e.positionsDecodeMatrix),e.aabb=t}else if(e.positionsCompressed){const t=c.collapseAABB3();c.expandAABB3Points3(t,e.positionsCompressed),Vt.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.buckets){const t=c.collapseAABB3();for(let i=0,s=e.buckets.length;i>24&255,r=i>>16&255,o=i>>8&255,n=255&i;switch(e.pickColor=new Uint8Array([n,o,r,s]),e.solid="solid"===e.primitive,t.origin=c.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),t.numPrimitives=e.numPrimitives,this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}_getNumPrimitives(e){let t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i>>0).toString(16)}_getVBOInstancingLayer(e){const t=this,i=e.origin,s=e.textureSetId||"-",r=e.geometryId,o=`${Math.round(i[0])}.${Math.round(i[1])}.${Math.round(i[2])}.${s}.${r}`;let n=this._vboInstancingLayers[o];if(n)return n;let a=e.textureSet;const l=e.geometry;for(;!n;)switch(l.primitive){case"triangles":case"surface":n=new ln({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":n=new ln({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":n=new Kn({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":n=new Na({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[o]=n,this.layerList.push(n),this._layersToFinalize.push(n),n}createEntity(e){if(void 0===e.id?e.id=c.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=c.createUUID()),void 0===e.meshIds)return void this.error("Config missing: meshIds");let t=0;return this._visible&&!1!==e.visible&&(t|=J),this._pickable&&!1!==e.pickable&&(t|=Z),this._culled&&!1!==e.culled&&(t|=Y),this._clippable&&!1!==e.clippable&&(t|=q),this._collidable&&!1!==e.collidable&&(t|=$),this._edges&&!1!==e.edges&&(t|=se),this._xrayed&&!1!==e.xrayed&&(t|=ee),this._highlighted&&!1!==e.highlighted&&(t|=te),this._selected&&!1!==e.selected&&(t|=ie),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];for(let i=0,s=e.meshIds.length;ie.sortIdt.sortId?1:0));for(let e=0,t=this.layerList.length;e0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}_updateRenderFlagsVisibleLayers(){const e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(let t=0,i=this.layerList.length;t0){const t=`${this.id}-${c.createUUID()}`;this.warn(`Creating dummy SceneModelEntity "${t}" for unused SceneMeshes: [${e.join(",")}]`),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}_getActiveSectionPlanesForLayer(e){const t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,s=i.length,r=e.layerIndex*s;if(s>0)for(let e=0;e0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0){this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions0&&(e.edgesTransparent=!0))}if(this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){const t=this.scene.highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}drawColorOpaque(e,t){const i=this.renderFlags;for(let t=0,s=i.visibleLayers.length;t65536?16:8)}else n=[{positionsCompressed:s,indices:r,edgeIndices:o}];return n}class fh extends D{constructor(e,t={}){if(super(e,t),this._positions=t.positions||[],t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;e{var r=e-i,o=t-s;return Math.sqrt(r*r+o*o)};class Mh extends D{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var i=this.plugin.viewer.scene;this._originWorld=c.vec3(),this._targetWorld=c.vec3(),this._wp=new Float64Array(24),this._vp=new Float64Array(24),this._pp=new Float64Array(24),this._cp=new Float64Array(8),this._xAxisLabelCulled=!1,this._yAxisLabelCulled=!1,this._zAxisLabelCulled=!1,this._color=t.color||this.plugin.defaultColor;const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))},l=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new ue(i,t.origin,this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._targetDot=new ue(i,t.target,this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthWire=new ge(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisWire=new ge(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisWire=new ge(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisWire=new ge(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthLabel=new me(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisLabel=new me(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisLabel=new me(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisLabel=new me(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._measurementOrientation="Horizontal",this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._sectionPlanesDirty=!0,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._useRotationAdjustment=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._xLabelEnabled=!1,this._yLabelEnabled=!1,this._zLabelEnabled=!1,this._lengthLabelEnabled=!1,this._labelsVisible=!1,this._labelsOnWires=!1,this._clickable=!1,this._originDot.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetDot.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=i.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=i.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=i.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.xLabelEnabled=t.xLabelEnabled,this.yLabelEnabled=t.yLabelEnabled,this.zLabelEnabled=t.zLabelEnabled,this.lengthLabelEnabled=t.lengthLabelEnabled,this.labelsVisible=t.labelsVisible,this.labelsOnWires=t.labelsOnWires,this._useRotationAdjustment=t.useRotationAdjustment,this._axesBasis=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}set axesBasis(e){this._axesBasis=e.slice(),this._wpDirty=!0,this._needUpdate(0)}get axesBasis(){return this._axesBasis}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty){const e=c.subVec3(this._targetWorld,this._originWorld,Ph);this._factors=c.transformVec3(this._axesBasis,e),this._measurementOrientation=function(e,t,i){return Math.abs(t[1]-e[1])>i?"Vertical":"Horizontal"}(this._originWorld,this._targetWorld,0),"Vertical"===this._measurementOrientation&&this._useRotationAdjustment?(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._originWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._originWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1):(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._originWorld[0]+this._axesBasis[0]*this._factors[0],this._wp[5]=this._originWorld[1]+this._axesBasis[4]*this._factors[0],this._wp[6]=this._originWorld[2]+this._axesBasis[8]*this._factors[0],this._wp[7]=1,this._wp[8]=this._originWorld[0]+this._axesBasis[0]*this._factors[0]+this._axesBasis[1]*this._factors[1],this._wp[9]=this._originWorld[1]+this._axesBasis[4]*this._factors[0]+this._axesBasis[5]*this._factors[1],this._wp[10]=this._originWorld[2]+this._axesBasis[8]*this._factors[0]+this._axesBasis[9]*this._factors[1],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1),this._wpDirty=!1,this._vpDirty=!0}if(this._vpDirty&&(c.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._originWorld)||this._isSliced(this._targetWorld))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}const t=this._originDot.viewPos[2],i=this._targetDot.viewPos[2];if(t>-.3||i>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){c.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var s=this._pp,r=this._cp,o=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var n=o.top-t.top,a=o.left-t.left,l=e.canvas.boundary,A=l[2],h=l[3],u=0;const i=this.plugin.viewer.scene.metrics,f=i.scale,g=i.units,m=i.unitsInfo[g].abbrev;for(var d=0,p=s.length;de.offsetTop+(e.offsetParent&&e.offsetParent!==s.parentNode&&h(e.offsetParent)),u=e=>e.offsetLeft+(e.offsetParent&&e.offsetParent!==s.parentNode&&u(e.offsetParent)),d=c.vec2(),p=e=>{const t=e.snappedCanvasPos||e.canvasPos;r=!0,o.set(e.worldPos),n.set(e.canvasPos),0===this._mouseState?(this._canvasToPagePos?(this._canvasToPagePos(s,t,d),this._markerDiv.style.left=d[0]-5+"px",this._markerDiv.style.top=d[1]-5+"px"):(this._markerDiv.style.left=u(s)+t[0]-5+"px",this._markerDiv.style.top=h(s)+t[1]-5+"px"),this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,this.pointerLens.snapped=!0),this._markerDiv.style.background="greenyellow",this._markerDiv.style.border="2px solid green"):(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red"),A=e.entity):(this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px"),s.style.cursor="pointer",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=this._currentDistanceMeasurementInitState.wireVisible,this._currentDistanceMeasurement.axisVisible=this._currentDistanceMeasurementInitState.axisVisible&&this.distanceMeasurementsPlugin.defaultAxisVisible,this._currentDistanceMeasurement.xAxisVisible=this._currentDistanceMeasurementInitState.xAxisVisible&&this.distanceMeasurementsPlugin.defaultXAxisVisible,this._currentDistanceMeasurement.yAxisVisible=this._currentDistanceMeasurementInitState.yAxisVisible&&this.distanceMeasurementsPlugin.defaultYAxisVisible,this._currentDistanceMeasurement.zAxisVisible=this._currentDistanceMeasurementInitState.zAxisVisible&&this.distanceMeasurementsPlugin.defaultZAxisVisible,this._currentDistanceMeasurement.targetVisible=this._currentDistanceMeasurementInitState.targetVisible,this._currentDistanceMeasurement.target.worldPos=o.slice(),this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px")};this._onHoverSnapOrSurface=i.on("hoverSnapOrSurface",(e=>{this._snapping&&p(e)})),this._onHoverSurface=i.on("hoverSurface",(e=>{this._snapping||p(e)})),s.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(a=e.clientX,l=e.clientY)}),s.addEventListener("mouseup",this._onMouseUp=t=>{1===t.which&&(t.clientX>a+20||t.clientXl+20||t.clientY{this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos),r=!1,this._markerDiv.style.left="-100px",this._markerDiv.style.top="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),s.style.cursor="default"};this._onHoverSnapOrSurfaceOff=i.on("hoverSnapOrSurfaceOff",(e=>{this._snapping&&f(e)})),this._onHoverOff=i.on("hoverOff",(e=>{this._snapping||f(e)})),this._active=!0}deactivate(){if(!this._active)return;this.fire("activated",!1),this.pointerLens&&(this.pointerLens.visible=!1),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onHoverSnapOrSurface),t.off(this._onHoverSurface),t.off(this._onHoverSnapOrSurfaceOff),t.off(this._onHoverOff),this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._mouseState=0)}get currentMeasurement(){return this._currentDistanceMeasurement}destroy(){this.deactivate(),super.destroy()}}class Ih extends D{constructor(e,t,i,s){const r=e.plugin.viewer;super(r.scene);const o=pe({viewer:r,handleMouseEvents:i,handleTouchEvents:s,pointerLens:t.pointerLens,dots:[e.origin,e.target],ray2WorldPos:(e,i,s)=>{const o=e=>{const t=r.scene.pick({canvasPos:s,snapToEdge:e,snapToVertex:e,pickSurface:!0});return t&&t.worldPos?t.worldPos:e&&o(!1)};return o(!!t.snapping)},onEnd:(e,t)=>{const i=!c.compareVec3(e,t.worldPos);return i&&this.fire("edited"),i}}),n=e.on("destroyed",o);this._deactivate=function(){e.off("destroyed",n),o()}}deactivate(){this._deactivate(),super.destroy()}}class Dh{constructor(e={}){this.cacheBuster=!1!==e.cacheBuster}_cacheBusterURL(e){if(!this.cacheBuster)return e;const t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}getMetaModel(e,t,i){_.loadJSON(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getGLTF(e,t,i){_.loadArraybuffer(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getGLB(e,t,i){_.loadArraybuffer(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getArrayBuffer(e,t,i,s){!function(e,t,i,s){var r=()=>{};i=i||r,s=s||r;const o=/^data:(.*?)(;base64)?,(.*)$/,n=t.match(o);if(n){const e=!!n[2];var a=n[3];a=window.decodeURIComponent(a),e&&(a=window.atob(a));try{const e=new ArrayBuffer(a.length),t=new Uint8Array(e);for(var l=0;l{i(e)}),(function(e){s(e)}))}}class Sh{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const i=this._messages[this._locale];if(!i)return null;const s=Th(e,i);return s?t?Rh(s,t):s:null}translatePlurals(e,t,i){const s=this._messages[this._locale];if(!s)return null;let r=Th(e,s);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=Rh(r,[t]),i&&(r=Rh(r,i)),r):null}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];if(s)for(const e in s)if(s.hasOwnProperty(e)){s[e].callback(t)}}on(t,i){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let s=this._eventSubs[t];s||(s={},this._eventSubs[t]=s);const r=this._eventSubIDMap.addItem();s[r]={callback:i},this._eventSubEvents[r]=t;const o=this._events[t];return void 0!==o&&i(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const i=this._eventSubs[t];i&&delete i[e],this._eventSubIDMap.removeItem(e)}}}function Th(e,t){if(t[e])return t[e];const i=e.split(".");let s=t;for(let e=0,t=i.length;s&&e1?1:e}get t(){return this._t}get tangent(){return this.getTangent(this._t)}get length(){var e=this._getLengths();return e[e.length-1]}getTangent(e){var t=1e-4;void 0===e&&(e=this._t);var i=e-t,s=e+t;i<0&&(i=0),s>1&&(s=1);var r=this.getPoint(i),o=this.getPoint(s),n=c.subVec3(o,r,[]);return c.normalizeVec3(n,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,i=[];for(t=0;t<=e;t++)i.push(this.getPoint(t/e));return i}_getLengths(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,i,s=[],r=this.getPoint(0),o=0;for(s.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),o+=c.lenVec3(c.subVec3(t,r,[])),s.push(o),r=t;return this.cacheArcLengths=s,s}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var i,s=this._getLengths(),r=0,o=s.length;i=t||e*s[o-1];for(var n,a=0,l=o-1;a<=l;)if((n=s[r=Math.floor(a+(l-a)/2)]-i)<0)a=r+1;else{if(!(n>0)){l=r;break}l=r-1}if(s[r=l]===i)return r/(o-1);var A=s[r];return(r+(i-A)/(s[r+1]-A))/(o-1)}}class Uh extends Lh{constructor(e,t={}){super(e,t),this.points=t.points,this.t=t.t}set points(e){this._points=e||[]}get points(){return this._points}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=this.points;if(!(t.length<3)){var i=(t.length-1)*e,s=Math.floor(i),r=i-s,o=t[0===s?s:s-1],n=t[s],a=t[s>t.length-2?t.length-1:s+1],l=t[s>t.length-3?t.length-1:s+2],A=c.vec3();return A[0]=c.catmullRomInterpolate(o[0],n[0],a[0],l[0],r),A[1]=c.catmullRomInterpolate(o[1],n[1],a[1],l[1],r),A[2]=c.catmullRomInterpolate(o[2],n[2],a[2],l[2],r),A}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}getJSON(){return{points:points,t:this._t}}}const kh=c.vec3();const Oh=c.vec3(),Nh=c.vec3(),Qh=c.vec3(),Vh=c.vec3(),Hh=c.vec3();class jh extends D{get type(){return"CameraFlightAnimation"}constructor(e,t={}){super(e,t),this._look1=c.vec3(),this._eye1=c.vec3(),this._up1=c.vec3(),this._look2=c.vec3(),this._eye2=c.vec3(),this._up2=c.vec3(),this._orthoScale1=1,this._orthoScale2=1,this._flying=!1,this._flyEyeLookUp=!1,this._flyingEye=!1,this._flyingLook=!1,this._callback=null,this._callbackScope=null,this._time1=null,this._time2=null,this.easing=!1!==t.easing,this.duration=t.duration,this.fit=t.fit,this.fitFOV=t.fitFOV,this.trail=t.trail}flyTo(e,t,i){e=e||this.scene,this._flying&&this.stop(),this._flying=!1,this._flyingEye=!1,this._flyingLook=!1,this._flyingEyeLookUp=!1,this._callback=t,this._callbackScope=i;const s=this.scene.camera,r=!!e.projection&&e.projection!==s.projection;let o,n,a,l,A;if(this._eye1[0]=s.eye[0],this._eye1[1]=s.eye[1],this._eye1[2]=s.eye[2],this._look1[0]=s.look[0],this._look1[1]=s.look[1],this._look1[2]=s.look[2],this._up1[0]=s.up[0],this._up1[1]=s.up[1],this._up1[2]=s.up[2],this._orthoScale1=s.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)o=e.aabb;else if(6===e.length)o=e;else if(e.eye&&e.look||e.up)n=e.eye,a=e.look,l=e.up;else if(e.eye)n=e.eye;else if(e.look)a=e.look;else{let s=e;if((_.isNumeric(s)||_.isString(s))&&(A=s,s=this.scene.components[A],!s))return this.error("Component not found: "+_.inQuotes(A)),void(t&&(i?t.call(i):t()));r||(o=s.aabb||this.scene.aabb)}const h=e.poi;if(o){if(o[3]=1;e>1&&(e=1);const i=this.easing?jh._ease(e,0,1,1):e,s=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(c.subVec3(s.eye,s.look,Hh),s.eye=c.lerpVec3(i,0,1,this._eye1,this._eye2,Qh),s.look=c.subVec3(Qh,Hh,Nh)):this._flyingLook&&(s.look=c.lerpVec3(i,0,1,this._look1,this._look2,Nh),s.up=c.lerpVec3(i,0,1,this._up1,this._up2,Vh)):this._flyingEyeLookUp&&(s.eye=c.lerpVec3(i,0,1,this._eye1,this._eye2,Qh),s.look=c.lerpVec3(i,0,1,this._look1,this._look2,Nh),s.up=c.lerpVec3(i,0,1,this._up1,this._up2,Vh)),this._projection2){const t="ortho"===this._projection2?jh._easeOutExpo(e,0,1,1):jh._easeInCubic(e,0,1,1);s.customProjection.matrix=c.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else s.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return s.ortho.scale=this._orthoScale2,void this.stop();M.scheduleTask(this._update,this)}static _ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}static _easeInCubic(e,t,i,s){return i*(e/=s)*e*e+t}static _easeOutExpo(e,t,i,s){return i*(1-Math.pow(2,-10*e/s))+t}stop(){if(!this._flying)return;this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);const e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}cancel(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}set duration(e){this._duration=e?1e3*e:500,this.stop()}get duration(){return this._duration/1e3}set fit(e){this._fit=!1!==e}get fit(){return this._fit}set fitFOV(e){this._fitFOV=e||45}get fitFOV(){return this._fitFOV}set trail(e){this._trail=!!e}get trail(){return this._trail}destroy(){this.stop(),super.destroy()}}class Gh extends D{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new jh(this),this._t=0,this.state=Gh.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,i;const s=performance.now(),r=this._lastTime?.001*(s-this._lastTime):0;if(this._lastTime=s,0!==r)switch(this.state){case Gh.SCRUBBING:return;case Gh.PLAYING:if(this._t+=this._playingRate*r,t=this._cameraPath.frames.length,0===t||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=Gh.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case Gh.PLAYING_TO:i=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&i<=this._playingToT||this._playingDir>0&&i>=this._playingToT)&&(i=this._playingToT,this.state=Gh.SCRUBBING,this.fire("stopped")),this._t=i,e.loadFrame(this._t)}}_ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}set cameraPath(e){this._cameraPath=e}get cameraPath(){return this._cameraPath}set rate(e){this._playingRate=e}get rate(){return this._playingRate}play(){this._cameraPath&&(this._lastTime=null,this.state=Gh.PLAYING)}playToT(e){this._cameraPath&&(this._playingFromT=this._t,this._playingToT=e,this._playingDir=this._playingToT-this._playingFromT<0?-1:1,this._lastTime=null,this.state=Gh.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const i=t.frames[e];i?this.playToT(i.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const i=this._cameraPath;if(!i)return;const s=i.frames[e];s?(this.state=Gh.SCRUBBING,this._cameraFlightAnimation.flyTo(s,t)):this.error("flyToFrame - frame index out of range: "+e)}scrubToT(e){const t=this._cameraPath;if(!t)return;this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=Gh.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=Gh.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=Gh.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}Gh.STOPPED=0,Gh.SCRUBBING=1,Gh.PLAYING=2,Gh.PLAYING_TO=3;const zh=c.vec3(),Wh=c.vec3();c.vec3();const Kh=c.vec3([0,-1,0]),Xh=c.vec4([0,0,0,1]);function Jh(e){if(!Yh(e.width)||!Yh(e.height)){const t=document.createElement("canvas");t.width=Zh(e.width),t.height=Zh(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function Yh(e){return 0==(e&e-1)}function Zh(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class qh extends D{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const i=this.scene.canvas.gl;this._state=new lt({texture:new Cs({gl:i,target:i.TEXTURE_CUBE_MAP}),flipY:this._checkFlipY(t.minFilter),encoding:this._checkEncoding(t.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),this._src=t.src,this._images=[],this._loadSrc(t.src),p.memory.textures++}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}_loadSrc(e){const t=this,i=this.scene.canvas.gl;this._images=[];let s=!1,r=0;for(let o=0;o{r(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,r(),i.projection=s.projection)}}const ec=c.vec3();const tc=c.vec3();class ic{constructor(){this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsHasColorize=[],this.objectsOpacity=[],this.numObjects=0}saveObjects(e,t){this.numObjects=0,this._mask=t?_.apply(t,{}):null;const i=e.objects,s=!t||t.visible,r=!t||t.edges,o=!t||t.xrayed,n=!t||t.highlighted,a=!t||t.selected,l=!t||t.clippable,A=!t||t.pickable,h=!t||t.colorize,c=!t||t.opacity;for(let e in i)if(i.hasOwnProperty(e)){const t=i[e],u=this.numObjects;if(s&&(this.objectsVisible[u]=t.visible),r&&(this.objectsEdges[u]=t.edges),o&&(this.objectsXrayed[u]=t.xrayed),n&&(this.objectsHighlighted[u]=t.highlighted),a&&(this.objectsSelected[u]=t.selected),l&&(this.objectsClippable[u]=t.clippable),A&&(this.objectsPickable[u]=t.pickable),h){const e=t.colorize;e?(this.objectsColorize[3*u+0]=e[0],this.objectsColorize[3*u+1]=e[1],this.objectsColorize[3*u+2]=e[2],this.objectsHasColorize[u]=!0):this.objectsHasColorize[u]=!1}c&&(this.objectsOpacity[u]=t.opacity),this.numObjects++}}restoreObjects(e){const t=this._mask,i=!t||t.visible,s=!t||t.edges,r=!t||t.xrayed,o=!t||t.highlighted,n=!t||t.selected,a=!t||t.clippable,l=!t||t.pickable,A=!t||t.colorize,h=!t||t.opacity;var c=0;const u=e.objects;for(let e in u)if(u.hasOwnProperty(e)){const t=u[e];i&&(t.visible=this.objectsVisible[c]),s&&(t.edges=this.objectsEdges[c]),r&&(t.xrayed=this.objectsXrayed[c]),o&&(t.highlighted=this.objectsHighlighted[c]),n&&(t.selected=this.objectsSelected[c]),a&&(t.clippable=this.objectsClippable[c]),l&&(t.pickable=this.objectsPickable[c]),A&&(this.objectsHasColorize[c]?(tc[0]=this.objectsColorize[3*c+0],tc[1]=this.objectsColorize[3*c+1],tc[2]=this.objectsColorize[3*c+2],t.colorize=tc):t.colorize=null),h&&(t.opacity=this.objectsOpacity[c]),c++}}}class sc extends D{constructor(e,t={}){super(e,t),this._skyboxMesh=new es(this,{geometry:new Gt(this,{primitive:"triangles",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]}),background:!0,scale:[2e3,2e3,2e3],rotation:[0,-90,0],material:new Jt(this,{ambient:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],emissive:[1,1,1],emissiveMap:new Ss(this,{src:t.src,flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge",encoding:t.encoding||"sRGB"}),backfaces:!0}),visible:!1,pickable:!1,clippable:!1,collidable:!1}),this.size=t.size,this.active=t.active}set size(e){this._size=e||1e3,this._skyboxMesh.scale=[this._size,this._size,this._size]}get size(){return this._size}set active(e){this._skyboxMesh.visible=e}get active(){return this._skyboxMesh.visible}}const rc=c.vec4(),oc=c.vec4(),nc=c.vec3(),ac=c.vec3(),lc=c.vec3(),Ac=c.vec4(),hc=c.vec4(),cc=c.vec4();class uc{constructor(e){this._scene=e}dollyToCanvasPos(e,t,i){let s=!1;const r=this._scene.camera;if(e){const t=c.subVec3(e,r.eye,nc);s=c.lenVec3(t){this._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(()=>{this._cameraDirty=!0})),this._onTick=this._scene.on("tick",(()=>{this.updatePivotElement(),this.updatePivotSphere()}))}createPivotSphere(){const e=this.getPivotPos(),t=c.vec3();c.decomposeMat4(c.inverseMat4(this._scene.viewer.camera.viewMatrix,c.mat4()),t,c.vec4(),c.vec3());const i=c.distVec3(t,e);let s=Math.tan(Math.PI/500)*i*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(s/=this._scene.camera.ortho.scale/2),W(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new Ls(this._scene,ss({radius:s})),this._pivotSphere=new es(this._scene,{geometry:this._pivotSphereGeometry,material:this._pivotSphereMaterial,pickable:!1,position:this._rtcPos,rtcCenter:this._rtcCenter})}destroyPivotSphere(){this._pivotSphere&&(this._pivotSphere.destroy(),this._pivotSphere=null),this._pivotSphereGeometry&&(this._pivotSphereGeometry.destroy(),this._pivotSphereGeometry=null)}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){c.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,c.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const i=t.boundary,s=i[2],r=i[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*s/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*r/2);let o=t._lastBoundingClientRect;if(!o||t._canvasSizeChanged){const e=t.canvas;o=t._lastBoundingClientRect=e.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(o.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(o.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}updatePivotSphere(){this._pivoting&&this._pivotSphere&&(W(this.getPivotPos(),this._rtcCenter,this._rtcPos),c.compareVec3(this._rtcPos,this._pivotSphere.position)||(this.destroyPivotSphere(),this.createPivotSphere()))}setPivotElement(e){this._pivotElement=e}enablePivotSphere(e={}){this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);const t=e.color||[1,0,0];this._pivotSphereMaterial=new Jt(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}disablePivotSphere(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}startPivot(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;const e=this._scene.camera;let t=c.lookAtMat4v(e.eye,e.look,e.worldUp);c.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const i=this.getPivotPos();this._cameraOffset[2]+=c.distVec3(e.eye,i),t=c.inverseMat4(t);const s=c.transformVec3(t,this._cameraOffset),r=c.vec3();if(c.subVec3(e.eye,i,r),c.addVec3(r,s),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=c.lenVec3(r),this._polar=Math.acos(r[1]/this._radius),this._azimuth=Math.atan2(r[0],r[2]),this._pivoting=!0}_cameraLookingDownwards(){const e=this._scene.camera,t=c.normalizeVec3(c.subVec3(e.look,e.eye,dc)),i=c.cross3Vec3(t,e.worldUp,pc);return c.sqLenVec3(i)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}setCanvasPivotPos(e){const t=this._scene.camera,i=Math.abs(c.distVec3(this._scene.center,t.eye)),s=t.project.transposedMatrix,r=s.subarray(8,12),o=s.subarray(12),n=[0,0,-1,1],a=c.dotVec4(n,r)/c.dotVec4(n,o),l=gc;t.project.unproject(e,a,mc,_c,l);const A=c.normalizeVec3(c.subVec3(l,t.eye,dc)),h=c.addVec3(t.eye,c.mulVec3Scalar(A,i,pc),fc);this.setPivotPos(h)}getPivotPos(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const i=this._scene.camera;var s=-e;const r=-t;1===i.worldUp[2]&&(s=-s),this._azimuth+=.01*-s,this._polar+=.01*r,this._polar=c.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 n=c.lenVec3(c.subVec3(i.look,i.eye,c.vec3())),a=this.getPivotPos();c.addVec3(o,a);let l=c.lookAtMat4v(o,a,i.worldUp);l=c.inverseMat4(l);const A=c.transformVec3(l,this._cameraOffset);l[12]-=A[0],l[13]-=A[1],l[14]-=A[2];const h=[l[8],l[9],l[10]];i.eye=[l[12],l[13],l[14]],c.subVec3(i.eye,c.mulVec3Scalar(h,n),i.look),i.up=[l[4],l[5],l[6]],this.showPivot()}showPivot(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}hidePivot(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}endPivot(){this._pivoting=!1}destroy(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}class bc{constructor(e,t){this._scene=e.scene,this._cameraControl=e,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=t,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=c.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;const e=`${~~this.pickCursorPos[0]}-${~~this.pickCursorPos[1]}-${this.scheduleSnapOrPick}-${this.schedulePickSurface}-${this.schedulePickEntity}`;if(this._lastHash===e)return;this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;const t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){const e=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});e&&(e.snappedToEdge||e.snappedToVertex)?(this.snapPickResult=e,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const e=this.pickResult.canvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){const e=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){const e=new Re;e.entity=this.snapPickResult.entity,e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){const e=this.pickResult.entity.id;this._lastPickedEntityId!==e&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=e)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}const yc=c.vec2();class xc{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController;let n,a,l,A=0,h=0,u=0,d=0,p=!1;const f=c.vec3();let g=!0;const m=this._scene.canvas.canvas,_=[];function v(e=!0){m.style.cursor="move",A=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],u=s.pointerCanvasPos[0],d=s.pointerCanvasPos[1],e&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(p=!0,f.set(o.pickResult.worldPos)):p=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!1}),m.addEventListener("mousedown",this._mouseDownHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:_[e.input.KEY_SHIFT]||i.planView?(n=!0,v()):(n=!0,v(!1));break;case 2:a=!0,v();break;case 3:l=!0,i.panRightClick&&v()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(!n&&!a&&!l)return;const o=e.canvas.boundary,u=o[2],d=o[3],g=s.pointerCanvasPos[0],m=s.pointerCanvasPos[1],v=_[e.input.KEY_SHIFT]||i.planView||!i.panRightClick&&a||i.panRightClick&&l,b=document.pointerLockElement?t.movementX:g-A,y=document.pointerLockElement?t.movementY:m-h;if(v){const t=e.camera;if("perspective"===t.projection){const i=Math.abs(p?c.lenVec3(c.subVec3(f,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(t.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*b*i/d,r.panDeltaY+=1.5*y*i/d}else r.panDeltaX+=.5*t.ortho.scale*(b/d),r.panDeltaY+=.5*t.ortho.scale*(y/d)}else!n||a||l||i.planView||(i.firstPerson?(r.rotateDeltaY-=b/u*i.dragRotationRate/2,r.rotateDeltaX+=y/d*(i.dragRotationRate/4)):(r.rotateDeltaY-=b/u*(1.5*i.dragRotationRate),r.rotateDeltaX+=y/d*(1.5*i.dragRotationRate)));A=g,h=m}),m.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{i.active&&i.pointerEnabled&&s.mouseover&&(g=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{if(i.active&&i.pointerEnabled)switch(e.which){case 1:case 2:case 3:n=!1,a=!1,l=!1}}),m.addEventListener("mouseup",this._mouseUpHandler=e=>{if(i.active&&i.pointerEnabled){if(3===e.which){!function(e,t){if(e){let i=e.target,s=0,r=0,o=0,n=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,o+=i.scrollLeft,n+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+o-s,t[1]=e.pageY+n-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,yc);const i=yc[0],s=yc[1];Math.abs(i-u)<3&&Math.abs(s-d)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:yc,event:e},!0)}m.style.removeProperty("cursor")}}),m.addEventListener("mouseenter",this._mouseEnterHandler=()=>{i.active&&i.pointerEnabled});const b=1/60;let y=null;m.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!(i.active&&i.pointerEnabled&&i.zoomOnMouseWheel))return;const t=performance.now()/1e3;var o=null!==y?t-y:0;y=t,o>.05&&(o=.05),o{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover)return;const n=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),a=r._isKeyDownForAction(r.AXIS_VIEW_BACK),l=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),A=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),h=r._isKeyDownForAction(r.AXIS_VIEW_TOP),u=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(n||a||l||A||h||u))return;const d=e.aabb,p=c.getAABB3Diag(d);c.getAABB3Center(d,Bc);const f=Math.abs(p/Math.tan(t.cameraFlight.fitFOV*c.DEGTORAD)),g=1.1*p;Ec.orthoScale=g,n?(Ec.eye.set(c.addVec3(Bc,c.mulVec3Scalar(o.worldRight,f,wc),Mc)),Ec.look.set(Bc),Ec.up.set(o.worldUp)):a?(Ec.eye.set(c.addVec3(Bc,c.mulVec3Scalar(o.worldForward,f,wc),Mc)),Ec.look.set(Bc),Ec.up.set(o.worldUp)):l?(Ec.eye.set(c.addVec3(Bc,c.mulVec3Scalar(o.worldRight,-f,wc),Mc)),Ec.look.set(Bc),Ec.up.set(o.worldUp)):A?(Ec.eye.set(c.addVec3(Bc,c.mulVec3Scalar(o.worldForward,-f,wc),Mc)),Ec.look.set(Bc),Ec.up.set(o.worldUp)):h?(Ec.eye.set(c.addVec3(Bc,c.mulVec3Scalar(o.worldUp,f,wc),Mc)),Ec.look.set(Bc),Ec.up.set(c.normalizeVec3(c.mulVec3Scalar(o.worldForward,1,Pc),Cc))):u&&(Ec.eye.set(c.addVec3(Bc,c.mulVec3Scalar(o.worldUp,-f,wc),Mc)),Ec.look.set(Bc),Ec.up.set(c.normalizeVec3(c.mulVec3Scalar(o.worldForward,-1,Pc)))),!i.firstPerson&&i.followPointer&&t.pivotController.setPivotPos(Bc),t.cameraFlight.duration>0?t.cameraFlight.flyTo(Ec,(()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(Ec),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class Ic{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;let l=!1,A=!1;const h=this._scene.canvas.canvas,u=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i&&i.entity?i.entity.aabb:e.aabb;if(s){const i=e.camera;c.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})},d=e.tickify(this._canvasMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(l||A)return;if(a.hasSubs("rayMove")){const t=c.vec3(),i=c.vec3();c.canvasPosToWorldRay(e.canvas.canvas,e.camera.viewMatrix,e.camera.projMatrix,e.camera.projection,s.pointerCanvasPos,t,i),a.fire("rayMove",{canvasPos:s.pointerCanvasPos,ray:{origin:t,direction:i,canvasPos:s.pointerCanvasPos}},!0)}const r=a.hasSubs("hover"),n=a.hasSubs("hoverEnter"),h=a.hasSubs("hoverOut"),u=a.hasSubs("hoverOff"),d=a.hasSubs("hoverSurface"),p=a.hasSubs("hoverSnapOrSurface");if(r||n||h||u||d||p)if(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=d,o.scheduleSnapOrPick=p,o.update(),o.pickResult){if(o.pickResult.entity){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),a.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t)}a.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&a.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),a.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)});h.addEventListener("mousemove",d),h.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(l=!0),3===t.which&&(A=!0);if(1===t.which&&i.active&&i.pointerEnabled&&(s.mouseDownClientX=t.clientX,s.mouseDownClientY=t.clientY,s.mouseDownCursorX=s.pointerCanvasPos[0],s.mouseDownCursorY=s.pointerCanvasPos[1],!i.firstPerson&&i.followPointer&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===t.which))){const t=o.pickResult;t&&t.worldPos?(n.setPivotPos(t.worldPos),n.startPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),n.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(l=!1),3===e.which&&(A=!1),n.getPivoting()&&n.endPivot()}),h.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!i.active||!i.pointerEnabled)return;if(!(1===r.which))return;if(n.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const l=a.hasSubs("picked"),A=a.hasSubs("pickedNothing"),h=a.hasSubs("pickedSurface"),d=a.hasSubs("doublePicked"),p=a.hasSubs("doublePickedSurface"),f=a.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||d||p||f))return(l||A||h)&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=h,o.update(),o.pickResult?(a.fire("picked",o.pickResult,!0),o.pickedSurface&&a.fire("pickedSurface",o.pickResult,!0)):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=h,o.update();const e=o.pickResult,r=o.pickedSurface;this._timeout=setTimeout((()=>{e&&e.worldPos?(a.fire("picked",e,!0),r&&(a.fire("pickedSurface",e,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),this._clicks=0}),i.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo||d||p,o.schedulePickSurface=o.schedulePickEntity&&p,o.update(),o.pickResult){if(a.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&a.fire("doublePickedSurface",o.pickResult,!0),i.doublePickFlyTo&&(u(o.pickResult),!i.firstPerson&&i.followPointer)){const e=o.pickResult.entity.aabb,i=c.getAABB3Center(e);t.pivotController.setPivotPos(i),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(a.fire("doublePickedNothing",{canvasPos:s.pointerCanvasPos},!0),i.doublePickFlyTo&&(u(),!i.firstPerson&&i.followPointer)){const i=e.aabb,s=c.getAABB3Center(i);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}this._clicks=0}},!1)}reset(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}class Dc{constructor(e,t,i,s,r){this._scene=e;const o=e.input,n=[],a=e.canvas.canvas;let l=!0;this._onSceneMouseMove=o.on("mousemove",(()=>{l=!0})),this._onSceneKeyDown=o.on("keydown",(t=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover||(n[t]=!0,t===o.KEY_SHIFT&&(a.style.cursor="move")))})),this._onSceneKeyUp=o.on("keyup",(s=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(n[s]=!1,s===o.KEY_SHIFT&&(a.style.cursor=null),t.pivotController.getPivoting()&&t.pivotController.endPivot())})),this._onTick=e.on("tick",(a=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover)return;const A=t.cameraControl,h=a.deltaTime/1e3;if(!i.planView){const e=A._isKeyDownForAction(A.ROTATE_Y_POS,n),s=A._isKeyDownForAction(A.ROTATE_Y_NEG,n),o=A._isKeyDownForAction(A.ROTATE_X_POS,n),a=A._isKeyDownForAction(A.ROTATE_X_NEG,n),l=h*i.keyboardRotationRate;(e||s||o||a)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:s&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:a&&(r.rotateDeltaX-=l),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!n[o.KEY_CTRL]&&!n[o.KEY_ALT]){const e=A._isKeyDownForAction(A.DOLLY_BACKWARDS,n),o=A._isKeyDownForAction(A.DOLLY_FORWARDS,n);if(e||o){const n=h*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=n:e&&(r.dollyDelta+=n),l&&(s.followPointerDirty=!0,l=!1)}}const c=A._isKeyDownForAction(A.PAN_FORWARDS,n),u=A._isKeyDownForAction(A.PAN_BACKWARDS,n),d=A._isKeyDownForAction(A.PAN_LEFT,n),p=A._isKeyDownForAction(A.PAN_RIGHT,n),f=A._isKeyDownForAction(A.PAN_UP,n),g=A._isKeyDownForAction(A.PAN_DOWN,n),m=(n[o.KEY_ALT]?.3:1)*h*i.keyboardPanRate;(c||u||d||p||f||g)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),g?r.panDeltaY+=m:f&&(r.panDeltaY+=-m),p?r.panDeltaX+=-m:d&&(r.panDeltaX+=m),u?r.panDeltaZ+=m:c&&(r.panDeltaZ+=-m))}))}reset(){}destroy(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),this._scene.input.off(this._onSceneKeyUp)}}const Sc=c.vec3();class Tc{constructor(e,t,i,s,r){this._scene=e;const o=e.camera,n=t.pickController,a=t.pivotController,l=t.panController;let A=1,h=1,u=null;this._onTick=e.on("tick",(()=>{if(!i.active||!i.pointerEnabled)return;let t="default";if(Math.abs(r.dollyDelta)<.001&&(r.dollyDelta=0),Math.abs(r.rotateDeltaX)<.001&&(r.rotateDeltaX=0),Math.abs(r.rotateDeltaY)<.001&&(r.rotateDeltaY=0),0===r.rotateDeltaX&&0===r.rotateDeltaY||(r.dollyDelta=0),i.followPointer){if(--A<=0&&(A=1,0!==r.dollyDelta)){if(0===r.rotateDeltaY&&0===r.rotateDeltaX&&i.followPointer&&s.followPointerDirty&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),n.pickResult&&n.pickResult.worldPos?u=n.pickResult.worldPos:(h=1,u=null),s.followPointerDirty=!1),u){const t=Math.abs(c.lenVec3(c.subVec3(u,e.camera.eye,Sc)));h=t/i.dollyProximityThreshold}h{s.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{s.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{Lc(e,o,s.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=e=>{i.active&&i.pointerEnabled&&(Lc(e,o,s.pointerCanvasPos),s.mouseover=!0)}),o.addEventListener("mouseup",this._mouseUpHandler=e=>{i.active&&i.pointerEnabled})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}function Lc(e,t,i){if(e){const{left:s,top:r}=t.getBoundingClientRect();i[0]=e.clientX-s,i[1]=e.clientY-r}else e=window.event,i[0]=e.x,i[1]=e.y;return i}const Uc=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 kc{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=c.vec2(),l=c.vec2(),A=c.vec2(),h=c.vec2(),u=[],d=this._scene.canvas.canvas;let p=0,f=!1;this._onTick=e.on("tick",(()=>{f=!1})),d.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!i.active||!i.pointerEnabled)return;t.preventDefault();const r=t.touches,l=t.changedTouches;for(s.touchStartTime=Date.now(),1===r.length&&1===l.length&&(Uc(r[0],a),i.followPointer&&(o.pickCursorPos=a,o.schedulePickSurface=!0,o.update(),i.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(n.setPivotPos(o.pickResult.worldPos),!i.firstPerson&&n.startPivot()&&n.showPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),!i.firstPerson&&n.startPivot()&&n.showPivot()))));u.length{n.getPivoting()&&n.endPivot()}),d.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const n=e.canvas.boundary,a=n[2],d=n[3],g=t.touches;if(t.touches.length===p){if(1===p){Uc(g[0],l),c.subVec2(l,u[0],h);const t=h[0],o=h[1];if(null!==s.longTouchTimeout&&(Math.abs(t)>i.longTapRadius||Math.abs(o)>i.longTapRadius)&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),i.planView){const s=e.camera;if("perspective"===s.projection){const n=Math.abs(e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*n/d*i.touchPanRate,r.panDeltaY+=o*n/d*i.touchPanRate}else r.panDeltaX+=.5*s.ortho.scale*(t/d)*i.touchPanRate,r.panDeltaY+=.5*s.ortho.scale*(o/d)*i.touchPanRate}else r.rotateDeltaY-=t/a*(1*i.dragRotationRate),r.rotateDeltaX+=o/d*(1.5*i.dragRotationRate)}else if(2===p){const t=g[0],n=g[1];Uc(t,l),Uc(n,A);const a=c.geometricMeanVec2(u[0],u[1]),h=c.geometricMeanVec2(l,A),p=c.vec2();c.subVec2(a,h,p);const f=p[0],m=p[1],_=e.camera,v=c.distVec2([t.pageX,t.pageY],[n.pageX,n.pageY]),b=(c.distVec2(u[0],u[1])-v)*i.touchDollyRate;if(r.dollyDelta=b,Math.abs(b)<1)if("perspective"===_.projection){const t=o.pickResult?o.pickResult.worldPos:e.center,s=Math.abs(c.lenVec3(c.subVec3(t,e.camera.eye,[])))*Math.tan(_.perspective.fov/2*Math.PI/180);r.panDeltaX-=f*s/d*i.touchPanRate,r.panDeltaY-=m*s/d*i.touchPanRate}else r.panDeltaX-=.5*_.ortho.scale*(f/d)*i.touchPanRate,r.panDeltaY-=.5*_.ortho.scale*(m/d)*i.touchPanRate;s.pointerCanvasPos=h}for(let e=0;e{let s;i&&i.worldPos&&(s=i.worldPos);const r=i?i.entity.aabb:e.aabb;if(s){const i=e.camera;c.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};d.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!i.active||!i.pointerEnabled)return;null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null);const r=e.touches,o=e.changedTouches;if(a=Date.now(),1===r.length&&1===o.length){h=a,Oc(r[0],A);const o=A[0],n=A[1],l=r[0].pageX,c=r[0].pageY;s.longTouchTimeout=setTimeout((()=>{t.cameraControl.fire("rightClick",{pagePos:[Math.round(l),Math.round(c)],canvasPos:[Math.round(o),Math.round(n)],event:e},!0),s.longTouchTimeout=null}),i.longTapTimeout)}else h=-1;for(;l.length{if(!i.active||!i.pointerEnabled)return;const t=Date.now(),r=e.touches,a=e.changedTouches,d=n.hasSubs("pickedSurface");null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),0===r.length&&1===a.length&&h>-1&&t-h<150&&(u>-1&&h-u<325?(Oc(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=d,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("doublePicked",o.pickResult),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult),i.doublePickFlyTo&&p(o.pickResult)):(n.fire("doublePickedNothing"),i.doublePickFlyTo&&p()),u=-1):c.distVec2(l[0],A)<4&&(Oc(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=d,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("picked",o.pickResult),o.pickedSurface&&n.fire("pickedSurface",o.pickResult)):n.fire("pickedNothing"),u=t),h=-1),l.length=r.length;for(let e=0,t=r.length;e{e.preventDefault()},this._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,zoomOnMouseWheel:!0,snapToVertex:true,snapToEdge:true,snapRadius:30,keyboardEnabledOnlyIfMouseover:!0,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},this._states={pointerCanvasPos:c.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:c.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const i=this.scene;this._controllers={cameraControl:this,pickController:new bc(this,this._configs),pivotController:new vc(i,this._configs),panController:new uc(i),cameraFlight:new jh(this,{duration:.5})},this._handlers=[new Rc(this.scene,this._controllers,this._configs,this._states,this._updates),new kc(this.scene,this._controllers,this._configs,this._states,this._updates),new xc(this.scene,this._controllers,this._configs,this._states,this._updates),new Fc(this.scene,this._controllers,this._configs,this._states,this._updates),new Ic(this.scene,this._controllers,this._configs,this._states,this._updates),new Nc(this.scene,this._controllers,this._configs,this._states,this._updates),new Dc(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new Tc(this.scene,this._controllers,this._configs,this._states,this._updates),this.navMode=t.navMode,t.planView&&(this.planView=t.planView),this.constrainVertical=t.constrainVertical,t.keyboardLayout?this.keyboardLayout=t.keyboardLayout:this.keyMap=t.keyMap,this.doublePickFlyTo=t.doublePickFlyTo,this.panRightClick=t.panRightClick,this.active=t.active,this.followPointer=t.followPointer,this.rotationInertia=t.rotationInertia,this.keyboardPanRate=t.keyboardPanRate,this.touchPanRate=t.touchPanRate,this.keyboardRotationRate=t.keyboardRotationRate,this.dragRotationRate=t.dragRotationRate,this.touchDollyRate=t.touchDollyRate,this.dollyInertia=t.dollyInertia,this.dollyProximityThreshold=t.dollyProximityThreshold,this.dollyMinSpeed=t.dollyMinSpeed,this.panInertia=t.panInertia,this.pointerEnabled=!0,this.keyboardDollyRate=t.keyboardDollyRate,this.mouseWheelDollyRate=t.mouseWheelDollyRate}set keyMap(e){if(e=e||"qwerty",_.isString(e)){const t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=i}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_isKeyDownForAction(e,t){const i=this._keyMap[e];if(!i)return!1;t||(t=this.scene.input.keyDown);for(let e=0,s=i.length;e0&&console.error(`[MetaModel._decompressProperties] Properties not found: ${i}`)}finalize(){if(this.finalized)throw"MetaScene already finalized - can't re-finalize";const e=this.metaScene;for(let t in e.metaObjects){const i=e.metaObjects[t];if(i.children&&(i.children=[]),i.propertySets&&(i.propertySets=[]),i.propertySetIds)for(let t=0,s=i.propertySetIds.length;t0?Wc(t):null,n=i&&i.length>0?Wc(i):null,a=e=>{if(!e)return;var t=!0;(n&&n[e.type]||o&&!o[e.type])&&(t=!1),t&&s.push(e.id);const i=e.children;if(i)for(var r=0,l=i.length;r>t;i.sort(KA);const s=new Int32Array(e.length);for(let t=0,r=i.length;te[t+1]){let i=e[t];e[t]=e[t+1],e[t+1]=i}XA=new Int32Array(e),t.sort(JA);const i=new Int32Array(e.length);for(let s=0,r=t.length;st){let i=e;e=t,t=i}function i(i,s){return i!==e?e-i:s!==t?t-s:0}let s=0,r=(o.length>>1)-1;for(;s<=r;){const e=r+s>>1,t=i(o[2*e],o[2*e+1]);if(t>0)s=e+1;else{if(!(t<0))return e;r=e-1}}return-s-1}const a=new Int32Array(o.length/2);a.fill(0);const l=s.length/3;if(l>8*(1<u.maxNumPositions&&(u=c()),u.bucketNumber>8)return[e];let p;-1===A[l]&&(A[l]=u.numPositions++,u.positionsCompressed.push(s[3*l]),u.positionsCompressed.push(s[3*l+1]),u.positionsCompressed.push(s[3*l+2])),-1===A[h]&&(A[h]=u.numPositions++,u.positionsCompressed.push(s[3*h]),u.positionsCompressed.push(s[3*h+1]),u.positionsCompressed.push(s[3*h+2])),-1===A[d]&&(A[d]=u.numPositions++,u.positionsCompressed.push(s[3*d]),u.positionsCompressed.push(s[3*d+1]),u.positionsCompressed.push(s[3*d+2])),u.indices.push(A[l]),u.indices.push(A[h]),u.indices.push(A[d]),(p=n(l,h))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(l,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(h,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]]))}const d=t/8*2,p=t/8,f=2*s.length+(r.length+o.length)*d;let g=0,m=-s.length/3;return h.forEach((e=>{g+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*p,m+=e.positionsCompressed.length/3})),g>f?[e]:(i&&function(e,t){const i={},s={};let r=0;e.forEach((e=>{const t=e.indices,o=e.edgeIndices,n=e.positionsCompressed;for(let e=0,s=t.length;e0){const e=t._meshes;for(let t=0,i=e.length;t0){const e=this._meshes;for(let t=0,i=e.length;t{this._viewMatrixDirty=!0})),this._meshesWithDirtyMatrices=[],this._numMeshesWithDirtyMatrices=0,this._onTick=this.scene.on("tick",(()=>{for(;this._numMeshesWithDirtyMatrices>0;)this._meshesWithDirtyMatrices[--this._numMeshesWithDirtyMatrices]._updateMatrix()})),this._createDefaultTextureSet(),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.backfaces=t.backfaces}_meshMatrixDirty(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}_createDefaultTextureSet(){const e=new IA({id:"defaultColorTexture",texture:new Cs({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new IA({id:"defaultMetalRoughTexture",texture:new Cs({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new IA({id:"defaultNormalsTexture",texture:new Cs({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),s=new IA({id:"defaultEmissiveTexture",texture:new Cs({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new IA({id:"defaultOcclusionTexture",texture:new Cs({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=s,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new FA({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:s,occlusionTexture:r})}get isPerformanceModel(){return!0}get transforms(){return this._transforms}get textures(){return this._textures}get textureSets(){return this._textureSets}get meshes(){return this._meshes}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),c.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),c.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||ch),c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),c.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),c.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get matrix(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),c.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),c.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}get rotationMatrixConjugate(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0,this._aabbDirty=!0}_transformDirty(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}_sceneModelDirty(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(let e=0,t=this._entityList.length;e0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,i=this._entityList.length;t0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._entityList.length;t0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._entityList.length;t0}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._entityList.length;t0}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._entityList.length;t0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._entityList.length;t0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,i=new Uint8Array(t.length);for(let e=0,s=t.length;e{l.setImage(A,{minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a}),this.glRedraw()},A.src=e.src;break;default:this._textureTranscoder?_.loadArraybuffer(e.src,(e=>{e.byteLength?this._textureTranscoder.transcode([e],l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'src': file data is zero length")}),(function(e){this.error(`[createTexture] Can't create texture from 'src': ${e}`)})):this.error(`[createTexture] Can't create texture from 'src' - SceneModel needs to be configured with a TextureTranscoder for this file type ('${t}')`)}}else e.buffers&&(this._textureTranscoder?this._textureTranscoder.transcode(e.buffers,l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'buffers' - SceneModel needs to be configured with a TextureTranscoder for this option"));this._textures[t]=new IA({id:t,texture:l})}createTextureSet(e){const t=e.id;if(null==t)return void this.error("[createTextureSet] Config missing: id");if(this._textureSets[t])return void this.error(`[createTextureSet] Texture set already created: ${t}`);let i,s,r,o,n;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(i=this._textures[e.colorTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.colorTextureId} - ensure that you create it first with createTexture()`)}else i=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(s=this._textures[e.metallicRoughnessTextureId],!s)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else s=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(r=this._textures[e.normalsTextureId],!r)return void this.error(`[createTextureSet] Texture not found: ${e.normalsTextureId} - ensure that you create it first with createTexture()`)}else r=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(o=this._textures[e.emissiveTextureId],!o)return void this.error(`[createTextureSet] Texture not found: ${e.emissiveTextureId} - ensure that you create it first with createTexture()`)}else o=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(n=this._textures[e.occlusionTextureId],!n)return void this.error(`[createTextureSet] Texture not found: ${e.occlusionTextureId} - ensure that you create it first with createTexture()`)}else n=this._textures.defaultOcclusionTexture;const a=new FA({id:t,model:this,colorTexture:i,alphaCutoff:e.alphaCutoff,metallicRoughnessTexture:s,normalsTexture:r,emissiveTexture:o,occlusionTexture:n});return this._textureSets[t]=a,a}createTransform(e){if(void 0===e.id||null===e.id)return void this.error("[createTransform] SceneModel.createTransform() config missing: id");if(this._transforms[e.id])return void this.error(`[createTransform] SceneModel already has a transform with this ID: ${e.id}`);let t;if(e.parentTransformId&&(t=this._transforms[e.parentTransformId],!t))return void this.error("[createTransform] SceneModel.createTransform() config missing: id");const i=new rh({id:e.id,model:this,parent:t,matrix:e.matrix,position:e.position,scale:e.scale,rotation:e.rotation,quaternion:e.quaternion});return this._transforms[i.id]=i,i}createMesh(e){if(void 0===e.id||null===e.id)return this.error("[createMesh] SceneModel.createMesh() config missing: id"),!1;if(this._meshes[e.id])return this.error(`[createMesh] SceneModel already has a mesh with this ID: ${e.id}`),!1;if(!(void 0!==e.geometryId)){if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"!==e.primitive&&"lines"!==e.primitive&&"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)return this.error(`Unsupported value for 'primitive': '${primitive}' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.`),!1;if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),!1;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),!1;if(!(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){const t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return e.indices=this._createDefaultIndices(numIndices),this.error(`Param expected: indices (required for '${e.primitive}' primitive type)`),!1;if((e.matrix||e.position||e.rotation||e.scale)&&(e.positionsCompressed||e.positionsDecodeBoundary))return this.error("Unexpected params: 'matrix', 'rotation', 'scale', 'position' not allowed with 'positionsCompressed'"),!1;const t=!(!this._dtxEnabled||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||e.textureSetId);if(e.origin=e.origin?c.addVec3(this._origin,e.origin,c.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){const t=e.scale||lh,i=e.position||Ah;e.rotation?(c.eulerToQuaternion(e.rotation,"XYZ",ah),e.meshMatrix=c.composeMat4(i,ah,t,c.mat4())):e.meshMatrix=c.composeMat4(i,e.quaternion||hh,t,c.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=io(e.positionsDecodeBoundary,c.mat4())),t){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):uh,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=c.vec3(),i=[];K(e.positions,i,t)&&(e.positions=i,e.origin=c.addVec3(e.origin,t,t))}if(e.positions){const t=c.collapseAABB3();e.positionsDecodeMatrix=c.mat4(),c.expandAABB3Points3(t,e.positions),e.positionsCompressed=to(e.positions,t,e.positionsDecodeMatrix),e.aabb=t}else if(e.positionsCompressed){const t=c.collapseAABB3();c.expandAABB3Points3(t,e.positionsCompressed),Vt.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.buckets){const t=c.collapseAABB3();for(let i=0,s=e.buckets.length;i>24&255,r=i>>16&255,o=i>>8&255,n=255&i;switch(e.pickColor=new Uint8Array([n,o,r,s]),e.solid="solid"===e.primitive,t.origin=c.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),t.numPrimitives=e.numPrimitives,this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}_getNumPrimitives(e){let t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i>>0).toString(16)}_getVBOInstancingLayer(e){const t=this,i=e.origin,s=e.textureSetId||"-",r=e.geometryId,o=`${Math.round(i[0])}.${Math.round(i[1])}.${Math.round(i[2])}.${s}.${r}`;let n=this._vboInstancingLayers[o];if(n)return n;let a=e.textureSet;const l=e.geometry;for(;!n;)switch(l.primitive){case"triangles":case"surface":n=new ln({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":n=new ln({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":n=new Kn({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":n=new Na({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[o]=n,this.layerList.push(n),this._layersToFinalize.push(n),n}createEntity(e){if(void 0===e.id?e.id=c.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=c.createUUID()),void 0===e.meshIds)return void this.error("Config missing: meshIds");let t=0;return this._visible&&!1!==e.visible&&(t|=J),this._pickable&&!1!==e.pickable&&(t|=Z),this._culled&&!1!==e.culled&&(t|=Y),this._clippable&&!1!==e.clippable&&(t|=q),this._collidable&&!1!==e.collidable&&(t|=$),this._edges&&!1!==e.edges&&(t|=se),this._xrayed&&!1!==e.xrayed&&(t|=ee),this._highlighted&&!1!==e.highlighted&&(t|=te),this._selected&&!1!==e.selected&&(t|=ie),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];for(let i=0,s=e.meshIds.length;ie.sortIdt.sortId?1:0));for(let e=0,t=this.layerList.length;e0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}_updateRenderFlagsVisibleLayers(){const e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(let t=0,i=this.layerList.length;t0){const t=`${this.id}-${c.createUUID()}`;this.warn(`Creating dummy SceneModelEntity "${t}" for unused SceneMeshes: [${e.join(",")}]`),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}_getActiveSectionPlanesForLayer(e){const t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,s=i.length,r=e.layerIndex*s;if(s>0)for(let e=0;e0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0){this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions0&&(e.edgesTransparent=!0))}if(this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){const t=this.scene.highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}drawColorOpaque(e,t){const i=this.renderFlags;for(let t=0,s=i.visibleLayers.length;t65536?16:8)}else n=[{positionsCompressed:s,indices:r,edgeIndices:o}];return n}class fh extends D{constructor(e,t={}){if(super(e,t),this._positions=t.positions||[],t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;e{var r=e-i,o=t-s;return Math.sqrt(r*r+o*o)};class Mh extends D{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var i=this.plugin.viewer.scene;this._originWorld=c.vec3(),this._targetWorld=c.vec3(),this._wp=new Float64Array(24),this._vp=new Float64Array(24),this._pp=new Float64Array(24),this._cp=new Float64Array(8),this._xAxisLabelCulled=!1,this._yAxisLabelCulled=!1,this._zAxisLabelCulled=!1,this._color=t.color||this.plugin.defaultColor;const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))},l=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new ue(i,t.origin,this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._targetDot=new ue(i,t.target,this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthWire=new ge(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisWire=new ge(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisWire=new ge(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisWire=new ge(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthLabel=new me(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisLabel=new me(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisLabel=new me(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisLabel=new me(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._measurementOrientation="Horizontal",this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._sectionPlanesDirty=!0,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._useRotationAdjustment=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._xLabelEnabled=!1,this._yLabelEnabled=!1,this._zLabelEnabled=!1,this._lengthLabelEnabled=!1,this._labelsVisible=!1,this._labelsOnWires=!1,this._clickable=!1,this._originDot.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetDot.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=i.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=i.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=i.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.xLabelEnabled=t.xLabelEnabled,this.yLabelEnabled=t.yLabelEnabled,this.zLabelEnabled=t.zLabelEnabled,this.lengthLabelEnabled=t.lengthLabelEnabled,this.labelsVisible=t.labelsVisible,this.labelsOnWires=t.labelsOnWires,this._useRotationAdjustment=t.useRotationAdjustment,this._axesBasis=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}set axesBasis(e){this._axesBasis=e.slice(),this._wpDirty=!0,this._needUpdate(0)}get axesBasis(){return this._axesBasis}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty){const e=c.subVec3(this._targetWorld,this._originWorld,Ph);this._factors=c.transformVec3(this._axesBasis,e),this._measurementOrientation=function(e,t,i){return Math.abs(t[1]-e[1])>i?"Vertical":"Horizontal"}(this._originWorld,this._targetWorld,0),"Vertical"===this._measurementOrientation&&this._useRotationAdjustment?(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._originWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._originWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1):(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._originWorld[0]+this._axesBasis[0]*this._factors[0],this._wp[5]=this._originWorld[1]+this._axesBasis[4]*this._factors[0],this._wp[6]=this._originWorld[2]+this._axesBasis[8]*this._factors[0],this._wp[7]=1,this._wp[8]=this._originWorld[0]+this._axesBasis[0]*this._factors[0]+this._axesBasis[1]*this._factors[1],this._wp[9]=this._originWorld[1]+this._axesBasis[4]*this._factors[0]+this._axesBasis[5]*this._factors[1],this._wp[10]=this._originWorld[2]+this._axesBasis[8]*this._factors[0]+this._axesBasis[9]*this._factors[1],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1),this._wpDirty=!1,this._vpDirty=!0}if(this._vpDirty&&(c.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._originWorld)||this._isSliced(this._targetWorld))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}const t=this._originDot.viewPos[2],i=this._targetDot.viewPos[2];if(t>-.3||i>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){c.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var s=this._pp,r=this._cp,o=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var n=o.top-t.top,a=o.left-t.left,l=e.canvas.boundary,A=l[2],h=l[3],u=0;const i=this.plugin.viewer.scene.metrics,f=i.scale,g=i.units,m=i.unitsInfo[g].abbrev;for(var d=0,p=s.length;de.offsetTop+(e.offsetParent&&e.offsetParent!==s.parentNode&&h(e.offsetParent)),u=e=>e.offsetLeft+(e.offsetParent&&e.offsetParent!==s.parentNode&&u(e.offsetParent)),d=c.vec2(),p=e=>{const t=e.snappedCanvasPos||e.canvasPos;r=!0,o.set(e.worldPos),n.set(e.canvasPos),0===this._mouseState?(this._canvasToPagePos?(this._canvasToPagePos(s,t,d),this._markerDiv.style.left=d[0]-5+"px",this._markerDiv.style.top=d[1]-5+"px"):(this._markerDiv.style.left=u(s)+t[0]-5+"px",this._markerDiv.style.top=h(s)+t[1]-5+"px"),this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,this.pointerLens.snapped=!0),this._markerDiv.style.background="greenyellow",this._markerDiv.style.border="2px solid green"):(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red"),A=e.entity):(this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px"),s.style.cursor="pointer",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=this._currentDistanceMeasurementInitState.wireVisible,this._currentDistanceMeasurement.axisVisible=this._currentDistanceMeasurementInitState.axisVisible&&this.distanceMeasurementsPlugin.defaultAxisVisible,this._currentDistanceMeasurement.xAxisVisible=this._currentDistanceMeasurementInitState.xAxisVisible&&this.distanceMeasurementsPlugin.defaultXAxisVisible,this._currentDistanceMeasurement.yAxisVisible=this._currentDistanceMeasurementInitState.yAxisVisible&&this.distanceMeasurementsPlugin.defaultYAxisVisible,this._currentDistanceMeasurement.zAxisVisible=this._currentDistanceMeasurementInitState.zAxisVisible&&this.distanceMeasurementsPlugin.defaultZAxisVisible,this._currentDistanceMeasurement.targetVisible=this._currentDistanceMeasurementInitState.targetVisible,this._currentDistanceMeasurement.target.worldPos=o.slice(),this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px")};this._onHoverSnapOrSurface=i.on("hoverSnapOrSurface",(e=>{this._snapping&&p(e)})),this._onHoverSurface=i.on("hoverSurface",(e=>{this._snapping||p(e)})),s.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(a=e.clientX,l=e.clientY)}),s.addEventListener("mouseup",this._onMouseUp=t=>{1===t.which&&(t.clientX>a+20||t.clientXl+20||t.clientY{this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos),r=!1,this._markerDiv.style.left="-100px",this._markerDiv.style.top="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),s.style.cursor="default"};this._onHoverSnapOrSurfaceOff=i.on("hoverSnapOrSurfaceOff",(e=>{this._snapping&&f(e)})),this._onHoverOff=i.on("hoverOff",(e=>{this._snapping||f(e)})),this._active=!0}deactivate(){if(!this._active)return;this.fire("activated",!1),this.pointerLens&&(this.pointerLens.visible=!1),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onHoverSnapOrSurface),t.off(this._onHoverSurface),t.off(this._onHoverSnapOrSurfaceOff),t.off(this._onHoverOff),this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._mouseState=0)}get currentMeasurement(){return this._currentDistanceMeasurement}destroy(){this.deactivate(),super.destroy()}}class Ih extends D{constructor(e,t,i,s){const r=e.plugin.viewer;super(r.scene);const o=pe({viewer:r,handleMouseEvents:i,handleTouchEvents:s,pointerLens:t.pointerLens,dots:[e.origin,e.target],ray2WorldPos:(e,i,s)=>{const o=e=>{const t=r.scene.pick({canvasPos:s,snapToEdge:e,snapToVertex:e,pickSurface:!0});return t&&t.worldPos?t.worldPos:e&&o(!1)};return o(!!t.snapping)},onEnd:(e,t)=>{const i=!c.compareVec3(e,t.worldPos);return i&&this.fire("edited"),i}}),n=e.on("destroyed",o);this._deactivate=function(){e.off("destroyed",n),o()}}deactivate(){this._deactivate(),super.destroy()}}class Dh{constructor(e={}){this.cacheBuster=!1!==e.cacheBuster}_cacheBusterURL(e){if(!this.cacheBuster)return e;const t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}getMetaModel(e,t,i){_.loadJSON(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getGLTF(e,t,i){_.loadArraybuffer(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getGLB(e,t,i){_.loadArraybuffer(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getArrayBuffer(e,t,i,s){!function(e,t,i,s){var r=()=>{};i=i||r,s=s||r;const o=/^data:(.*?)(;base64)?,(.*)$/,n=t.match(o);if(n){const e=!!n[2];var a=n[3];a=window.decodeURIComponent(a),e&&(a=window.atob(a));try{const e=new ArrayBuffer(a.length),t=new Uint8Array(e);for(var l=0;l{i(e)}),(function(e){s(e)}))}}class Sh{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const i=this._messages[this._locale];if(!i)return null;const s=Th(e,i);return s?t?Rh(s,t):s:null}translatePlurals(e,t,i){const s=this._messages[this._locale];if(!s)return null;let r=Th(e,s);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=Rh(r,[t]),i&&(r=Rh(r,i)),r):null}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];if(s)for(const e in s)if(s.hasOwnProperty(e)){s[e].callback(t)}}on(t,i){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let s=this._eventSubs[t];s||(s={},this._eventSubs[t]=s);const r=this._eventSubIDMap.addItem();s[r]={callback:i},this._eventSubEvents[r]=t;const o=this._events[t];return void 0!==o&&i(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const i=this._eventSubs[t];i&&delete i[e],this._eventSubIDMap.removeItem(e)}}}function Th(e,t){if(t[e])return t[e];const i=e.split(".");let s=t;for(let e=0,t=i.length;s&&e1?1:e}get t(){return this._t}get tangent(){return this.getTangent(this._t)}get length(){var e=this._getLengths();return e[e.length-1]}getTangent(e){var t=1e-4;void 0===e&&(e=this._t);var i=e-t,s=e+t;i<0&&(i=0),s>1&&(s=1);var r=this.getPoint(i),o=this.getPoint(s),n=c.subVec3(o,r,[]);return c.normalizeVec3(n,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,i=[];for(t=0;t<=e;t++)i.push(this.getPoint(t/e));return i}_getLengths(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,i,s=[],r=this.getPoint(0),o=0;for(s.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),o+=c.lenVec3(c.subVec3(t,r,[])),s.push(o),r=t;return this.cacheArcLengths=s,s}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var i,s=this._getLengths(),r=0,o=s.length;i=t||e*s[o-1];for(var n,a=0,l=o-1;a<=l;)if((n=s[r=Math.floor(a+(l-a)/2)]-i)<0)a=r+1;else{if(!(n>0)){l=r;break}l=r-1}if(s[r=l]===i)return r/(o-1);var A=s[r];return(r+(i-A)/(s[r+1]-A))/(o-1)}}class Uh extends Lh{constructor(e,t={}){super(e,t),this.points=t.points,this.t=t.t}set points(e){this._points=e||[]}get points(){return this._points}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=this.points;if(!(t.length<3)){var i=(t.length-1)*e,s=Math.floor(i),r=i-s,o=t[0===s?s:s-1],n=t[s],a=t[s>t.length-2?t.length-1:s+1],l=t[s>t.length-3?t.length-1:s+2],A=c.vec3();return A[0]=c.catmullRomInterpolate(o[0],n[0],a[0],l[0],r),A[1]=c.catmullRomInterpolate(o[1],n[1],a[1],l[1],r),A[2]=c.catmullRomInterpolate(o[2],n[2],a[2],l[2],r),A}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}getJSON(){return{points:points,t:this._t}}}const Oh=c.vec3();const kh=c.vec3(),Nh=c.vec3(),Qh=c.vec3(),Vh=c.vec3(),Hh=c.vec3();class jh extends D{get type(){return"CameraFlightAnimation"}constructor(e,t={}){super(e,t),this._look1=c.vec3(),this._eye1=c.vec3(),this._up1=c.vec3(),this._look2=c.vec3(),this._eye2=c.vec3(),this._up2=c.vec3(),this._orthoScale1=1,this._orthoScale2=1,this._flying=!1,this._flyEyeLookUp=!1,this._flyingEye=!1,this._flyingLook=!1,this._callback=null,this._callbackScope=null,this._time1=null,this._time2=null,this.easing=!1!==t.easing,this.duration=t.duration,this.fit=t.fit,this.fitFOV=t.fitFOV,this.trail=t.trail}flyTo(e,t,i){e=e||this.scene,this._flying&&this.stop(),this._flying=!1,this._flyingEye=!1,this._flyingLook=!1,this._flyingEyeLookUp=!1,this._callback=t,this._callbackScope=i;const s=this.scene.camera,r=!!e.projection&&e.projection!==s.projection;let o,n,a,l,A;if(this._eye1[0]=s.eye[0],this._eye1[1]=s.eye[1],this._eye1[2]=s.eye[2],this._look1[0]=s.look[0],this._look1[1]=s.look[1],this._look1[2]=s.look[2],this._up1[0]=s.up[0],this._up1[1]=s.up[1],this._up1[2]=s.up[2],this._orthoScale1=s.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)o=e.aabb;else if(6===e.length)o=e;else if(e.eye&&e.look||e.up)n=e.eye,a=e.look,l=e.up;else if(e.eye)n=e.eye;else if(e.look)a=e.look;else{let s=e;if((_.isNumeric(s)||_.isString(s))&&(A=s,s=this.scene.components[A],!s))return this.error("Component not found: "+_.inQuotes(A)),void(t&&(i?t.call(i):t()));r||(o=s.aabb||this.scene.aabb)}const h=e.poi;if(o){if(o[3]=1;e>1&&(e=1);const i=this.easing?jh._ease(e,0,1,1):e,s=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(c.subVec3(s.eye,s.look,Hh),s.eye=c.lerpVec3(i,0,1,this._eye1,this._eye2,Qh),s.look=c.subVec3(Qh,Hh,Nh)):this._flyingLook&&(s.look=c.lerpVec3(i,0,1,this._look1,this._look2,Nh),s.up=c.lerpVec3(i,0,1,this._up1,this._up2,Vh)):this._flyingEyeLookUp&&(s.eye=c.lerpVec3(i,0,1,this._eye1,this._eye2,Qh),s.look=c.lerpVec3(i,0,1,this._look1,this._look2,Nh),s.up=c.lerpVec3(i,0,1,this._up1,this._up2,Vh)),this._projection2){const t="ortho"===this._projection2?jh._easeOutExpo(e,0,1,1):jh._easeInCubic(e,0,1,1);s.customProjection.matrix=c.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else s.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return s.ortho.scale=this._orthoScale2,void this.stop();M.scheduleTask(this._update,this)}static _ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}static _easeInCubic(e,t,i,s){return i*(e/=s)*e*e+t}static _easeOutExpo(e,t,i,s){return i*(1-Math.pow(2,-10*e/s))+t}stop(){if(!this._flying)return;this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);const e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}cancel(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}set duration(e){this._duration=e?1e3*e:500,this.stop()}get duration(){return this._duration/1e3}set fit(e){this._fit=!1!==e}get fit(){return this._fit}set fitFOV(e){this._fitFOV=e||45}get fitFOV(){return this._fitFOV}set trail(e){this._trail=!!e}get trail(){return this._trail}destroy(){this.stop(),super.destroy()}}class Gh extends D{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new jh(this),this._t=0,this.state=Gh.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,i;const s=performance.now(),r=this._lastTime?.001*(s-this._lastTime):0;if(this._lastTime=s,0!==r)switch(this.state){case Gh.SCRUBBING:return;case Gh.PLAYING:if(this._t+=this._playingRate*r,t=this._cameraPath.frames.length,0===t||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=Gh.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case Gh.PLAYING_TO:i=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&i<=this._playingToT||this._playingDir>0&&i>=this._playingToT)&&(i=this._playingToT,this.state=Gh.SCRUBBING,this.fire("stopped")),this._t=i,e.loadFrame(this._t)}}_ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}set cameraPath(e){this._cameraPath=e}get cameraPath(){return this._cameraPath}set rate(e){this._playingRate=e}get rate(){return this._playingRate}play(){this._cameraPath&&(this._lastTime=null,this.state=Gh.PLAYING)}playToT(e){this._cameraPath&&(this._playingFromT=this._t,this._playingToT=e,this._playingDir=this._playingToT-this._playingFromT<0?-1:1,this._lastTime=null,this.state=Gh.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const i=t.frames[e];i?this.playToT(i.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const i=this._cameraPath;if(!i)return;const s=i.frames[e];s?(this.state=Gh.SCRUBBING,this._cameraFlightAnimation.flyTo(s,t)):this.error("flyToFrame - frame index out of range: "+e)}scrubToT(e){const t=this._cameraPath;if(!t)return;this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=Gh.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=Gh.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=Gh.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}Gh.STOPPED=0,Gh.SCRUBBING=1,Gh.PLAYING=2,Gh.PLAYING_TO=3;const zh=c.vec3(),Wh=c.vec3();c.vec3();const Kh=c.vec3([0,-1,0]),Xh=c.vec4([0,0,0,1]);function Jh(e){if(!Yh(e.width)||!Yh(e.height)){const t=document.createElement("canvas");t.width=Zh(e.width),t.height=Zh(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function Yh(e){return 0==(e&e-1)}function Zh(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class qh extends D{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const i=this.scene.canvas.gl;this._state=new lt({texture:new Cs({gl:i,target:i.TEXTURE_CUBE_MAP}),flipY:this._checkFlipY(t.minFilter),encoding:this._checkEncoding(t.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),this._src=t.src,this._images=[],this._loadSrc(t.src),p.memory.textures++}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}_loadSrc(e){const t=this,i=this.scene.canvas.gl;this._images=[];let s=!1,r=0;for(let o=0;o{r(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,r(),i.projection=s.projection)}}const ec=c.vec3();const tc=c.vec3();class ic{constructor(){this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsHasColorize=[],this.objectsOpacity=[],this.numObjects=0}saveObjects(e,t){this.numObjects=0,this._mask=t?_.apply(t,{}):null;const i=e.objects,s=!t||t.visible,r=!t||t.edges,o=!t||t.xrayed,n=!t||t.highlighted,a=!t||t.selected,l=!t||t.clippable,A=!t||t.pickable,h=!t||t.colorize,c=!t||t.opacity;for(let e in i)if(i.hasOwnProperty(e)){const t=i[e],u=this.numObjects;if(s&&(this.objectsVisible[u]=t.visible),r&&(this.objectsEdges[u]=t.edges),o&&(this.objectsXrayed[u]=t.xrayed),n&&(this.objectsHighlighted[u]=t.highlighted),a&&(this.objectsSelected[u]=t.selected),l&&(this.objectsClippable[u]=t.clippable),A&&(this.objectsPickable[u]=t.pickable),h){const e=t.colorize;e?(this.objectsColorize[3*u+0]=e[0],this.objectsColorize[3*u+1]=e[1],this.objectsColorize[3*u+2]=e[2],this.objectsHasColorize[u]=!0):this.objectsHasColorize[u]=!1}c&&(this.objectsOpacity[u]=t.opacity),this.numObjects++}}restoreObjects(e){const t=this._mask,i=!t||t.visible,s=!t||t.edges,r=!t||t.xrayed,o=!t||t.highlighted,n=!t||t.selected,a=!t||t.clippable,l=!t||t.pickable,A=!t||t.colorize,h=!t||t.opacity;var c=0;const u=e.objects;for(let e in u)if(u.hasOwnProperty(e)){const t=u[e];i&&(t.visible=this.objectsVisible[c]),s&&(t.edges=this.objectsEdges[c]),r&&(t.xrayed=this.objectsXrayed[c]),o&&(t.highlighted=this.objectsHighlighted[c]),n&&(t.selected=this.objectsSelected[c]),a&&(t.clippable=this.objectsClippable[c]),l&&(t.pickable=this.objectsPickable[c]),A&&(this.objectsHasColorize[c]?(tc[0]=this.objectsColorize[3*c+0],tc[1]=this.objectsColorize[3*c+1],tc[2]=this.objectsColorize[3*c+2],t.colorize=tc):t.colorize=null),h&&(t.opacity=this.objectsOpacity[c]),c++}}}class sc extends D{constructor(e,t={}){super(e,t),this._skyboxMesh=new es(this,{geometry:new Gt(this,{primitive:"triangles",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]}),background:!0,scale:[2e3,2e3,2e3],rotation:[0,-90,0],material:new Jt(this,{ambient:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],emissive:[1,1,1],emissiveMap:new Ss(this,{src:t.src,flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge",encoding:t.encoding||"sRGB"}),backfaces:!0}),visible:!1,pickable:!1,clippable:!1,collidable:!1}),this.size=t.size,this.active=t.active}set size(e){this._size=e||1e3,this._skyboxMesh.scale=[this._size,this._size,this._size]}get size(){return this._size}set active(e){this._skyboxMesh.visible=e}get active(){return this._skyboxMesh.visible}}const rc=c.vec4(),oc=c.vec4(),nc=c.vec3(),ac=c.vec3(),lc=c.vec3(),Ac=c.vec4(),hc=c.vec4(),cc=c.vec4();class uc{constructor(e){this._scene=e}dollyToCanvasPos(e,t,i){let s=!1;const r=this._scene.camera;if(e){const t=c.subVec3(e,r.eye,nc);s=c.lenVec3(t){this._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(()=>{this._cameraDirty=!0})),this._onTick=this._scene.on("tick",(()=>{this.updatePivotElement(),this.updatePivotSphere()}))}createPivotSphere(){const e=this.getPivotPos(),t=c.vec3();c.decomposeMat4(c.inverseMat4(this._scene.viewer.camera.viewMatrix,c.mat4()),t,c.vec4(),c.vec3());const i=c.distVec3(t,e);let s=Math.tan(Math.PI/500)*i*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(s/=this._scene.camera.ortho.scale/2),W(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new Ls(this._scene,ss({radius:s})),this._pivotSphere=new es(this._scene,{geometry:this._pivotSphereGeometry,material:this._pivotSphereMaterial,pickable:!1,position:this._rtcPos,rtcCenter:this._rtcCenter})}destroyPivotSphere(){this._pivotSphere&&(this._pivotSphere.destroy(),this._pivotSphere=null),this._pivotSphereGeometry&&(this._pivotSphereGeometry.destroy(),this._pivotSphereGeometry=null)}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){c.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,c.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const i=t.boundary,s=i[2],r=i[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*s/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*r/2);let o=t._lastBoundingClientRect;if(!o||t._canvasSizeChanged){const e=t.canvas;o=t._lastBoundingClientRect=e.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(o.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(o.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}updatePivotSphere(){this._pivoting&&this._pivotSphere&&(W(this.getPivotPos(),this._rtcCenter,this._rtcPos),c.compareVec3(this._rtcPos,this._pivotSphere.position)||(this.destroyPivotSphere(),this.createPivotSphere()))}setPivotElement(e){this._pivotElement=e}enablePivotSphere(e={}){this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);const t=e.color||[1,0,0];this._pivotSphereMaterial=new Jt(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}disablePivotSphere(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}startPivot(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;const e=this._scene.camera;let t=c.lookAtMat4v(e.eye,e.look,e.worldUp);c.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const i=this.getPivotPos();this._cameraOffset[2]+=c.distVec3(e.eye,i),t=c.inverseMat4(t);const s=c.transformVec3(t,this._cameraOffset),r=c.vec3();if(c.subVec3(e.eye,i,r),c.addVec3(r,s),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=c.lenVec3(r),this._polar=Math.acos(r[1]/this._radius),this._azimuth=Math.atan2(r[0],r[2]),this._pivoting=!0}_cameraLookingDownwards(){const e=this._scene.camera,t=c.normalizeVec3(c.subVec3(e.look,e.eye,dc)),i=c.cross3Vec3(t,e.worldUp,pc);return c.sqLenVec3(i)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}setCanvasPivotPos(e){const t=this._scene.camera,i=Math.abs(c.distVec3(this._scene.center,t.eye)),s=t.project.transposedMatrix,r=s.subarray(8,12),o=s.subarray(12),n=[0,0,-1,1],a=c.dotVec4(n,r)/c.dotVec4(n,o),l=gc;t.project.unproject(e,a,mc,_c,l);const A=c.normalizeVec3(c.subVec3(l,t.eye,dc)),h=c.addVec3(t.eye,c.mulVec3Scalar(A,i,pc),fc);this.setPivotPos(h)}getPivotPos(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const i=this._scene.camera;var s=-e;const r=-t;1===i.worldUp[2]&&(s=-s),this._azimuth+=.01*-s,this._polar+=.01*r,this._polar=c.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 n=c.lenVec3(c.subVec3(i.look,i.eye,c.vec3())),a=this.getPivotPos();c.addVec3(o,a);let l=c.lookAtMat4v(o,a,i.worldUp);l=c.inverseMat4(l);const A=c.transformVec3(l,this._cameraOffset);l[12]-=A[0],l[13]-=A[1],l[14]-=A[2];const h=[l[8],l[9],l[10]];i.eye=[l[12],l[13],l[14]],c.subVec3(i.eye,c.mulVec3Scalar(h,n),i.look),i.up=[l[4],l[5],l[6]],this.showPivot()}showPivot(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}hidePivot(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}endPivot(){this._pivoting=!1}destroy(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}class bc{constructor(e,t){this._scene=e.scene,this._cameraControl=e,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=t,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=c.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;const e=`${~~this.pickCursorPos[0]}-${~~this.pickCursorPos[1]}-${this.scheduleSnapOrPick}-${this.schedulePickSurface}-${this.schedulePickEntity}`;if(this._lastHash===e)return;this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;const t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){const e=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});e&&(e.snappedToEdge||e.snappedToVertex)?(this.snapPickResult=e,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const e=this.pickResult.canvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){const e=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){const e=new Re;e.entity=this.snapPickResult.entity,e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){const e=this.pickResult.entity.id;this._lastPickedEntityId!==e&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=e)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}const yc=c.vec2();class xc{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController;let n,a,l,A=0,h=0,u=0,d=0,p=!1;const f=c.vec3();let g=!0;const m=this._scene.canvas.canvas,_=[];function v(e=!0){m.style.cursor="move",A=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],u=s.pointerCanvasPos[0],d=s.pointerCanvasPos[1],e&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(p=!0,f.set(o.pickResult.worldPos)):p=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!1}),m.addEventListener("mousedown",this._mouseDownHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:_[e.input.KEY_SHIFT]||i.planView?(n=!0,v()):(n=!0,v(!1));break;case 2:a=!0,v();break;case 3:l=!0,i.panRightClick&&v()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(!n&&!a&&!l)return;const o=e.canvas.boundary,u=o[2],d=o[3],g=s.pointerCanvasPos[0],m=s.pointerCanvasPos[1],v=_[e.input.KEY_SHIFT]||i.planView||!i.panRightClick&&a||i.panRightClick&&l,b=document.pointerLockElement?t.movementX:g-A,y=document.pointerLockElement?t.movementY:m-h;if(v){const t=e.camera;if("perspective"===t.projection){const i=Math.abs(p?c.lenVec3(c.subVec3(f,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(t.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*b*i/d,r.panDeltaY+=1.5*y*i/d}else r.panDeltaX+=.5*t.ortho.scale*(b/d),r.panDeltaY+=.5*t.ortho.scale*(y/d)}else!n||a||l||i.planView||(i.firstPerson?(r.rotateDeltaY-=b/u*i.dragRotationRate/2,r.rotateDeltaX+=y/d*(i.dragRotationRate/4)):(r.rotateDeltaY-=b/u*(1.5*i.dragRotationRate),r.rotateDeltaX+=y/d*(1.5*i.dragRotationRate)));A=g,h=m}),m.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{i.active&&i.pointerEnabled&&s.mouseover&&(g=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{if(i.active&&i.pointerEnabled)switch(e.which){case 1:case 2:case 3:n=!1,a=!1,l=!1}}),m.addEventListener("mouseup",this._mouseUpHandler=e=>{if(i.active&&i.pointerEnabled){if(3===e.which){!function(e,t){if(e){let i=e.target,s=0,r=0,o=0,n=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,o+=i.scrollLeft,n+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+o-s,t[1]=e.pageY+n-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,yc);const i=yc[0],s=yc[1];Math.abs(i-u)<3&&Math.abs(s-d)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:yc,event:e},!0)}m.style.removeProperty("cursor")}}),m.addEventListener("mouseenter",this._mouseEnterHandler=()=>{i.active&&i.pointerEnabled});const b=1/60;let y=null;m.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!(i.active&&i.pointerEnabled&&i.zoomOnMouseWheel))return;const t=performance.now()/1e3;var o=null!==y?t-y:0;y=t,o>.05&&(o=.05),o{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover)return;const n=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),a=r._isKeyDownForAction(r.AXIS_VIEW_BACK),l=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),A=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),h=r._isKeyDownForAction(r.AXIS_VIEW_TOP),u=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(n||a||l||A||h||u))return;const d=e.aabb,p=c.getAABB3Diag(d);c.getAABB3Center(d,Bc);const f=Math.abs(p/Math.tan(t.cameraFlight.fitFOV*c.DEGTORAD)),g=1.1*p;Ec.orthoScale=g,n?(Ec.eye.set(c.addVec3(Bc,c.mulVec3Scalar(o.worldRight,f,wc),Mc)),Ec.look.set(Bc),Ec.up.set(o.worldUp)):a?(Ec.eye.set(c.addVec3(Bc,c.mulVec3Scalar(o.worldForward,f,wc),Mc)),Ec.look.set(Bc),Ec.up.set(o.worldUp)):l?(Ec.eye.set(c.addVec3(Bc,c.mulVec3Scalar(o.worldRight,-f,wc),Mc)),Ec.look.set(Bc),Ec.up.set(o.worldUp)):A?(Ec.eye.set(c.addVec3(Bc,c.mulVec3Scalar(o.worldForward,-f,wc),Mc)),Ec.look.set(Bc),Ec.up.set(o.worldUp)):h?(Ec.eye.set(c.addVec3(Bc,c.mulVec3Scalar(o.worldUp,f,wc),Mc)),Ec.look.set(Bc),Ec.up.set(c.normalizeVec3(c.mulVec3Scalar(o.worldForward,1,Pc),Cc))):u&&(Ec.eye.set(c.addVec3(Bc,c.mulVec3Scalar(o.worldUp,-f,wc),Mc)),Ec.look.set(Bc),Ec.up.set(c.normalizeVec3(c.mulVec3Scalar(o.worldForward,-1,Pc)))),!i.firstPerson&&i.followPointer&&t.pivotController.setPivotPos(Bc),t.cameraFlight.duration>0?t.cameraFlight.flyTo(Ec,(()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(Ec),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class Ic{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;let l=!1,A=!1;const h=this._scene.canvas.canvas,u=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i&&i.entity?i.entity.aabb:e.aabb;if(s){const i=e.camera;c.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})},d=e.tickify(this._canvasMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(l||A)return;if(a.hasSubs("rayMove")){const t=c.vec3(),i=c.vec3();c.canvasPosToWorldRay(e.canvas.canvas,e.camera.viewMatrix,e.camera.projMatrix,e.camera.projection,s.pointerCanvasPos,t,i),a.fire("rayMove",{canvasPos:s.pointerCanvasPos,ray:{origin:t,direction:i,canvasPos:s.pointerCanvasPos}},!0)}const r=a.hasSubs("hover"),n=a.hasSubs("hoverEnter"),h=a.hasSubs("hoverOut"),u=a.hasSubs("hoverOff"),d=a.hasSubs("hoverSurface"),p=a.hasSubs("hoverSnapOrSurface");if(r||n||h||u||d||p)if(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=d,o.scheduleSnapOrPick=p,o.update(),o.pickResult){if(o.pickResult.entity){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),a.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t)}a.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&a.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),a.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)});h.addEventListener("mousemove",d),h.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(l=!0),3===t.which&&(A=!0);if(1===t.which&&i.active&&i.pointerEnabled&&(s.mouseDownClientX=t.clientX,s.mouseDownClientY=t.clientY,s.mouseDownCursorX=s.pointerCanvasPos[0],s.mouseDownCursorY=s.pointerCanvasPos[1],!i.firstPerson&&i.followPointer&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===t.which))){const t=o.pickResult;t&&t.worldPos?(n.setPivotPos(t.worldPos),n.startPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),n.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(l=!1),3===e.which&&(A=!1),n.getPivoting()&&n.endPivot()}),h.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!i.active||!i.pointerEnabled)return;if(!(1===r.which))return;if(n.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const l=a.hasSubs("picked"),A=a.hasSubs("pickedNothing"),h=a.hasSubs("pickedSurface"),d=a.hasSubs("doublePicked"),p=a.hasSubs("doublePickedSurface"),f=a.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||d||p||f))return(l||A||h)&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=h,o.update(),o.pickResult?(a.fire("picked",o.pickResult,!0),o.pickedSurface&&a.fire("pickedSurface",o.pickResult,!0)):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=h,o.update();const e=o.pickResult,r=o.pickedSurface;this._timeout=setTimeout((()=>{e&&e.worldPos?(a.fire("picked",e,!0),r&&(a.fire("pickedSurface",e,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),this._clicks=0}),i.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo||d||p,o.schedulePickSurface=o.schedulePickEntity&&p,o.update(),o.pickResult){if(a.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&a.fire("doublePickedSurface",o.pickResult,!0),i.doublePickFlyTo&&(u(o.pickResult),!i.firstPerson&&i.followPointer)){const e=o.pickResult.entity.aabb,i=c.getAABB3Center(e);t.pivotController.setPivotPos(i),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(a.fire("doublePickedNothing",{canvasPos:s.pointerCanvasPos},!0),i.doublePickFlyTo&&(u(),!i.firstPerson&&i.followPointer)){const i=e.aabb,s=c.getAABB3Center(i);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}this._clicks=0}},!1)}reset(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}class Dc{constructor(e,t,i,s,r){this._scene=e;const o=e.input,n=[],a=e.canvas.canvas;let l=!0;this._onSceneMouseMove=o.on("mousemove",(()=>{l=!0})),this._onSceneKeyDown=o.on("keydown",(t=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover||(n[t]=!0,t===o.KEY_SHIFT&&(a.style.cursor="move")))})),this._onSceneKeyUp=o.on("keyup",(s=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(n[s]=!1,s===o.KEY_SHIFT&&(a.style.cursor=null),t.pivotController.getPivoting()&&t.pivotController.endPivot())})),this._onTick=e.on("tick",(a=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover)return;const A=t.cameraControl,h=a.deltaTime/1e3;if(!i.planView){const e=A._isKeyDownForAction(A.ROTATE_Y_POS,n),s=A._isKeyDownForAction(A.ROTATE_Y_NEG,n),o=A._isKeyDownForAction(A.ROTATE_X_POS,n),a=A._isKeyDownForAction(A.ROTATE_X_NEG,n),l=h*i.keyboardRotationRate;(e||s||o||a)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:s&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:a&&(r.rotateDeltaX-=l),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!n[o.KEY_CTRL]&&!n[o.KEY_ALT]){const e=A._isKeyDownForAction(A.DOLLY_BACKWARDS,n),o=A._isKeyDownForAction(A.DOLLY_FORWARDS,n);if(e||o){const n=h*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=n:e&&(r.dollyDelta+=n),l&&(s.followPointerDirty=!0,l=!1)}}const c=A._isKeyDownForAction(A.PAN_FORWARDS,n),u=A._isKeyDownForAction(A.PAN_BACKWARDS,n),d=A._isKeyDownForAction(A.PAN_LEFT,n),p=A._isKeyDownForAction(A.PAN_RIGHT,n),f=A._isKeyDownForAction(A.PAN_UP,n),g=A._isKeyDownForAction(A.PAN_DOWN,n),m=(n[o.KEY_ALT]?.3:1)*h*i.keyboardPanRate;(c||u||d||p||f||g)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),g?r.panDeltaY+=m:f&&(r.panDeltaY+=-m),p?r.panDeltaX+=-m:d&&(r.panDeltaX+=m),u?r.panDeltaZ+=m:c&&(r.panDeltaZ+=-m))}))}reset(){}destroy(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),this._scene.input.off(this._onSceneKeyUp)}}const Sc=c.vec3();class Tc{constructor(e,t,i,s,r){this._scene=e;const o=e.camera,n=t.pickController,a=t.pivotController,l=t.panController;let A=1,h=1,u=null;this._onTick=e.on("tick",(()=>{if(!i.active||!i.pointerEnabled)return;let t="default";if(Math.abs(r.dollyDelta)<.001&&(r.dollyDelta=0),Math.abs(r.rotateDeltaX)<.001&&(r.rotateDeltaX=0),Math.abs(r.rotateDeltaY)<.001&&(r.rotateDeltaY=0),0===r.rotateDeltaX&&0===r.rotateDeltaY||(r.dollyDelta=0),i.followPointer){if(--A<=0&&(A=1,0!==r.dollyDelta)){if(0===r.rotateDeltaY&&0===r.rotateDeltaX&&i.followPointer&&s.followPointerDirty&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),n.pickResult&&n.pickResult.worldPos?u=n.pickResult.worldPos:(h=1,u=null),s.followPointerDirty=!1),u){const t=Math.abs(c.lenVec3(c.subVec3(u,e.camera.eye,Sc)));h=t/i.dollyProximityThreshold}h{s.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{s.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{Lc(e,o,s.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=e=>{i.active&&i.pointerEnabled&&(Lc(e,o,s.pointerCanvasPos),s.mouseover=!0)}),o.addEventListener("mouseup",this._mouseUpHandler=e=>{i.active&&i.pointerEnabled})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}function Lc(e,t,i){if(e){const{left:s,top:r}=t.getBoundingClientRect();i[0]=e.clientX-s,i[1]=e.clientY-r}else e=window.event,i[0]=e.x,i[1]=e.y;return i}const Uc=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 Oc{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=c.vec2(),l=c.vec2(),A=c.vec2(),h=c.vec2(),u=[],d=this._scene.canvas.canvas;let p=0,f=!1;this._onTick=e.on("tick",(()=>{f=!1})),d.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!i.active||!i.pointerEnabled)return;t.preventDefault();const r=t.touches,l=t.changedTouches;for(s.touchStartTime=Date.now(),1===r.length&&1===l.length&&(Uc(r[0],a),i.followPointer&&(o.pickCursorPos=a,o.schedulePickSurface=!0,o.update(),i.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(n.setPivotPos(o.pickResult.worldPos),!i.firstPerson&&n.startPivot()&&n.showPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),!i.firstPerson&&n.startPivot()&&n.showPivot()))));u.length{n.getPivoting()&&n.endPivot()}),d.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const n=e.canvas.boundary,a=n[2],d=n[3],g=t.touches;if(t.touches.length===p){if(1===p){Uc(g[0],l),c.subVec2(l,u[0],h);const t=h[0],o=h[1];if(null!==s.longTouchTimeout&&(Math.abs(t)>i.longTapRadius||Math.abs(o)>i.longTapRadius)&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),i.planView){const s=e.camera;if("perspective"===s.projection){const n=Math.abs(e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*n/d*i.touchPanRate,r.panDeltaY+=o*n/d*i.touchPanRate}else r.panDeltaX+=.5*s.ortho.scale*(t/d)*i.touchPanRate,r.panDeltaY+=.5*s.ortho.scale*(o/d)*i.touchPanRate}else r.rotateDeltaY-=t/a*(1*i.dragRotationRate),r.rotateDeltaX+=o/d*(1.5*i.dragRotationRate)}else if(2===p){const t=g[0],n=g[1];Uc(t,l),Uc(n,A);const a=c.geometricMeanVec2(u[0],u[1]),h=c.geometricMeanVec2(l,A),p=c.vec2();c.subVec2(a,h,p);const f=p[0],m=p[1],_=e.camera,v=c.distVec2([t.pageX,t.pageY],[n.pageX,n.pageY]),b=(c.distVec2(u[0],u[1])-v)*i.touchDollyRate;if(r.dollyDelta=b,Math.abs(b)<1)if("perspective"===_.projection){const t=o.pickResult?o.pickResult.worldPos:e.center,s=Math.abs(c.lenVec3(c.subVec3(t,e.camera.eye,[])))*Math.tan(_.perspective.fov/2*Math.PI/180);r.panDeltaX-=f*s/d*i.touchPanRate,r.panDeltaY-=m*s/d*i.touchPanRate}else r.panDeltaX-=.5*_.ortho.scale*(f/d)*i.touchPanRate,r.panDeltaY-=.5*_.ortho.scale*(m/d)*i.touchPanRate;s.pointerCanvasPos=h}for(let e=0;e{let s;i&&i.worldPos&&(s=i.worldPos);const r=i?i.entity.aabb:e.aabb;if(s){const i=e.camera;c.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};d.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!i.active||!i.pointerEnabled)return;null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null);const r=e.touches,o=e.changedTouches;if(a=Date.now(),1===r.length&&1===o.length){h=a,kc(r[0],A);const o=A[0],n=A[1],l=r[0].pageX,c=r[0].pageY;s.longTouchTimeout=setTimeout((()=>{t.cameraControl.fire("rightClick",{pagePos:[Math.round(l),Math.round(c)],canvasPos:[Math.round(o),Math.round(n)],event:e},!0),s.longTouchTimeout=null}),i.longTapTimeout)}else h=-1;for(;l.length{if(!i.active||!i.pointerEnabled)return;const t=Date.now(),r=e.touches,a=e.changedTouches,d=n.hasSubs("pickedSurface");null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),0===r.length&&1===a.length&&h>-1&&t-h<150&&(u>-1&&h-u<325?(kc(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=d,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("doublePicked",o.pickResult),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult),i.doublePickFlyTo&&p(o.pickResult)):(n.fire("doublePickedNothing"),i.doublePickFlyTo&&p()),u=-1):c.distVec2(l[0],A)<4&&(kc(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=d,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("picked",o.pickResult),o.pickedSurface&&n.fire("pickedSurface",o.pickResult)):n.fire("pickedNothing"),u=t),h=-1),l.length=r.length;for(let e=0,t=r.length;e{e.preventDefault()},this._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,zoomOnMouseWheel:!0,snapToVertex:true,snapToEdge:true,snapRadius:30,keyboardEnabledOnlyIfMouseover:!0,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},this._states={pointerCanvasPos:c.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:c.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const i=this.scene;this._controllers={cameraControl:this,pickController:new bc(this,this._configs),pivotController:new vc(i,this._configs),panController:new uc(i),cameraFlight:new jh(this,{duration:.5})},this._handlers=[new Rc(this.scene,this._controllers,this._configs,this._states,this._updates),new Oc(this.scene,this._controllers,this._configs,this._states,this._updates),new xc(this.scene,this._controllers,this._configs,this._states,this._updates),new Fc(this.scene,this._controllers,this._configs,this._states,this._updates),new Ic(this.scene,this._controllers,this._configs,this._states,this._updates),new Nc(this.scene,this._controllers,this._configs,this._states,this._updates),new Dc(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new Tc(this.scene,this._controllers,this._configs,this._states,this._updates),this.navMode=t.navMode,t.planView&&(this.planView=t.planView),this.constrainVertical=t.constrainVertical,t.keyboardLayout?this.keyboardLayout=t.keyboardLayout:this.keyMap=t.keyMap,this.doublePickFlyTo=t.doublePickFlyTo,this.panRightClick=t.panRightClick,this.active=t.active,this.followPointer=t.followPointer,this.rotationInertia=t.rotationInertia,this.keyboardPanRate=t.keyboardPanRate,this.touchPanRate=t.touchPanRate,this.keyboardRotationRate=t.keyboardRotationRate,this.dragRotationRate=t.dragRotationRate,this.touchDollyRate=t.touchDollyRate,this.dollyInertia=t.dollyInertia,this.dollyProximityThreshold=t.dollyProximityThreshold,this.dollyMinSpeed=t.dollyMinSpeed,this.panInertia=t.panInertia,this.pointerEnabled=!0,this.keyboardDollyRate=t.keyboardDollyRate,this.mouseWheelDollyRate=t.mouseWheelDollyRate}set keyMap(e){if(e=e||"qwerty",_.isString(e)){const t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=i}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_isKeyDownForAction(e,t){const i=this._keyMap[e];if(!i)return!1;t||(t=this.scene.input.keyDown);for(let e=0,s=i.length;e0&&console.error(`[MetaModel._decompressProperties] Properties not found: ${i}`)}finalize(){if(this.finalized)throw"MetaScene already finalized - can't re-finalize";const e=this.metaScene;for(let t in e.metaObjects){const i=e.metaObjects[t];if(i.children&&(i.children=[]),i.propertySets&&(i.propertySets=[]),i.propertySetIds)for(let t=0,s=i.propertySetIds.length;t0?Wc(t):null,n=i&&i.length>0?Wc(i):null,a=e=>{if(!e)return;var t=!0;(n&&n[e.type]||o&&!o[e.type])&&(t=!1),t&&s.push(e.id);const i=e.children;if(i)for(var r=0,l=i.length;r * Copyright (c) 2022 Niklas von Hertzen @@ -33,5 +33,5 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */var Kc=function(e,t){return Kc=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},Kc(e,t)};function Xc(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}Kc(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}var Jc=function(){return Jc=Object.assign||function(e){for(var t,i=1,s=arguments.length;i0&&r[r.length-1])||6!==o[0]&&2!==o[0])){n=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]=55296&&r<=56319&&i>10),n%1024+56320)),(r+1===i||s.length>16384)&&(o+=String.fromCharCode.apply(String,s),s.length=0)}return o},su="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ru="undefined"==typeof Uint8Array?[]:new Uint8Array(256),ou=0;ou=0){if(e<55296||e>56319&&e<=65535)return t=((t=this.index[e>>5])<<2)+(31&e),this.data[t];if(e<=65535)return t=((t=this.index[2048+(e-55296>>5)])<<2)+(31&e),this.data[t];if(e>11),t=this.index[t],t+=e>>5&63,t=((t=this.index[t])<<2)+(31&e),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},e}(),cu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",uu="undefined"==typeof Uint8Array?[]:new Uint8Array(256),du=0;du>4,h[l++]=(15&s)<<4|r>>2,h[l++]=(3&r)<<6|63&o;return A}(e),n=Array.isArray(o)?function(e){for(var t=e.length,i=[],s=0;s0;){var n=s[--o];if(Array.isArray(e)?-1!==e.indexOf(n):e===n)for(var a=i;a<=s.length;){var l;if((l=s[++a])===t)return!0;if(l!==pu)break}if(n!==pu)break}return!1},Xu=function(e,t){for(var i=e;i>=0;){var s=t[i];if(s!==pu)return s;i--}return 0},Ju=function(e,t,i,s,r){if(0===i[s])return"×";var o=s-1;if(Array.isArray(r)&&!0===r[o])return"×";var n=o-1,a=o+1,l=t[o],A=n>=0?t[n]:0,h=t[a];if(2===l&&3===h)return"×";if(-1!==Vu.indexOf(l))return"!";if(-1!==Vu.indexOf(h))return"×";if(-1!==Hu.indexOf(h))return"×";if(8===Xu(o,t))return"÷";if(11===Nu.get(e[o]))return"×";if((l===Fu||l===Iu)&&11===Nu.get(e[a]))return"×";if(7===l||7===h)return"×";if(9===l)return"×";if(-1===[pu,fu,gu].indexOf(l)&&9===h)return"×";if(-1!==[mu,_u,vu,Bu,Mu].indexOf(h))return"×";if(Xu(o,t)===xu)return"×";if(Ku(23,xu,o,t))return"×";if(Ku([mu,_u],yu,o,t))return"×";if(Ku(12,12,o,t))return"×";if(l===pu)return"÷";if(23===l||23===h)return"×";if(16===h||16===l)return"÷";if(-1!==[fu,gu,yu].indexOf(h)||14===l)return"×";if(36===A&&-1!==Wu.indexOf(l))return"×";if(l===Mu&&36===h)return"×";if(h===bu)return"×";if(-1!==Qu.indexOf(h)&&l===wu||-1!==Qu.indexOf(l)&&h===wu)return"×";if(l===Cu&&-1!==[Tu,Fu,Iu].indexOf(h)||-1!==[Tu,Fu,Iu].indexOf(l)&&h===Pu)return"×";if(-1!==Qu.indexOf(l)&&-1!==ju.indexOf(h)||-1!==ju.indexOf(l)&&-1!==Qu.indexOf(h))return"×";if(-1!==[Cu,Pu].indexOf(l)&&(h===wu||-1!==[xu,gu].indexOf(h)&&t[a+1]===wu)||-1!==[xu,gu].indexOf(l)&&h===wu||l===wu&&-1!==[wu,Mu,Bu].indexOf(h))return"×";if(-1!==[wu,Mu,Bu,mu,_u].indexOf(h))for(var c=o;c>=0;){if((u=t[c])===wu)return"×";if(-1===[Mu,Bu].indexOf(u))break;c--}if(-1!==[Cu,Pu].indexOf(h))for(c=-1!==[mu,_u].indexOf(l)?n:o;c>=0;){var u;if((u=t[c])===wu)return"×";if(-1===[Mu,Bu].indexOf(u))break;c--}if(Ru===l&&-1!==[Ru,Lu,Du,Su].indexOf(h)||-1!==[Lu,Du].indexOf(l)&&-1!==[Lu,Uu].indexOf(h)||-1!==[Uu,Su].indexOf(l)&&h===Uu)return"×";if(-1!==zu.indexOf(l)&&-1!==[bu,Pu].indexOf(h)||-1!==zu.indexOf(h)&&l===Cu)return"×";if(-1!==Qu.indexOf(l)&&-1!==Qu.indexOf(h))return"×";if(l===Bu&&-1!==Qu.indexOf(h))return"×";if(-1!==Qu.concat(wu).indexOf(l)&&h===xu&&-1===Ou.indexOf(e[a])||-1!==Qu.concat(wu).indexOf(h)&&l===_u)return"×";if(41===l&&41===h){for(var d=i[o],p=1;d>0&&41===t[--d];)p++;if(p%2!=0)return"×"}return l===Fu&&h===Iu?"×":"÷"},Yu=function(e,t){t||(t={lineBreak:"normal",wordBreak:"normal"});var i=function(e,t){void 0===t&&(t="strict");var i=[],s=[],r=[];return e.forEach((function(e,o){var n=Nu.get(e);if(n>50?(r.push(!0),n-=50):r.push(!1),-1!==["normal","auto","loose"].indexOf(t)&&-1!==[8208,8211,12316,12448].indexOf(e))return s.push(o),i.push(16);if(4===n||11===n){if(0===o)return s.push(o),i.push(Eu);var a=i[o-1];return-1===Gu.indexOf(a)?(s.push(s[o-1]),i.push(a)):(s.push(o),i.push(Eu))}return s.push(o),31===n?i.push("strict"===t?yu:Tu):n===ku||29===n?i.push(Eu):43===n?e>=131072&&e<=196605||e>=196608&&e<=262141?i.push(Tu):i.push(Eu):void i.push(n)})),[s,i,r]}(e,t.lineBreak),s=i[0],r=i[1],o=i[2];"break-all"!==t.wordBreak&&"break-word"!==t.wordBreak||(r=r.map((function(e){return-1!==[wu,Eu,ku].indexOf(e)?Tu:e})));var n="keep-all"===t.wordBreak?o.map((function(t,i){return t&&e[i]>=19968&&e[i]<=40959})):void 0;return[s,r,n]},Zu=function(){function e(e,t,i,s){this.codePoints=e,this.required="!"===t,this.start=i,this.end=s}return e.prototype.slice=function(){return iu.apply(void 0,this.codePoints.slice(this.start,this.end))},e}(),qu=function(e){return e>=48&&e<=57},$u=function(e){return qu(e)||e>=65&&e<=70||e>=97&&e<=102},ed=function(e){return 10===e||9===e||32===e},td=function(e){return function(e){return function(e){return e>=97&&e<=122}(e)||function(e){return e>=65&&e<=90}(e)}(e)||function(e){return e>=128}(e)||95===e},id=function(e){return td(e)||qu(e)||45===e},sd=function(e){return e>=0&&e<=8||11===e||e>=14&&e<=31||127===e},rd=function(e,t){return 92===e&&10!==t},od=function(e,t,i){return 45===e?td(t)||rd(t,i):!!td(e)||!(92!==e||!rd(e,t))},nd=function(e,t,i){return 43===e||45===e?!!qu(t)||46===t&&qu(i):qu(46===e?t:e)},ad=function(e){var t=0,i=1;43!==e[t]&&45!==e[t]||(45===e[t]&&(i=-1),t++);for(var s=[];qu(e[t]);)s.push(e[t++]);var r=s.length?parseInt(iu.apply(void 0,s),10):0;46===e[t]&&t++;for(var o=[];qu(e[t]);)o.push(e[t++]);var n=o.length,a=n?parseInt(iu.apply(void 0,o),10):0;69!==e[t]&&101!==e[t]||t++;var l=1;43!==e[t]&&45!==e[t]||(45===e[t]&&(l=-1),t++);for(var A=[];qu(e[t]);)A.push(e[t++]);var h=A.length?parseInt(iu.apply(void 0,A),10):0;return i*(r+a*Math.pow(10,-n))*Math.pow(10,l*h)},ld={type:2},Ad={type:3},hd={type:4},cd={type:13},ud={type:8},dd={type:21},pd={type:9},fd={type:10},gd={type:11},md={type:12},_d={type:14},vd={type:23},bd={type:1},yd={type:25},xd={type:24},Bd={type:26},wd={type:27},Pd={type:28},Cd={type:29},Md={type:31},Ed={type:32},Fd=function(){function e(){this._value=[]}return e.prototype.write=function(e){this._value=this._value.concat(tu(e))},e.prototype.read=function(){for(var e=[],t=this.consumeToken();t!==Ed;)e.push(t),t=this.consumeToken();return e},e.prototype.consumeToken=function(){var e=this.consumeCodePoint();switch(e){case 34:return this.consumeStringToken(34);case 35:var t=this.peekCodePoint(0),i=this.peekCodePoint(1),s=this.peekCodePoint(2);if(id(t)||rd(i,s)){var r=od(t,i,s)?2:1;return{type:5,value:this.consumeName(),flags:r}}break;case 36:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),cd;break;case 39:return this.consumeStringToken(39);case 40:return ld;case 41:return Ad;case 42:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),_d;break;case 43:if(nd(e,this.peekCodePoint(0),this.peekCodePoint(1)))return this.reconsumeCodePoint(e),this.consumeNumericToken();break;case 44:return hd;case 45:var o=e,n=this.peekCodePoint(0),a=this.peekCodePoint(1);if(nd(o,n,a))return this.reconsumeCodePoint(e),this.consumeNumericToken();if(od(o,n,a))return this.reconsumeCodePoint(e),this.consumeIdentLikeToken();if(45===n&&62===a)return this.consumeCodePoint(),this.consumeCodePoint(),xd;break;case 46:if(nd(e,this.peekCodePoint(0),this.peekCodePoint(1)))return this.reconsumeCodePoint(e),this.consumeNumericToken();break;case 47:if(42===this.peekCodePoint(0))for(this.consumeCodePoint();;){var l=this.consumeCodePoint();if(42===l&&47===(l=this.consumeCodePoint()))return this.consumeToken();if(-1===l)return this.consumeToken()}break;case 58:return Bd;case 59:return wd;case 60:if(33===this.peekCodePoint(0)&&45===this.peekCodePoint(1)&&45===this.peekCodePoint(2))return this.consumeCodePoint(),this.consumeCodePoint(),yd;break;case 64:var A=this.peekCodePoint(0),h=this.peekCodePoint(1),c=this.peekCodePoint(2);if(od(A,h,c))return{type:7,value:this.consumeName()};break;case 91:return Pd;case 92:if(rd(e,this.peekCodePoint(0)))return this.reconsumeCodePoint(e),this.consumeIdentLikeToken();break;case 93:return Cd;case 61:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),ud;break;case 123:return gd;case 125:return md;case 117:case 85:var u=this.peekCodePoint(0),d=this.peekCodePoint(1);return 43!==u||!$u(d)&&63!==d||(this.consumeCodePoint(),this.consumeUnicodeRangeToken()),this.reconsumeCodePoint(e),this.consumeIdentLikeToken();case 124:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),pd;if(124===this.peekCodePoint(0))return this.consumeCodePoint(),dd;break;case 126:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),fd;break;case-1:return Ed}return ed(e)?(this.consumeWhiteSpace(),Md):qu(e)?(this.reconsumeCodePoint(e),this.consumeNumericToken()):td(e)?(this.reconsumeCodePoint(e),this.consumeIdentLikeToken()):{type:6,value:iu(e)}},e.prototype.consumeCodePoint=function(){var e=this._value.shift();return void 0===e?-1:e},e.prototype.reconsumeCodePoint=function(e){this._value.unshift(e)},e.prototype.peekCodePoint=function(e){return e>=this._value.length?-1:this._value[e]},e.prototype.consumeUnicodeRangeToken=function(){for(var e=[],t=this.consumeCodePoint();$u(t)&&e.length<6;)e.push(t),t=this.consumeCodePoint();for(var i=!1;63===t&&e.length<6;)e.push(t),t=this.consumeCodePoint(),i=!0;if(i)return{type:30,start:parseInt(iu.apply(void 0,e.map((function(e){return 63===e?48:e}))),16),end:parseInt(iu.apply(void 0,e.map((function(e){return 63===e?70:e}))),16)};var s=parseInt(iu.apply(void 0,e),16);if(45===this.peekCodePoint(0)&&$u(this.peekCodePoint(1))){this.consumeCodePoint(),t=this.consumeCodePoint();for(var r=[];$u(t)&&r.length<6;)r.push(t),t=this.consumeCodePoint();return{type:30,start:s,end:parseInt(iu.apply(void 0,r),16)}}return{type:30,start:s,end:s}},e.prototype.consumeIdentLikeToken=function(){var e=this.consumeName();return"url"===e.toLowerCase()&&40===this.peekCodePoint(0)?(this.consumeCodePoint(),this.consumeUrlToken()):40===this.peekCodePoint(0)?(this.consumeCodePoint(),{type:19,value:e}):{type:20,value:e}},e.prototype.consumeUrlToken=function(){var e=[];if(this.consumeWhiteSpace(),-1===this.peekCodePoint(0))return{type:22,value:""};var t=this.peekCodePoint(0);if(39===t||34===t){var i=this.consumeStringToken(this.consumeCodePoint());return 0===i.type&&(this.consumeWhiteSpace(),-1===this.peekCodePoint(0)||41===this.peekCodePoint(0))?(this.consumeCodePoint(),{type:22,value:i.value}):(this.consumeBadUrlRemnants(),vd)}for(;;){var s=this.consumeCodePoint();if(-1===s||41===s)return{type:22,value:iu.apply(void 0,e)};if(ed(s))return this.consumeWhiteSpace(),-1===this.peekCodePoint(0)||41===this.peekCodePoint(0)?(this.consumeCodePoint(),{type:22,value:iu.apply(void 0,e)}):(this.consumeBadUrlRemnants(),vd);if(34===s||39===s||40===s||sd(s))return this.consumeBadUrlRemnants(),vd;if(92===s){if(!rd(s,this.peekCodePoint(0)))return this.consumeBadUrlRemnants(),vd;e.push(this.consumeEscapedCodePoint())}else e.push(s)}},e.prototype.consumeWhiteSpace=function(){for(;ed(this.peekCodePoint(0));)this.consumeCodePoint()},e.prototype.consumeBadUrlRemnants=function(){for(;;){var e=this.consumeCodePoint();if(41===e||-1===e)return;rd(e,this.peekCodePoint(0))&&this.consumeEscapedCodePoint()}},e.prototype.consumeStringSlice=function(e){for(var t="";e>0;){var i=Math.min(5e4,e);t+=iu.apply(void 0,this._value.splice(0,i)),e-=i}return this._value.shift(),t},e.prototype.consumeStringToken=function(e){for(var t="",i=0;;){var s=this._value[i];if(-1===s||void 0===s||s===e)return{type:0,value:t+=this.consumeStringSlice(i)};if(10===s)return this._value.splice(0,i),bd;if(92===s){var r=this._value[i+1];-1!==r&&void 0!==r&&(10===r?(t+=this.consumeStringSlice(i),i=-1,this._value.shift()):rd(s,r)&&(t+=this.consumeStringSlice(i),t+=iu(this.consumeEscapedCodePoint()),i=-1))}i++}},e.prototype.consumeNumber=function(){var e=[],t=4,i=this.peekCodePoint(0);for(43!==i&&45!==i||e.push(this.consumeCodePoint());qu(this.peekCodePoint(0));)e.push(this.consumeCodePoint());i=this.peekCodePoint(0);var s=this.peekCodePoint(1);if(46===i&&qu(s))for(e.push(this.consumeCodePoint(),this.consumeCodePoint()),t=8;qu(this.peekCodePoint(0));)e.push(this.consumeCodePoint());i=this.peekCodePoint(0),s=this.peekCodePoint(1);var r=this.peekCodePoint(2);if((69===i||101===i)&&((43===s||45===s)&&qu(r)||qu(s)))for(e.push(this.consumeCodePoint(),this.consumeCodePoint()),t=8;qu(this.peekCodePoint(0));)e.push(this.consumeCodePoint());return[ad(e),t]},e.prototype.consumeNumericToken=function(){var e=this.consumeNumber(),t=e[0],i=e[1],s=this.peekCodePoint(0),r=this.peekCodePoint(1),o=this.peekCodePoint(2);return od(s,r,o)?{type:15,number:t,flags:i,unit:this.consumeName()}:37===s?(this.consumeCodePoint(),{type:16,number:t,flags:i}):{type:17,number:t,flags:i}},e.prototype.consumeEscapedCodePoint=function(){var e=this.consumeCodePoint();if($u(e)){for(var t=iu(e);$u(this.peekCodePoint(0))&&t.length<6;)t+=iu(this.consumeCodePoint());ed(this.peekCodePoint(0))&&this.consumeCodePoint();var i=parseInt(t,16);return 0===i||function(e){return e>=55296&&e<=57343}(i)||i>1114111?65533:i}return-1===e?65533:e},e.prototype.consumeName=function(){for(var e="";;){var t=this.consumeCodePoint();if(id(t))e+=iu(t);else{if(!rd(t,this.peekCodePoint(0)))return this.reconsumeCodePoint(t),e;e+=iu(this.consumeEscapedCodePoint())}}},e}(),Id=function(){function e(e){this._tokens=e}return e.create=function(t){var i=new Fd;return i.write(t),new e(i.read())},e.parseValue=function(t){return e.create(t).parseComponentValue()},e.parseValues=function(t){return e.create(t).parseComponentValues()},e.prototype.parseComponentValue=function(){for(var e=this.consumeToken();31===e.type;)e=this.consumeToken();if(32===e.type)throw new SyntaxError("Error parsing CSS component value, unexpected EOF");this.reconsumeToken(e);var t=this.consumeComponentValue();do{e=this.consumeToken()}while(31===e.type);if(32===e.type)return t;throw new SyntaxError("Error parsing CSS component value, multiple values found when expecting only one")},e.prototype.parseComponentValues=function(){for(var e=[];;){var t=this.consumeComponentValue();if(32===t.type)return e;e.push(t),e.push()}},e.prototype.consumeComponentValue=function(){var e=this.consumeToken();switch(e.type){case 11:case 28:case 2:return this.consumeSimpleBlock(e.type);case 19:return this.consumeFunction(e)}return e},e.prototype.consumeSimpleBlock=function(e){for(var t={type:e,values:[]},i=this.consumeToken();;){if(32===i.type||Nd(i,e))return t;this.reconsumeToken(i),t.values.push(this.consumeComponentValue()),i=this.consumeToken()}},e.prototype.consumeFunction=function(e){for(var t={name:e.value,values:[],type:18};;){var i=this.consumeToken();if(32===i.type||3===i.type)return t;this.reconsumeToken(i),t.values.push(this.consumeComponentValue())}},e.prototype.consumeToken=function(){var e=this._tokens.shift();return void 0===e?Ed:e},e.prototype.reconsumeToken=function(e){this._tokens.unshift(e)},e}(),Dd=function(e){return 15===e.type},Sd=function(e){return 17===e.type},Td=function(e){return 20===e.type},Rd=function(e){return 0===e.type},Ld=function(e,t){return Td(e)&&e.value===t},Ud=function(e){return 31!==e.type},kd=function(e){return 31!==e.type&&4!==e.type},Od=function(e){var t=[],i=[];return e.forEach((function(e){if(4===e.type){if(0===i.length)throw new Error("Error parsing function args, zero tokens for arg");return t.push(i),void(i=[])}31!==e.type&&i.push(e)})),i.length&&t.push(i),t},Nd=function(e,t){return 11===t&&12===e.type||(28===t&&29===e.type||2===t&&3===e.type)},Qd=function(e){return 17===e.type||15===e.type},Vd=function(e){return 16===e.type||Qd(e)},Hd=function(e){return e.length>1?[e[0],e[1]]:[e[0]]},jd={type:17,number:0,flags:4},Gd={type:16,number:50,flags:4},zd={type:16,number:100,flags:4},Wd=function(e,t,i){var s=e[0],r=e[1];return[Kd(s,t),Kd(void 0!==r?r:s,i)]},Kd=function(e,t){if(16===e.type)return e.number/100*t;if(Dd(e))switch(e.unit){case"rem":case"em":return 16*e.number;default:return e.number}return e.number},Xd=function(e,t){if(15===t.type)switch(t.unit){case"deg":return Math.PI*t.number/180;case"grad":return Math.PI/200*t.number;case"rad":return t.number;case"turn":return 2*Math.PI*t.number}throw new Error("Unsupported angle type")},Jd=function(e){return 15===e.type&&("deg"===e.unit||"grad"===e.unit||"rad"===e.unit||"turn"===e.unit)},Yd=function(e){switch(e.filter(Td).map((function(e){return e.value})).join(" ")){case"to bottom right":case"to right bottom":case"left top":case"top left":return[jd,jd];case"to top":case"bottom":return Zd(0);case"to bottom left":case"to left bottom":case"right top":case"top right":return[jd,zd];case"to right":case"left":return Zd(90);case"to top left":case"to left top":case"right bottom":case"bottom right":return[zd,zd];case"to bottom":case"top":return Zd(180);case"to top right":case"to right top":case"left bottom":case"bottom left":return[zd,jd];case"to left":case"right":return Zd(270)}return 0},Zd=function(e){return Math.PI*e/180},qd=function(e,t){if(18===t.type){var i=np[t.name];if(void 0===i)throw new Error('Attempting to parse an unsupported color function "'+t.name+'"');return i(e,t.values)}if(5===t.type){if(3===t.value.length){var s=t.value.substring(0,1),r=t.value.substring(1,2),o=t.value.substring(2,3);return tp(parseInt(s+s,16),parseInt(r+r,16),parseInt(o+o,16),1)}if(4===t.value.length){s=t.value.substring(0,1),r=t.value.substring(1,2),o=t.value.substring(2,3);var n=t.value.substring(3,4);return tp(parseInt(s+s,16),parseInt(r+r,16),parseInt(o+o,16),parseInt(n+n,16)/255)}if(6===t.value.length){s=t.value.substring(0,2),r=t.value.substring(2,4),o=t.value.substring(4,6);return tp(parseInt(s,16),parseInt(r,16),parseInt(o,16),1)}if(8===t.value.length){s=t.value.substring(0,2),r=t.value.substring(2,4),o=t.value.substring(4,6),n=t.value.substring(6,8);return tp(parseInt(s,16),parseInt(r,16),parseInt(o,16),parseInt(n,16)/255)}}if(20===t.type){var a=lp[t.value.toUpperCase()];if(void 0!==a)return a}return lp.TRANSPARENT},$d=function(e){return 0==(255&e)},ep=function(e){var t=255&e,i=255&e>>8,s=255&e>>16,r=255&e>>24;return t<255?"rgba("+r+","+s+","+i+","+t/255+")":"rgb("+r+","+s+","+i+")"},tp=function(e,t,i,s){return(e<<24|t<<16|i<<8|Math.round(255*s)<<0)>>>0},ip=function(e,t){if(17===e.type)return e.number;if(16===e.type){var i=3===t?1:255;return 3===t?e.number/100*i:Math.round(e.number/100*i)}return 0},sp=function(e,t){var i=t.filter(kd);if(3===i.length){var s=i.map(ip),r=s[0],o=s[1],n=s[2];return tp(r,o,n,1)}if(4===i.length){var a=i.map(ip),l=(r=a[0],o=a[1],n=a[2],a[3]);return tp(r,o,n,l)}return 0};function rp(e,t,i){return i<0&&(i+=1),i>=1&&(i-=1),i<1/6?(t-e)*i*6+e:i<.5?t:i<2/3?6*(t-e)*(2/3-i)+e:e}var op=function(e,t){var i=t.filter(kd),s=i[0],r=i[1],o=i[2],n=i[3],a=(17===s.type?Zd(s.number):Xd(e,s))/(2*Math.PI),l=Vd(r)?r.number/100:0,A=Vd(o)?o.number/100:0,h=void 0!==n&&Vd(n)?Kd(n,1):1;if(0===l)return tp(255*A,255*A,255*A,1);var c=A<=.5?A*(l+1):A+l-A*l,u=2*A-c,d=rp(u,c,a+1/3),p=rp(u,c,a),f=rp(u,c,a-1/3);return tp(255*d,255*p,255*f,h)},np={hsl:op,hsla:op,rgb:sp,rgba:sp},ap=function(e,t){return qd(e,Id.create(t).parseComponentValue())},lp={ALICEBLUE:4042850303,ANTIQUEWHITE:4209760255,AQUA:16777215,AQUAMARINE:2147472639,AZURE:4043309055,BEIGE:4126530815,BISQUE:4293182719,BLACK:255,BLANCHEDALMOND:4293643775,BLUE:65535,BLUEVIOLET:2318131967,BROWN:2771004159,BURLYWOOD:3736635391,CADETBLUE:1604231423,CHARTREUSE:2147418367,CHOCOLATE:3530104575,CORAL:4286533887,CORNFLOWERBLUE:1687547391,CORNSILK:4294499583,CRIMSON:3692313855,CYAN:16777215,DARKBLUE:35839,DARKCYAN:9145343,DARKGOLDENROD:3095837695,DARKGRAY:2846468607,DARKGREEN:6553855,DARKGREY:2846468607,DARKKHAKI:3182914559,DARKMAGENTA:2332068863,DARKOLIVEGREEN:1433087999,DARKORANGE:4287365375,DARKORCHID:2570243327,DARKRED:2332033279,DARKSALMON:3918953215,DARKSEAGREEN:2411499519,DARKSLATEBLUE:1211993087,DARKSLATEGRAY:793726975,DARKSLATEGREY:793726975,DARKTURQUOISE:13554175,DARKVIOLET:2483082239,DEEPPINK:4279538687,DEEPSKYBLUE:12582911,DIMGRAY:1768516095,DIMGREY:1768516095,DODGERBLUE:512819199,FIREBRICK:2988581631,FLORALWHITE:4294635775,FORESTGREEN:579543807,FUCHSIA:4278255615,GAINSBORO:3705462015,GHOSTWHITE:4177068031,GOLD:4292280575,GOLDENROD:3668254975,GRAY:2155905279,GREEN:8388863,GREENYELLOW:2919182335,GREY:2155905279,HONEYDEW:4043305215,HOTPINK:4285117695,INDIANRED:3445382399,INDIGO:1258324735,IVORY:4294963455,KHAKI:4041641215,LAVENDER:3873897215,LAVENDERBLUSH:4293981695,LAWNGREEN:2096890111,LEMONCHIFFON:4294626815,LIGHTBLUE:2916673279,LIGHTCORAL:4034953471,LIGHTCYAN:3774873599,LIGHTGOLDENRODYELLOW:4210742015,LIGHTGRAY:3553874943,LIGHTGREEN:2431553791,LIGHTGREY:3553874943,LIGHTPINK:4290167295,LIGHTSALMON:4288707327,LIGHTSEAGREEN:548580095,LIGHTSKYBLUE:2278488831,LIGHTSLATEGRAY:2005441023,LIGHTSLATEGREY:2005441023,LIGHTSTEELBLUE:2965692159,LIGHTYELLOW:4294959359,LIME:16711935,LIMEGREEN:852308735,LINEN:4210091775,MAGENTA:4278255615,MAROON:2147483903,MEDIUMAQUAMARINE:1724754687,MEDIUMBLUE:52735,MEDIUMORCHID:3126187007,MEDIUMPURPLE:2473647103,MEDIUMSEAGREEN:1018393087,MEDIUMSLATEBLUE:2070474495,MEDIUMSPRINGGREEN:16423679,MEDIUMTURQUOISE:1221709055,MEDIUMVIOLETRED:3340076543,MIDNIGHTBLUE:421097727,MINTCREAM:4127193855,MISTYROSE:4293190143,MOCCASIN:4293178879,NAVAJOWHITE:4292783615,NAVY:33023,OLDLACE:4260751103,OLIVE:2155872511,OLIVEDRAB:1804477439,ORANGE:4289003775,ORANGERED:4282712319,ORCHID:3664828159,PALEGOLDENROD:4008225535,PALEGREEN:2566625535,PALETURQUOISE:2951671551,PALEVIOLETRED:3681588223,PAPAYAWHIP:4293907967,PEACHPUFF:4292524543,PERU:3448061951,PINK:4290825215,PLUM:3718307327,POWDERBLUE:2967529215,PURPLE:2147516671,REBECCAPURPLE:1714657791,RED:4278190335,ROSYBROWN:3163525119,ROYALBLUE:1097458175,SADDLEBROWN:2336560127,SALMON:4202722047,SANDYBROWN:4104413439,SEAGREEN:780883967,SEASHELL:4294307583,SIENNA:2689740287,SILVER:3233857791,SKYBLUE:2278484991,SLATEBLUE:1784335871,SLATEGRAY:1887473919,SLATEGREY:1887473919,SNOW:4294638335,SPRINGGREEN:16744447,STEELBLUE:1182971135,TAN:3535047935,TEAL:8421631,THISTLE:3636451583,TOMATO:4284696575,TRANSPARENT:0,TURQUOISE:1088475391,VIOLET:4001558271,WHEAT:4125012991,WHITE:4294967295,WHITESMOKE:4126537215,YELLOW:4294902015,YELLOWGREEN:2597139199},Ap={name:"background-clip",initialValue:"border-box",prefix:!1,type:1,parse:function(e,t){return t.map((function(e){if(Td(e))switch(e.value){case"padding-box":return 1;case"content-box":return 2}return 0}))}},hp={name:"background-color",initialValue:"transparent",prefix:!1,type:3,format:"color"},cp=function(e,t){var i=qd(e,t[0]),s=t[1];return s&&Vd(s)?{color:i,stop:s}:{color:i,stop:null}},up=function(e,t){var i=e[0],s=e[e.length-1];null===i.stop&&(i.stop=jd),null===s.stop&&(s.stop=zd);for(var r=[],o=0,n=0;no?r.push(l):r.push(o),o=l}else r.push(null)}var A=null;for(n=0;ne.optimumDistance)?{optimumCorner:t,optimumDistance:a}:e}),{optimumDistance:r?1/0:-1/0,optimumCorner:null}).optimumCorner},gp=function(e,t){var i=Zd(180),s=[];return Od(t).forEach((function(t,r){if(0===r){var o=t[0];if(20===o.type&&-1!==["top","left","right","bottom"].indexOf(o.value))return void(i=Yd(t));if(Jd(o))return void(i=(Xd(e,o)+Zd(270))%Zd(360))}var n=cp(e,t);s.push(n)})),{angle:i,stops:s,type:1}},mp=function(e,t){var i=0,s=3,r=[],o=[];return Od(t).forEach((function(t,n){var a=!0;if(0===n?a=t.reduce((function(e,t){if(Td(t))switch(t.value){case"center":return o.push(Gd),!1;case"top":case"left":return o.push(jd),!1;case"right":case"bottom":return o.push(zd),!1}else if(Vd(t)||Qd(t))return o.push(t),!1;return e}),a):1===n&&(a=t.reduce((function(e,t){if(Td(t))switch(t.value){case"circle":return i=0,!1;case"ellipse":return i=1,!1;case"contain":case"closest-side":return s=0,!1;case"farthest-side":return s=1,!1;case"closest-corner":return s=2,!1;case"cover":case"farthest-corner":return s=3,!1}else if(Qd(t)||Vd(t))return Array.isArray(s)||(s=[]),s.push(t),!1;return e}),a)),a){var l=cp(e,t);r.push(l)}})),{size:s,shape:i,stops:r,position:o,type:2}},_p=function(e,t){if(22===t.type){var i={url:t.value,type:0};return e.cache.addImage(t.value),i}if(18===t.type){var s=bp[t.name];if(void 0===s)throw new Error('Attempting to parse an unsupported image function "'+t.name+'"');return s(e,t.values)}throw new Error("Unsupported image type "+t.type)};var vp,bp={"linear-gradient":function(e,t){var i=Zd(180),s=[];return Od(t).forEach((function(t,r){if(0===r){var o=t[0];if(20===o.type&&"to"===o.value)return void(i=Yd(t));if(Jd(o))return void(i=Xd(e,o))}var n=cp(e,t);s.push(n)})),{angle:i,stops:s,type:1}},"-moz-linear-gradient":gp,"-ms-linear-gradient":gp,"-o-linear-gradient":gp,"-webkit-linear-gradient":gp,"radial-gradient":function(e,t){var i=0,s=3,r=[],o=[];return Od(t).forEach((function(t,n){var a=!0;if(0===n){var l=!1;a=t.reduce((function(e,t){if(l)if(Td(t))switch(t.value){case"center":return o.push(Gd),e;case"top":case"left":return o.push(jd),e;case"right":case"bottom":return o.push(zd),e}else(Vd(t)||Qd(t))&&o.push(t);else if(Td(t))switch(t.value){case"circle":return i=0,!1;case"ellipse":return i=1,!1;case"at":return l=!0,!1;case"closest-side":return s=0,!1;case"cover":case"farthest-side":return s=1,!1;case"contain":case"closest-corner":return s=2,!1;case"farthest-corner":return s=3,!1}else if(Qd(t)||Vd(t))return Array.isArray(s)||(s=[]),s.push(t),!1;return e}),a)}if(a){var A=cp(e,t);r.push(A)}})),{size:s,shape:i,stops:r,position:o,type:2}},"-moz-radial-gradient":mp,"-ms-radial-gradient":mp,"-o-radial-gradient":mp,"-webkit-radial-gradient":mp,"-webkit-gradient":function(e,t){var i=Zd(180),s=[],r=1;return Od(t).forEach((function(t,i){var o=t[0];if(0===i){if(Td(o)&&"linear"===o.value)return void(r=1);if(Td(o)&&"radial"===o.value)return void(r=2)}if(18===o.type)if("from"===o.name){var n=qd(e,o.values[0]);s.push({stop:jd,color:n})}else if("to"===o.name){n=qd(e,o.values[0]);s.push({stop:zd,color:n})}else if("color-stop"===o.name){var a=o.values.filter(kd);if(2===a.length){n=qd(e,a[1]);var l=a[0];Sd(l)&&s.push({stop:{type:16,number:100*l.number,flags:l.flags},color:n})}}})),1===r?{angle:(i+Zd(180))%Zd(360),stops:s,type:r}:{size:3,shape:0,stops:s,position:[],type:r}}},yp={name:"background-image",initialValue:"none",type:1,prefix:!1,parse:function(e,t){if(0===t.length)return[];var i=t[0];return 20===i.type&&"none"===i.value?[]:t.filter((function(e){return kd(e)&&function(e){return!(20===e.type&&"none"===e.value||18===e.type&&!bp[e.name])}(e)})).map((function(t){return _p(e,t)}))}},xp={name:"background-origin",initialValue:"border-box",prefix:!1,type:1,parse:function(e,t){return t.map((function(e){if(Td(e))switch(e.value){case"padding-box":return 1;case"content-box":return 2}return 0}))}},Bp={name:"background-position",initialValue:"0% 0%",type:1,prefix:!1,parse:function(e,t){return Od(t).map((function(e){return e.filter(Vd)})).map(Hd)}},wp={name:"background-repeat",initialValue:"repeat",prefix:!1,type:1,parse:function(e,t){return Od(t).map((function(e){return e.filter(Td).map((function(e){return e.value})).join(" ")})).map(Pp)}},Pp=function(e){switch(e){case"no-repeat":return 1;case"repeat-x":case"repeat no-repeat":return 2;case"repeat-y":case"no-repeat repeat":return 3;default:return 0}};!function(e){e.AUTO="auto",e.CONTAIN="contain",e.COVER="cover"}(vp||(vp={}));var Cp,Mp={name:"background-size",initialValue:"0",prefix:!1,type:1,parse:function(e,t){return Od(t).map((function(e){return e.filter(Ep)}))}},Ep=function(e){return Td(e)||Vd(e)},Fp=function(e){return{name:"border-"+e+"-color",initialValue:"transparent",prefix:!1,type:3,format:"color"}},Ip=Fp("top"),Dp=Fp("right"),Sp=Fp("bottom"),Tp=Fp("left"),Rp=function(e){return{name:"border-radius-"+e,initialValue:"0 0",prefix:!1,type:1,parse:function(e,t){return Hd(t.filter(Vd))}}},Lp=Rp("top-left"),Up=Rp("top-right"),kp=Rp("bottom-right"),Op=Rp("bottom-left"),Np=function(e){return{name:"border-"+e+"-style",initialValue:"solid",prefix:!1,type:2,parse:function(e,t){switch(t){case"none":return 0;case"dashed":return 2;case"dotted":return 3;case"double":return 4}return 1}}},Qp=Np("top"),Vp=Np("right"),Hp=Np("bottom"),jp=Np("left"),Gp=function(e){return{name:"border-"+e+"-width",initialValue:"0",type:0,prefix:!1,parse:function(e,t){return Dd(t)?t.number:0}}},zp=Gp("top"),Wp=Gp("right"),Kp=Gp("bottom"),Xp=Gp("left"),Jp={name:"color",initialValue:"transparent",prefix:!1,type:3,format:"color"},Yp={name:"direction",initialValue:"ltr",prefix:!1,type:2,parse:function(e,t){return"rtl"===t?1:0}},Zp={name:"display",initialValue:"inline-block",prefix:!1,type:1,parse:function(e,t){return t.filter(Td).reduce((function(e,t){return e|qp(t.value)}),0)}},qp=function(e){switch(e){case"block":case"-webkit-box":return 2;case"inline":return 4;case"run-in":return 8;case"flow":return 16;case"flow-root":return 32;case"table":return 64;case"flex":case"-webkit-flex":return 128;case"grid":case"-ms-grid":return 256;case"ruby":return 512;case"subgrid":return 1024;case"list-item":return 2048;case"table-row-group":return 4096;case"table-header-group":return 8192;case"table-footer-group":return 16384;case"table-row":return 32768;case"table-cell":return 65536;case"table-column-group":return 131072;case"table-column":return 262144;case"table-caption":return 524288;case"ruby-base":return 1048576;case"ruby-text":return 2097152;case"ruby-base-container":return 4194304;case"ruby-text-container":return 8388608;case"contents":return 16777216;case"inline-block":return 33554432;case"inline-list-item":return 67108864;case"inline-table":return 134217728;case"inline-flex":return 268435456;case"inline-grid":return 536870912}return 0},$p={name:"float",initialValue:"none",prefix:!1,type:2,parse:function(e,t){switch(t){case"left":return 1;case"right":return 2;case"inline-start":return 3;case"inline-end":return 4}return 0}},ef={name:"letter-spacing",initialValue:"0",prefix:!1,type:0,parse:function(e,t){return 20===t.type&&"normal"===t.value?0:17===t.type||15===t.type?t.number:0}};!function(e){e.NORMAL="normal",e.STRICT="strict"}(Cp||(Cp={}));var tf,sf={name:"line-break",initialValue:"normal",prefix:!1,type:2,parse:function(e,t){return"strict"===t?Cp.STRICT:Cp.NORMAL}},rf={name:"line-height",initialValue:"normal",prefix:!1,type:4},of=function(e,t){return Td(e)&&"normal"===e.value?1.2*t:17===e.type?t*e.number:Vd(e)?Kd(e,t):t},nf={name:"list-style-image",initialValue:"none",type:0,prefix:!1,parse:function(e,t){return 20===t.type&&"none"===t.value?null:_p(e,t)}},af={name:"list-style-position",initialValue:"outside",prefix:!1,type:2,parse:function(e,t){return"inside"===t?0:1}},lf={name:"list-style-type",initialValue:"none",prefix:!1,type:2,parse:function(e,t){switch(t){case"disc":return 0;case"circle":return 1;case"square":return 2;case"decimal":return 3;case"cjk-decimal":return 4;case"decimal-leading-zero":return 5;case"lower-roman":return 6;case"upper-roman":return 7;case"lower-greek":return 8;case"lower-alpha":return 9;case"upper-alpha":return 10;case"arabic-indic":return 11;case"armenian":return 12;case"bengali":return 13;case"cambodian":return 14;case"cjk-earthly-branch":return 15;case"cjk-heavenly-stem":return 16;case"cjk-ideographic":return 17;case"devanagari":return 18;case"ethiopic-numeric":return 19;case"georgian":return 20;case"gujarati":return 21;case"gurmukhi":case"hebrew":return 22;case"hiragana":return 23;case"hiragana-iroha":return 24;case"japanese-formal":return 25;case"japanese-informal":return 26;case"kannada":return 27;case"katakana":return 28;case"katakana-iroha":return 29;case"khmer":return 30;case"korean-hangul-formal":return 31;case"korean-hanja-formal":return 32;case"korean-hanja-informal":return 33;case"lao":return 34;case"lower-armenian":return 35;case"malayalam":return 36;case"mongolian":return 37;case"myanmar":return 38;case"oriya":return 39;case"persian":return 40;case"simp-chinese-formal":return 41;case"simp-chinese-informal":return 42;case"tamil":return 43;case"telugu":return 44;case"thai":return 45;case"tibetan":return 46;case"trad-chinese-formal":return 47;case"trad-chinese-informal":return 48;case"upper-armenian":return 49;case"disclosure-open":return 50;case"disclosure-closed":return 51;default:return-1}}},Af=function(e){return{name:"margin-"+e,initialValue:"0",prefix:!1,type:4}},hf=Af("top"),cf=Af("right"),uf=Af("bottom"),df=Af("left"),pf={name:"overflow",initialValue:"visible",prefix:!1,type:1,parse:function(e,t){return t.filter(Td).map((function(e){switch(e.value){case"hidden":return 1;case"scroll":return 2;case"clip":return 3;case"auto":return 4;default:return 0}}))}},ff={name:"overflow-wrap",initialValue:"normal",prefix:!1,type:2,parse:function(e,t){return"break-word"===t?"break-word":"normal"}},gf=function(e){return{name:"padding-"+e,initialValue:"0",prefix:!1,type:3,format:"length-percentage"}},mf=gf("top"),_f=gf("right"),vf=gf("bottom"),bf=gf("left"),yf={name:"text-align",initialValue:"left",prefix:!1,type:2,parse:function(e,t){switch(t){case"right":return 2;case"center":case"justify":return 1;default:return 0}}},xf={name:"position",initialValue:"static",prefix:!1,type:2,parse:function(e,t){switch(t){case"relative":return 1;case"absolute":return 2;case"fixed":return 3;case"sticky":return 4}return 0}},Bf={name:"text-shadow",initialValue:"none",type:1,prefix:!1,parse:function(e,t){return 1===t.length&&Ld(t[0],"none")?[]:Od(t).map((function(t){for(var i={color:lp.TRANSPARENT,offsetX:jd,offsetY:jd,blur:jd},s=0,r=0;r1?1:0],this.overflowWrap=ig(e,ff,t.overflowWrap),this.paddingTop=ig(e,mf,t.paddingTop),this.paddingRight=ig(e,_f,t.paddingRight),this.paddingBottom=ig(e,vf,t.paddingBottom),this.paddingLeft=ig(e,bf,t.paddingLeft),this.paintOrder=ig(e,Yf,t.paintOrder),this.position=ig(e,xf,t.position),this.textAlign=ig(e,yf,t.textAlign),this.textDecorationColor=ig(e,Lf,null!==(i=t.textDecorationColor)&&void 0!==i?i:t.color),this.textDecorationLine=ig(e,Uf,null!==(s=t.textDecorationLine)&&void 0!==s?s:t.textDecoration),this.textShadow=ig(e,Bf,t.textShadow),this.textTransform=ig(e,wf,t.textTransform),this.transform=ig(e,Pf,t.transform),this.transformOrigin=ig(e,Ff,t.transformOrigin),this.visibility=ig(e,If,t.visibility),this.webkitTextStrokeColor=ig(e,Zf,t.webkitTextStrokeColor),this.webkitTextStrokeWidth=ig(e,qf,t.webkitTextStrokeWidth),this.wordBreak=ig(e,Df,t.wordBreak),this.zIndex=ig(e,Sf,t.zIndex)}return e.prototype.isVisible=function(){return this.display>0&&this.opacity>0&&0===this.visibility},e.prototype.isTransparent=function(){return $d(this.backgroundColor)},e.prototype.isTransformed=function(){return null!==this.transform},e.prototype.isPositioned=function(){return 0!==this.position},e.prototype.isPositionedWithZIndex=function(){return this.isPositioned()&&!this.zIndex.auto},e.prototype.isFloating=function(){return 0!==this.float},e.prototype.isInlineLevel=function(){return Hf(this.display,4)||Hf(this.display,33554432)||Hf(this.display,268435456)||Hf(this.display,536870912)||Hf(this.display,67108864)||Hf(this.display,134217728)},e}(),eg=function(e,t){this.content=ig(e,jf,t.content),this.quotes=ig(e,Kf,t.quotes)},tg=function(e,t){this.counterIncrement=ig(e,Gf,t.counterIncrement),this.counterReset=ig(e,zf,t.counterReset)},ig=function(e,t,i){var s=new Fd,r=null!=i?i.toString():t.initialValue;s.write(r);var o=new Id(s.read());switch(t.type){case 2:var n=o.parseComponentValue();return t.parse(e,Td(n)?n.value:t.initialValue);case 0:return t.parse(e,o.parseComponentValue());case 1:return t.parse(e,o.parseComponentValues());case 4:return o.parseComponentValue();case 3:switch(t.format){case"angle":return Xd(e,o.parseComponentValue());case"color":return qd(e,o.parseComponentValue());case"image":return _p(e,o.parseComponentValue());case"length":var a=o.parseComponentValue();return Qd(a)?a:jd;case"length-percentage":var l=o.parseComponentValue();return Vd(l)?l:jd;case"time":return Tf(e,o.parseComponentValue())}}},sg=function(e,t){var i=function(e){switch(e.getAttribute("data-html2canvas-debug")){case"all":return 1;case"clone":return 2;case"parse":return 3;case"render":return 4;default:return 0}}(e);return 1===i||t===i},rg=function(e,t){this.context=e,this.textNodes=[],this.elements=[],this.flags=0,sg(t,3),this.styles=new $f(e,window.getComputedStyle(t,null)),rm(t)&&(this.styles.animationDuration.some((function(e){return e>0}))&&(t.style.animationDuration="0s"),null!==this.styles.transform&&(t.style.transform="none")),this.bounds=eu(this.context,t),sg(t,4)&&(this.flags|=16)},og="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ng="undefined"==typeof Uint8Array?[]:new Uint8Array(256),ag=0;ag=0){if(e<55296||e>56319&&e<=65535)return t=((t=this.index[e>>5])<<2)+(31&e),this.data[t];if(e<=65535)return t=((t=this.index[2048+(e-55296>>5)])<<2)+(31&e),this.data[t];if(e>11),t=this.index[t],t+=e>>5&63,t=((t=this.index[t])<<2)+(31&e),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},e}(),hg="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",cg="undefined"==typeof Uint8Array?[]:new Uint8Array(256),ug=0;ug>10),n%1024+56320)),(r+1===i||s.length>16384)&&(o+=String.fromCharCode.apply(String,s),s.length=0)}return o},vg=function(e,t){var i,s,r,o=function(e){var t,i,s,r,o,n=.75*e.length,a=e.length,l=0;"="===e[e.length-1]&&(n--,"="===e[e.length-2]&&n--);var A="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&void 0!==Uint8Array.prototype.slice?new ArrayBuffer(n):new Array(n),h=Array.isArray(A)?A:new Uint8Array(A);for(t=0;t>4,h[l++]=(15&s)<<4|r>>2,h[l++]=(3&r)<<6|63&o;return A}(e),n=Array.isArray(o)?function(e){for(var t=e.length,i=[],s=0;s=55296&&r<=56319&&i=i)return{done:!0,value:null};for(var e="×";sn.x||r.y>n.y;return n=r,0===t||a}));return e.body.removeChild(t),a}(document);return Object.defineProperty(Cg,"SUPPORT_WORD_BREAKING",{value:e}),e},get SUPPORT_SVG_DRAWING(){var e=function(e){var t=new Image,i=e.createElement("canvas"),s=i.getContext("2d");if(!s)return!1;t.src="data:image/svg+xml,";try{s.drawImage(t,0,0),i.toDataURL()}catch(e){return!1}return!0}(document);return Object.defineProperty(Cg,"SUPPORT_SVG_DRAWING",{value:e}),e},get SUPPORT_FOREIGNOBJECT_DRAWING(){var e="function"==typeof Array.from&&"function"==typeof window.fetch?function(e){var t=e.createElement("canvas"),i=100;t.width=i,t.height=i;var s=t.getContext("2d");if(!s)return Promise.reject(!1);s.fillStyle="rgb(0, 255, 0)",s.fillRect(0,0,i,i);var r=new Image,o=t.toDataURL();r.src=o;var n=wg(i,i,0,0,r);return s.fillStyle="red",s.fillRect(0,0,i,i),Pg(n).then((function(t){s.drawImage(t,0,0);var r=s.getImageData(0,0,i,i).data;s.fillStyle="red",s.fillRect(0,0,i,i);var n=e.createElement("div");return n.style.backgroundImage="url("+o+")",n.style.height="100px",Bg(r)?Pg(wg(i,i,0,0,n)):Promise.reject(!1)})).then((function(e){return s.drawImage(e,0,0),Bg(s.getImageData(0,0,i,i).data)})).catch((function(){return!1}))}(document):Promise.resolve(!1);return Object.defineProperty(Cg,"SUPPORT_FOREIGNOBJECT_DRAWING",{value:e}),e},get SUPPORT_CORS_IMAGES(){var e=void 0!==(new Image).crossOrigin;return Object.defineProperty(Cg,"SUPPORT_CORS_IMAGES",{value:e}),e},get SUPPORT_RESPONSE_TYPE(){var e="string"==typeof(new XMLHttpRequest).responseType;return Object.defineProperty(Cg,"SUPPORT_RESPONSE_TYPE",{value:e}),e},get SUPPORT_CORS_XHR(){var e="withCredentials"in new XMLHttpRequest;return Object.defineProperty(Cg,"SUPPORT_CORS_XHR",{value:e}),e},get SUPPORT_NATIVE_TEXT_SEGMENTATION(){var e=!("undefined"==typeof Intl||!Intl.Segmenter);return Object.defineProperty(Cg,"SUPPORT_NATIVE_TEXT_SEGMENTATION",{value:e}),e}},Mg=function(e,t){this.text=e,this.bounds=t},Eg=function(e,t){var i=t.ownerDocument;if(i){var s=i.createElement("html2canvaswrapper");s.appendChild(t.cloneNode(!0));var r=t.parentNode;if(r){r.replaceChild(s,t);var o=eu(e,s);return s.firstChild&&r.replaceChild(s.firstChild,s),o}}return $c.EMPTY},Fg=function(e,t,i){var s=e.ownerDocument;if(!s)throw new Error("Node has no owner document");var r=s.createRange();return r.setStart(e,t),r.setEnd(e,t+i),r},Ig=function(e){if(Cg.SUPPORT_NATIVE_TEXT_SEGMENTATION){var t=new Intl.Segmenter(void 0,{granularity:"grapheme"});return Array.from(t.segment(e)).map((function(e){return e.segment}))}return function(e){for(var t,i=xg(e),s=[];!(t=i.next()).done;)t.value&&s.push(t.value.slice());return s}(e)},Dg=function(e,t){return 0!==t.letterSpacing?Ig(e):function(e,t){if(Cg.SUPPORT_NATIVE_TEXT_SEGMENTATION){var i=new Intl.Segmenter(void 0,{granularity:"word"});return Array.from(i.segment(e)).map((function(e){return e.segment}))}return Tg(e,t)}(e,t)},Sg=[32,160,4961,65792,65793,4153,4241],Tg=function(e,t){for(var i,s=function(e,t){var i=tu(e),s=Yu(i,t),r=s[0],o=s[1],n=s[2],a=i.length,l=0,A=0;return{next:function(){if(A>=a)return{done:!0,value:null};for(var e="×";A0)if(Cg.SUPPORT_RANGE_BOUNDS){var r=Fg(s,n,t.length).getClientRects();if(r.length>1){var a=Ig(t),l=0;a.forEach((function(t){o.push(new Mg(t,$c.fromDOMRectList(e,Fg(s,l+n,t.length).getClientRects()))),l+=t.length}))}else o.push(new Mg(t,$c.fromDOMRectList(e,r)))}else{var A=s.splitText(t.length);o.push(new Mg(t,Eg(e,s))),s=A}else Cg.SUPPORT_RANGE_BOUNDS||(s=s.splitText(t.length));n+=t.length})),o}(e,this.text,i,t)},Lg=function(e,t){switch(t){case 1:return e.toLowerCase();case 3:return e.replace(Ug,kg);case 2:return e.toUpperCase();default:return e}},Ug=/(^|\s|:|-|\(|\))([a-z])/g,kg=function(e,t,i){return e.length>0?t+i.toUpperCase():e},Og=function(e){function t(t,i){var s=e.call(this,t,i)||this;return s.src=i.currentSrc||i.src,s.intrinsicWidth=i.naturalWidth,s.intrinsicHeight=i.naturalHeight,s.context.cache.addImage(s.src),s}return Xc(t,e),t}(rg),Ng=function(e){function t(t,i){var s=e.call(this,t,i)||this;return s.canvas=i,s.intrinsicWidth=i.width,s.intrinsicHeight=i.height,s}return Xc(t,e),t}(rg),Qg=function(e){function t(t,i){var s=e.call(this,t,i)||this,r=new XMLSerializer,o=eu(t,i);return i.setAttribute("width",o.width+"px"),i.setAttribute("height",o.height+"px"),s.svg="data:image/svg+xml,"+encodeURIComponent(r.serializeToString(i)),s.intrinsicWidth=i.width.baseVal.value,s.intrinsicHeight=i.height.baseVal.value,s.context.cache.addImage(s.svg),s}return Xc(t,e),t}(rg),Vg=function(e){function t(t,i){var s=e.call(this,t,i)||this;return s.value=i.value,s}return Xc(t,e),t}(rg),Hg=function(e){function t(t,i){var s=e.call(this,t,i)||this;return s.start=i.start,s.reversed="boolean"==typeof i.reversed&&!0===i.reversed,s}return Xc(t,e),t}(rg),jg=[{type:15,flags:0,unit:"px",number:3}],Gg=[{type:16,flags:0,number:50}],zg="password",Wg=function(e){function t(t,i){var s,r=e.call(this,t,i)||this;switch(r.type=i.type.toLowerCase(),r.checked=i.checked,r.value=function(e){var t=e.type===zg?new Array(e.value.length+1).join("•"):e.value;return 0===t.length?e.placeholder||"":t}(i),"checkbox"!==r.type&&"radio"!==r.type||(r.styles.backgroundColor=3739148031,r.styles.borderTopColor=r.styles.borderRightColor=r.styles.borderBottomColor=r.styles.borderLeftColor=2779096575,r.styles.borderTopWidth=r.styles.borderRightWidth=r.styles.borderBottomWidth=r.styles.borderLeftWidth=1,r.styles.borderTopStyle=r.styles.borderRightStyle=r.styles.borderBottomStyle=r.styles.borderLeftStyle=1,r.styles.backgroundClip=[0],r.styles.backgroundOrigin=[0],r.bounds=(s=r.bounds).width>s.height?new $c(s.left+(s.width-s.height)/2,s.top,s.height,s.height):s.width0)i.textNodes.push(new Rg(e,r,i.styles));else if(sm(r))if(_m(r)&&r.assignedNodes)r.assignedNodes().forEach((function(t){return Zg(e,t,i,s)}));else{var n=qg(e,r);n.styles.isVisible()&&(em(r,n,s)?n.flags|=4:tm(n.styles)&&(n.flags|=2),-1!==Yg.indexOf(r.tagName)&&(n.flags|=8),i.elements.push(n),r.slot,r.shadowRoot?Zg(e,r.shadowRoot,n,s):gm(r)||Am(r)||mm(r)||Zg(e,r,n,s))}},qg=function(e,t){return dm(t)?new Og(e,t):cm(t)?new Ng(e,t):Am(t)?new Qg(e,t):nm(t)?new Vg(e,t):am(t)?new Hg(e,t):lm(t)?new Wg(e,t):mm(t)?new Kg(e,t):gm(t)?new Xg(e,t):pm(t)?new Jg(e,t):new rg(e,t)},$g=function(e,t){var i=qg(e,t);return i.flags|=4,Zg(e,t,i,i),i},em=function(e,t,i){return t.styles.isPositionedWithZIndex()||t.styles.opacity<1||t.styles.isTransformed()||hm(e)&&i.styles.isTransparent()},tm=function(e){return e.isPositioned()||e.isFloating()},im=function(e){return e.nodeType===Node.TEXT_NODE},sm=function(e){return e.nodeType===Node.ELEMENT_NODE},rm=function(e){return sm(e)&&void 0!==e.style&&!om(e)},om=function(e){return"object"==typeof e.className},nm=function(e){return"LI"===e.tagName},am=function(e){return"OL"===e.tagName},lm=function(e){return"INPUT"===e.tagName},Am=function(e){return"svg"===e.tagName},hm=function(e){return"BODY"===e.tagName},cm=function(e){return"CANVAS"===e.tagName},um=function(e){return"VIDEO"===e.tagName},dm=function(e){return"IMG"===e.tagName},pm=function(e){return"IFRAME"===e.tagName},fm=function(e){return"STYLE"===e.tagName},gm=function(e){return"TEXTAREA"===e.tagName},mm=function(e){return"SELECT"===e.tagName},_m=function(e){return"SLOT"===e.tagName},vm=function(e){return e.tagName.indexOf("-")>0},bm=function(){function e(){this.counters={}}return e.prototype.getCounterValue=function(e){var t=this.counters[e];return t&&t.length?t[t.length-1]:1},e.prototype.getCounterValues=function(e){var t=this.counters[e];return t||[]},e.prototype.pop=function(e){var t=this;e.forEach((function(e){return t.counters[e].pop()}))},e.prototype.parse=function(e){var t=this,i=e.counterIncrement,s=e.counterReset,r=!0;null!==i&&i.forEach((function(e){var i=t.counters[e.counter];i&&0!==e.increment&&(r=!1,i.length||i.push(1),i[Math.max(0,i.length-1)]+=e.increment)}));var o=[];return r&&s.forEach((function(e){var i=t.counters[e.counter];o.push(e.counter),i||(i=t.counters[e.counter]=[]),i.push(e.reset)})),o},e}(),ym={integers:[1e3,900,500,400,100,90,50,40,10,9,5,4,1],values:["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]},xm={integers:[9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],values:["Ք","Փ","Ւ","Ց","Ր","Տ","Վ","Ս","Ռ","Ջ","Պ","Չ","Ո","Շ","Ն","Յ","Մ","Ճ","Ղ","Ձ","Հ","Կ","Ծ","Խ","Լ","Ի","Ժ","Թ","Ը","Է","Զ","Ե","Դ","Գ","Բ","Ա"]},Bm={integers:[1e4,9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,400,300,200,100,90,80,70,60,50,40,30,20,19,18,17,16,15,10,9,8,7,6,5,4,3,2,1],values:["י׳","ט׳","ח׳","ז׳","ו׳","ה׳","ד׳","ג׳","ב׳","א׳","ת","ש","ר","ק","צ","פ","ע","ס","נ","מ","ל","כ","יט","יח","יז","טז","טו","י","ט","ח","ז","ו","ה","ד","ג","ב","א"]},wm={integers:[1e4,9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],values:["ჵ","ჰ","ჯ","ჴ","ხ","ჭ","წ","ძ","ც","ჩ","შ","ყ","ღ","ქ","ფ","ჳ","ტ","ს","რ","ჟ","პ","ო","ჲ","ნ","მ","ლ","კ","ი","თ","ჱ","ზ","ვ","ე","დ","გ","ბ","ა"]},Pm=function(e,t,i,s,r,o){return ei?Im(e,r,o.length>0):s.integers.reduce((function(t,i,r){for(;e>=i;)e-=i,t+=s.values[r];return t}),"")+o},Cm=function(e,t,i,s){var r="";do{i||e--,r=s(e)+r,e/=t}while(e*t>=t);return r},Mm=function(e,t,i,s,r){var o=i-t+1;return(e<0?"-":"")+(Cm(Math.abs(e),o,s,(function(e){return iu(Math.floor(e%o)+t)}))+r)},Em=function(e,t,i){void 0===i&&(i=". ");var s=t.length;return Cm(Math.abs(e),s,!1,(function(e){return t[Math.floor(e%s)]}))+i},Fm=function(e,t,i,s,r,o){if(e<-9999||e>9999)return Im(e,4,r.length>0);var n=Math.abs(e),a=r;if(0===n)return t[0]+a;for(var l=0;n>0&&l<=4;l++){var A=n%10;0===A&&Hf(o,1)&&""!==a?a=t[A]+a:A>1||1===A&&0===l||1===A&&1===l&&Hf(o,2)||1===A&&1===l&&Hf(o,4)&&e>100||1===A&&l>1&&Hf(o,8)?a=t[A]+(l>0?i[l-1]:"")+a:1===A&&l>0&&(a=i[l-1]+a),n=Math.floor(n/10)}return(e<0?s:"")+a},Im=function(e,t,i){var s=i?". ":"",r=i?"、":"",o=i?", ":"",n=i?" ":"";switch(t){case 0:return"•"+n;case 1:return"◦"+n;case 2:return"◾"+n;case 5:var a=Mm(e,48,57,!0,s);return a.length<4?"0"+a:a;case 4:return Em(e,"〇一二三四五六七八九",r);case 6:return Pm(e,1,3999,ym,3,s).toLowerCase();case 7:return Pm(e,1,3999,ym,3,s);case 8:return Mm(e,945,969,!1,s);case 9:return Mm(e,97,122,!1,s);case 10:return Mm(e,65,90,!1,s);case 11:return Mm(e,1632,1641,!0,s);case 12:case 49:return Pm(e,1,9999,xm,3,s);case 35:return Pm(e,1,9999,xm,3,s).toLowerCase();case 13:return Mm(e,2534,2543,!0,s);case 14:case 30:return Mm(e,6112,6121,!0,s);case 15:return Em(e,"子丑寅卯辰巳午未申酉戌亥",r);case 16:return Em(e,"甲乙丙丁戊己庚辛壬癸",r);case 17:case 48:return Fm(e,"零一二三四五六七八九","十百千萬","負",r,14);case 47:return Fm(e,"零壹貳參肆伍陸柒捌玖","拾佰仟萬","負",r,15);case 42:return Fm(e,"零一二三四五六七八九","十百千萬","负",r,14);case 41:return Fm(e,"零壹贰叁肆伍陆柒捌玖","拾佰仟萬","负",r,15);case 26:return Fm(e,"〇一二三四五六七八九","十百千万","マイナス",r,0);case 25:return Fm(e,"零壱弐参四伍六七八九","拾百千万","マイナス",r,7);case 31:return Fm(e,"영일이삼사오육칠팔구","십백천만","마이너스",o,7);case 33:return Fm(e,"零一二三四五六七八九","十百千萬","마이너스",o,0);case 32:return Fm(e,"零壹貳參四五六七八九","拾百千","마이너스",o,7);case 18:return Mm(e,2406,2415,!0,s);case 20:return Pm(e,1,19999,wm,3,s);case 21:return Mm(e,2790,2799,!0,s);case 22:return Mm(e,2662,2671,!0,s);case 22:return Pm(e,1,10999,Bm,3,s);case 23:return Em(e,"あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわゐゑをん");case 24:return Em(e,"いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす");case 27:return Mm(e,3302,3311,!0,s);case 28:return Em(e,"アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヰヱヲン",r);case 29:return Em(e,"イロハニホヘトチリヌルヲワカヨタレソツネナラムウヰノオクヤマケフコエテアサキユメミシヱヒモセス",r);case 34:return Mm(e,3792,3801,!0,s);case 37:return Mm(e,6160,6169,!0,s);case 38:return Mm(e,4160,4169,!0,s);case 39:return Mm(e,2918,2927,!0,s);case 40:return Mm(e,1776,1785,!0,s);case 43:return Mm(e,3046,3055,!0,s);case 44:return Mm(e,3174,3183,!0,s);case 45:return Mm(e,3664,3673,!0,s);case 46:return Mm(e,3872,3881,!0,s);default:return Mm(e,48,57,!0,s)}},Dm=function(){function e(e,t,i){if(this.context=e,this.options=i,this.scrolledElements=[],this.referenceElement=t,this.counters=new bm,this.quoteDepth=0,!t.ownerDocument)throw new Error("Cloned element does not have an owner document");this.documentElement=this.cloneNode(t.ownerDocument.documentElement,!1)}return e.prototype.toIFrame=function(e,t){var i=this,s=Tm(e,t);if(!s.contentWindow)return Promise.reject("Unable to find iframe window");var r=e.defaultView.pageXOffset,o=e.defaultView.pageYOffset,n=s.contentWindow,a=n.document,l=Um(s).then((function(){return Yc(i,void 0,void 0,(function(){var e,i;return Zc(this,(function(r){switch(r.label){case 0:return this.scrolledElements.forEach(Vm),n&&(n.scrollTo(t.left,t.top),!/(iPad|iPhone|iPod)/g.test(navigator.userAgent)||n.scrollY===t.top&&n.scrollX===t.left||(this.context.logger.warn("Unable to restore scroll position for cloned document"),this.context.windowBounds=this.context.windowBounds.add(n.scrollX-t.left,n.scrollY-t.top,0,0))),e=this.options.onclone,void 0===(i=this.clonedReferenceElement)?[2,Promise.reject("Error finding the "+this.referenceElement.nodeName+" in the cloned document")]:a.fonts&&a.fonts.ready?[4,a.fonts.ready]:[3,2];case 1:r.sent(),r.label=2;case 2:return/(AppleWebKit)/g.test(navigator.userAgent)?[4,Lm(a)]:[3,4];case 3:r.sent(),r.label=4;case 4:return"function"==typeof e?[2,Promise.resolve().then((function(){return e(a,i)})).then((function(){return s}))]:[2,s]}}))}))}));return a.open(),a.write(Nm(document.doctype)+""),Qm(this.referenceElement.ownerDocument,r,o),a.replaceChild(a.adoptNode(this.documentElement),a.documentElement),a.close(),l},e.prototype.createElementClone=function(e){if(sg(e,2),cm(e))return this.createCanvasClone(e);if(um(e))return this.createVideoClone(e);if(fm(e))return this.createStyleClone(e);var t=e.cloneNode(!1);return dm(t)&&(dm(e)&&e.currentSrc&&e.currentSrc!==e.src&&(t.src=e.currentSrc,t.srcset=""),"lazy"===t.loading&&(t.loading="eager")),vm(t)?this.createCustomElementClone(t):t},e.prototype.createCustomElementClone=function(e){var t=document.createElement("html2canvascustomelement");return Om(e.style,t),t},e.prototype.createStyleClone=function(e){try{var t=e.sheet;if(t&&t.cssRules){var i=[].slice.call(t.cssRules,0).reduce((function(e,t){return t&&"string"==typeof t.cssText?e+t.cssText:e}),""),s=e.cloneNode(!1);return s.textContent=i,s}}catch(e){if(this.context.logger.error("Unable to access cssRules property",e),"SecurityError"!==e.name)throw e}return e.cloneNode(!1)},e.prototype.createCanvasClone=function(e){var t;if(this.options.inlineImages&&e.ownerDocument){var i=e.ownerDocument.createElement("img");try{return i.src=e.toDataURL(),i}catch(t){this.context.logger.info("Unable to inline canvas contents, canvas is tainted",e)}}var s=e.cloneNode(!1);try{s.width=e.width,s.height=e.height;var r=e.getContext("2d"),o=s.getContext("2d");if(o)if(!this.options.allowTaint&&r)o.putImageData(r.getImageData(0,0,e.width,e.height),0,0);else{var n=null!==(t=e.getContext("webgl2"))&&void 0!==t?t:e.getContext("webgl");if(n){var a=n.getContextAttributes();!1===(null==a?void 0:a.preserveDrawingBuffer)&&this.context.logger.warn("Unable to clone WebGL context as it has preserveDrawingBuffer=false",e)}o.drawImage(e,0,0)}return s}catch(t){this.context.logger.info("Unable to clone canvas as it is tainted",e)}return s},e.prototype.createVideoClone=function(e){var t=e.ownerDocument.createElement("canvas");t.width=e.offsetWidth,t.height=e.offsetHeight;var i=t.getContext("2d");try{return i&&(i.drawImage(e,0,0,t.width,t.height),this.options.allowTaint||i.getImageData(0,0,t.width,t.height)),t}catch(t){this.context.logger.info("Unable to clone video as it is tainted",e)}var s=e.ownerDocument.createElement("canvas");return s.width=e.offsetWidth,s.height=e.offsetHeight,s},e.prototype.appendChildNode=function(e,t,i){sm(t)&&(function(e){return"SCRIPT"===e.tagName}(t)||t.hasAttribute("data-html2canvas-ignore")||"function"==typeof this.options.ignoreElements&&this.options.ignoreElements(t))||this.options.copyStyles&&sm(t)&&fm(t)||e.appendChild(this.cloneNode(t,i))},e.prototype.cloneChildNodes=function(e,t,i){for(var s=this,r=e.shadowRoot?e.shadowRoot.firstChild:e.firstChild;r;r=r.nextSibling)if(sm(r)&&_m(r)&&"function"==typeof r.assignedNodes){var o=r.assignedNodes();o.length&&o.forEach((function(e){return s.appendChildNode(t,e,i)}))}else this.appendChildNode(t,r,i)},e.prototype.cloneNode=function(e,t){if(im(e))return document.createTextNode(e.data);if(!e.ownerDocument)return e.cloneNode(!1);var i=e.ownerDocument.defaultView;if(i&&sm(e)&&(rm(e)||om(e))){var s=this.createElementClone(e);s.style.transitionProperty="none";var r=i.getComputedStyle(e),o=i.getComputedStyle(e,":before"),n=i.getComputedStyle(e,":after");this.referenceElement===e&&rm(s)&&(this.clonedReferenceElement=s),hm(s)&&Gm(s);var a=this.counters.parse(new tg(this.context,r)),l=this.resolvePseudoContent(e,s,o,dg.BEFORE);vm(e)&&(t=!0),um(e)||this.cloneChildNodes(e,s,t),l&&s.insertBefore(l,s.firstChild);var A=this.resolvePseudoContent(e,s,n,dg.AFTER);return A&&s.appendChild(A),this.counters.pop(a),(r&&(this.options.copyStyles||om(e))&&!pm(e)||t)&&Om(r,s),0===e.scrollTop&&0===e.scrollLeft||this.scrolledElements.push([s,e.scrollLeft,e.scrollTop]),(gm(e)||mm(e))&&(gm(s)||mm(s))&&(s.value=e.value),s}return e.cloneNode(!1)},e.prototype.resolvePseudoContent=function(e,t,i,s){var r=this;if(i){var o=i.content,n=t.ownerDocument;if(n&&o&&"none"!==o&&"-moz-alt-content"!==o&&"none"!==i.display){this.counters.parse(new tg(this.context,i));var a=new eg(this.context,i),l=n.createElement("html2canvaspseudoelement");Om(i,l),a.content.forEach((function(t){if(0===t.type)l.appendChild(n.createTextNode(t.value));else if(22===t.type){var i=n.createElement("img");i.src=t.value,i.style.opacity="1",l.appendChild(i)}else if(18===t.type){if("attr"===t.name){var s=t.values.filter(Td);s.length&&l.appendChild(n.createTextNode(e.getAttribute(s[0].value)||""))}else if("counter"===t.name){var o=t.values.filter(kd),A=o[0],h=o[1];if(A&&Td(A)){var c=r.counters.getCounterValue(A.value),u=h&&Td(h)?lf.parse(r.context,h.value):3;l.appendChild(n.createTextNode(Im(c,u,!1)))}}else if("counters"===t.name){var d=t.values.filter(kd),p=(A=d[0],d[1]);h=d[2];if(A&&Td(A)){var f=r.counters.getCounterValues(A.value),g=h&&Td(h)?lf.parse(r.context,h.value):3,m=p&&0===p.type?p.value:"",_=f.map((function(e){return Im(e,g,!1)})).join(m);l.appendChild(n.createTextNode(_))}}}else if(20===t.type)switch(t.value){case"open-quote":l.appendChild(n.createTextNode(Xf(a.quotes,r.quoteDepth++,!0)));break;case"close-quote":l.appendChild(n.createTextNode(Xf(a.quotes,--r.quoteDepth,!1)));break;default:l.appendChild(n.createTextNode(t.value))}})),l.className=Hm+" "+jm;var A=s===dg.BEFORE?" "+Hm:" "+jm;return om(t)?t.className.baseValue+=A:t.className+=A,l}}},e.destroy=function(e){return!!e.parentNode&&(e.parentNode.removeChild(e),!0)},e}();!function(e){e[e.BEFORE=0]="BEFORE",e[e.AFTER=1]="AFTER"}(dg||(dg={}));var Sm,Tm=function(e,t){var i=e.createElement("iframe");return i.className="html2canvas-container",i.style.visibility="hidden",i.style.position="fixed",i.style.left="-10000px",i.style.top="0px",i.style.border="0",i.width=t.width.toString(),i.height=t.height.toString(),i.scrolling="no",i.setAttribute("data-html2canvas-ignore","true"),e.body.appendChild(i),i},Rm=function(e){return new Promise((function(t){e.complete?t():e.src?(e.onload=t,e.onerror=t):t()}))},Lm=function(e){return Promise.all([].slice.call(e.images,0).map(Rm))},Um=function(e){return new Promise((function(t,i){var s=e.contentWindow;if(!s)return i("No window assigned for iframe");var r=s.document;s.onload=e.onload=function(){s.onload=e.onload=null;var i=setInterval((function(){r.body.childNodes.length>0&&"complete"===r.readyState&&(clearInterval(i),t(e))}),50)}}))},km=["all","d","content"],Om=function(e,t){for(var i=e.length-1;i>=0;i--){var s=e.item(i);-1===km.indexOf(s)&&t.style.setProperty(s,e.getPropertyValue(s))}return t},Nm=function(e){var t="";return e&&(t+=""),t},Qm=function(e,t,i){e&&e.defaultView&&(t!==e.defaultView.pageXOffset||i!==e.defaultView.pageYOffset)&&e.defaultView.scrollTo(t,i)},Vm=function(e){var t=e[0],i=e[1],s=e[2];t.scrollLeft=i,t.scrollTop=s},Hm="___html2canvas___pseudoelement_before",jm="___html2canvas___pseudoelement_after",Gm=function(e){zm(e,"."+Hm+':before{\n content: "" !important;\n display: none !important;\n}\n .'+jm+':after{\n content: "" !important;\n display: none !important;\n}')},zm=function(e,t){var i=e.ownerDocument;if(i){var s=i.createElement("style");s.textContent=t,e.appendChild(s)}},Wm=function(){function e(){}return e.getOrigin=function(t){var i=e._link;return i?(i.href=t,i.href=i.href,i.protocol+i.hostname+i.port):"about:blank"},e.isSameOrigin=function(t){return e.getOrigin(t)===e._origin},e.setContext=function(t){e._link=t.document.createElement("a"),e._origin=e.getOrigin(t.location.href)},e._origin="about:blank",e}(),Km=function(){function e(e,t){this.context=e,this._options=t,this._cache={}}return e.prototype.addImage=function(e){var t=Promise.resolve();return this.has(e)?t:e_(e)||Zm(e)?((this._cache[e]=this.loadImage(e)).catch((function(){})),t):t},e.prototype.match=function(e){return this._cache[e]},e.prototype.loadImage=function(e){return Yc(this,void 0,void 0,(function(){var t,i,s,r,o=this;return Zc(this,(function(n){switch(n.label){case 0:return t=Wm.isSameOrigin(e),i=!qm(e)&&!0===this._options.useCORS&&Cg.SUPPORT_CORS_IMAGES&&!t,s=!qm(e)&&!t&&!e_(e)&&"string"==typeof this._options.proxy&&Cg.SUPPORT_CORS_XHR&&!i,t||!1!==this._options.allowTaint||qm(e)||e_(e)||s||i?(r=e,s?[4,this.proxy(r)]:[3,2]):[2];case 1:r=n.sent(),n.label=2;case 2:return this.context.logger.debug("Added image "+e.substring(0,256)),[4,new Promise((function(e,t){var s=new Image;s.onload=function(){return e(s)},s.onerror=t,($m(r)||i)&&(s.crossOrigin="anonymous"),s.src=r,!0===s.complete&&setTimeout((function(){return e(s)}),500),o._options.imageTimeout>0&&setTimeout((function(){return t("Timed out ("+o._options.imageTimeout+"ms) loading image")}),o._options.imageTimeout)}))];case 3:return[2,n.sent()]}}))}))},e.prototype.has=function(e){return void 0!==this._cache[e]},e.prototype.keys=function(){return Promise.resolve(Object.keys(this._cache))},e.prototype.proxy=function(e){var t=this,i=this._options.proxy;if(!i)throw new Error("No proxy defined");var s=e.substring(0,256);return new Promise((function(r,o){var n=Cg.SUPPORT_RESPONSE_TYPE?"blob":"text",a=new XMLHttpRequest;a.onload=function(){if(200===a.status)if("text"===n)r(a.response);else{var e=new FileReader;e.addEventListener("load",(function(){return r(e.result)}),!1),e.addEventListener("error",(function(e){return o(e)}),!1),e.readAsDataURL(a.response)}else o("Failed to proxy resource "+s+" with status code "+a.status)},a.onerror=o;var l=i.indexOf("?")>-1?"&":"?";if(a.open("GET",""+i+l+"url="+encodeURIComponent(e)+"&responseType="+n),"text"!==n&&a instanceof XMLHttpRequest&&(a.responseType=n),t._options.imageTimeout){var A=t._options.imageTimeout;a.timeout=A,a.ontimeout=function(){return o("Timed out ("+A+"ms) proxying "+s)}}a.send()}))},e}(),Xm=/^data:image\/svg\+xml/i,Jm=/^data:image\/.*;base64,/i,Ym=/^data:image\/.*/i,Zm=function(e){return Cg.SUPPORT_SVG_DRAWING||!t_(e)},qm=function(e){return Ym.test(e)},$m=function(e){return Jm.test(e)},e_=function(e){return"blob"===e.substr(0,4)},t_=function(e){return"svg"===e.substr(-3).toLowerCase()||Xm.test(e)},i_=function(){function e(e,t){this.type=0,this.x=e,this.y=t}return e.prototype.add=function(t,i){return new e(this.x+t,this.y+i)},e}(),s_=function(e,t,i){return new i_(e.x+(t.x-e.x)*i,e.y+(t.y-e.y)*i)},r_=function(){function e(e,t,i,s){this.type=1,this.start=e,this.startControl=t,this.endControl=i,this.end=s}return e.prototype.subdivide=function(t,i){var s=s_(this.start,this.startControl,t),r=s_(this.startControl,this.endControl,t),o=s_(this.endControl,this.end,t),n=s_(s,r,t),a=s_(r,o,t),l=s_(n,a,t);return i?new e(this.start,s,n,l):new e(l,a,o,this.end)},e.prototype.add=function(t,i){return new e(this.start.add(t,i),this.startControl.add(t,i),this.endControl.add(t,i),this.end.add(t,i))},e.prototype.reverse=function(){return new e(this.end,this.endControl,this.startControl,this.start)},e}(),o_=function(e){return 1===e.type},n_=function(e){var t=e.styles,i=e.bounds,s=Wd(t.borderTopLeftRadius,i.width,i.height),r=s[0],o=s[1],n=Wd(t.borderTopRightRadius,i.width,i.height),a=n[0],l=n[1],A=Wd(t.borderBottomRightRadius,i.width,i.height),h=A[0],c=A[1],u=Wd(t.borderBottomLeftRadius,i.width,i.height),d=u[0],p=u[1],f=[];f.push((r+a)/i.width),f.push((d+h)/i.width),f.push((o+p)/i.height),f.push((l+c)/i.height);var g=Math.max.apply(Math,f);g>1&&(r/=g,o/=g,a/=g,l/=g,h/=g,c/=g,d/=g,p/=g);var m=i.width-a,_=i.height-c,v=i.width-h,b=i.height-p,y=t.borderTopWidth,x=t.borderRightWidth,B=t.borderBottomWidth,w=t.borderLeftWidth,P=Kd(t.paddingTop,e.bounds.width),C=Kd(t.paddingRight,e.bounds.width),M=Kd(t.paddingBottom,e.bounds.width),E=Kd(t.paddingLeft,e.bounds.width);this.topLeftBorderDoubleOuterBox=r>0||o>0?a_(i.left+w/3,i.top+y/3,r-w/3,o-y/3,Sm.TOP_LEFT):new i_(i.left+w/3,i.top+y/3),this.topRightBorderDoubleOuterBox=r>0||o>0?a_(i.left+m,i.top+y/3,a-x/3,l-y/3,Sm.TOP_RIGHT):new i_(i.left+i.width-x/3,i.top+y/3),this.bottomRightBorderDoubleOuterBox=h>0||c>0?a_(i.left+v,i.top+_,h-x/3,c-B/3,Sm.BOTTOM_RIGHT):new i_(i.left+i.width-x/3,i.top+i.height-B/3),this.bottomLeftBorderDoubleOuterBox=d>0||p>0?a_(i.left+w/3,i.top+b,d-w/3,p-B/3,Sm.BOTTOM_LEFT):new i_(i.left+w/3,i.top+i.height-B/3),this.topLeftBorderDoubleInnerBox=r>0||o>0?a_(i.left+2*w/3,i.top+2*y/3,r-2*w/3,o-2*y/3,Sm.TOP_LEFT):new i_(i.left+2*w/3,i.top+2*y/3),this.topRightBorderDoubleInnerBox=r>0||o>0?a_(i.left+m,i.top+2*y/3,a-2*x/3,l-2*y/3,Sm.TOP_RIGHT):new i_(i.left+i.width-2*x/3,i.top+2*y/3),this.bottomRightBorderDoubleInnerBox=h>0||c>0?a_(i.left+v,i.top+_,h-2*x/3,c-2*B/3,Sm.BOTTOM_RIGHT):new i_(i.left+i.width-2*x/3,i.top+i.height-2*B/3),this.bottomLeftBorderDoubleInnerBox=d>0||p>0?a_(i.left+2*w/3,i.top+b,d-2*w/3,p-2*B/3,Sm.BOTTOM_LEFT):new i_(i.left+2*w/3,i.top+i.height-2*B/3),this.topLeftBorderStroke=r>0||o>0?a_(i.left+w/2,i.top+y/2,r-w/2,o-y/2,Sm.TOP_LEFT):new i_(i.left+w/2,i.top+y/2),this.topRightBorderStroke=r>0||o>0?a_(i.left+m,i.top+y/2,a-x/2,l-y/2,Sm.TOP_RIGHT):new i_(i.left+i.width-x/2,i.top+y/2),this.bottomRightBorderStroke=h>0||c>0?a_(i.left+v,i.top+_,h-x/2,c-B/2,Sm.BOTTOM_RIGHT):new i_(i.left+i.width-x/2,i.top+i.height-B/2),this.bottomLeftBorderStroke=d>0||p>0?a_(i.left+w/2,i.top+b,d-w/2,p-B/2,Sm.BOTTOM_LEFT):new i_(i.left+w/2,i.top+i.height-B/2),this.topLeftBorderBox=r>0||o>0?a_(i.left,i.top,r,o,Sm.TOP_LEFT):new i_(i.left,i.top),this.topRightBorderBox=a>0||l>0?a_(i.left+m,i.top,a,l,Sm.TOP_RIGHT):new i_(i.left+i.width,i.top),this.bottomRightBorderBox=h>0||c>0?a_(i.left+v,i.top+_,h,c,Sm.BOTTOM_RIGHT):new i_(i.left+i.width,i.top+i.height),this.bottomLeftBorderBox=d>0||p>0?a_(i.left,i.top+b,d,p,Sm.BOTTOM_LEFT):new i_(i.left,i.top+i.height),this.topLeftPaddingBox=r>0||o>0?a_(i.left+w,i.top+y,Math.max(0,r-w),Math.max(0,o-y),Sm.TOP_LEFT):new i_(i.left+w,i.top+y),this.topRightPaddingBox=a>0||l>0?a_(i.left+Math.min(m,i.width-x),i.top+y,m>i.width+x?0:Math.max(0,a-x),Math.max(0,l-y),Sm.TOP_RIGHT):new i_(i.left+i.width-x,i.top+y),this.bottomRightPaddingBox=h>0||c>0?a_(i.left+Math.min(v,i.width-w),i.top+Math.min(_,i.height-B),Math.max(0,h-x),Math.max(0,c-B),Sm.BOTTOM_RIGHT):new i_(i.left+i.width-x,i.top+i.height-B),this.bottomLeftPaddingBox=d>0||p>0?a_(i.left+w,i.top+Math.min(b,i.height-B),Math.max(0,d-w),Math.max(0,p-B),Sm.BOTTOM_LEFT):new i_(i.left+w,i.top+i.height-B),this.topLeftContentBox=r>0||o>0?a_(i.left+w+E,i.top+y+P,Math.max(0,r-(w+E)),Math.max(0,o-(y+P)),Sm.TOP_LEFT):new i_(i.left+w+E,i.top+y+P),this.topRightContentBox=a>0||l>0?a_(i.left+Math.min(m,i.width+w+E),i.top+y+P,m>i.width+w+E?0:a-w+E,l-(y+P),Sm.TOP_RIGHT):new i_(i.left+i.width-(x+C),i.top+y+P),this.bottomRightContentBox=h>0||c>0?a_(i.left+Math.min(v,i.width-(w+E)),i.top+Math.min(_,i.height+y+P),Math.max(0,h-(x+C)),c-(B+M),Sm.BOTTOM_RIGHT):new i_(i.left+i.width-(x+C),i.top+i.height-(B+M)),this.bottomLeftContentBox=d>0||p>0?a_(i.left+w+E,i.top+b,Math.max(0,d-(w+E)),p-(B+M),Sm.BOTTOM_LEFT):new i_(i.left+w+E,i.top+i.height-(B+M))};!function(e){e[e.TOP_LEFT=0]="TOP_LEFT",e[e.TOP_RIGHT=1]="TOP_RIGHT",e[e.BOTTOM_RIGHT=2]="BOTTOM_RIGHT",e[e.BOTTOM_LEFT=3]="BOTTOM_LEFT"}(Sm||(Sm={}));var a_=function(e,t,i,s,r){var o=(Math.sqrt(2)-1)/3*4,n=i*o,a=s*o,l=e+i,A=t+s;switch(r){case Sm.TOP_LEFT:return new r_(new i_(e,A),new i_(e,A-a),new i_(l-n,t),new i_(l,t));case Sm.TOP_RIGHT:return new r_(new i_(e,t),new i_(e+n,t),new i_(l,A-a),new i_(l,A));case Sm.BOTTOM_RIGHT:return new r_(new i_(l,t),new i_(l,t+a),new i_(e+n,A),new i_(e,A));case Sm.BOTTOM_LEFT:default:return new r_(new i_(l,A),new i_(l-n,A),new i_(e,t+a),new i_(e,t))}},l_=function(e){return[e.topLeftBorderBox,e.topRightBorderBox,e.bottomRightBorderBox,e.bottomLeftBorderBox]},A_=function(e){return[e.topLeftPaddingBox,e.topRightPaddingBox,e.bottomRightPaddingBox,e.bottomLeftPaddingBox]},h_=function(e,t,i){this.offsetX=e,this.offsetY=t,this.matrix=i,this.type=0,this.target=6},c_=function(e,t){this.path=e,this.target=t,this.type=1},u_=function(e){this.opacity=e,this.type=2,this.target=6},d_=function(e){return 1===e.type},p_=function(e,t){return e.length===t.length&&e.some((function(e,i){return e===t[i]}))},f_=function(e){this.element=e,this.inlineLevel=[],this.nonInlineLevel=[],this.negativeZIndex=[],this.zeroOrAutoZIndexOrTransformedOrOpacity=[],this.positiveZIndex=[],this.nonPositionedFloats=[],this.nonPositionedInlineLevel=[]},g_=function(){function e(e,t){if(this.container=e,this.parent=t,this.effects=[],this.curves=new n_(this.container),this.container.styles.opacity<1&&this.effects.push(new u_(this.container.styles.opacity)),null!==this.container.styles.transform){var i=this.container.bounds.left+this.container.styles.transformOrigin[0].number,s=this.container.bounds.top+this.container.styles.transformOrigin[1].number,r=this.container.styles.transform;this.effects.push(new h_(i,s,r))}if(0!==this.container.styles.overflowX){var o=l_(this.curves),n=A_(this.curves);p_(o,n)?this.effects.push(new c_(o,6)):(this.effects.push(new c_(o,2)),this.effects.push(new c_(n,4)))}}return e.prototype.getEffects=function(e){for(var t=-1===[2,3].indexOf(this.container.styles.position),i=this.parent,s=this.effects.slice(0);i;){var r=i.effects.filter((function(e){return!d_(e)}));if(t||0!==i.container.styles.position||!i.parent){if(s.unshift.apply(s,r),t=-1===[2,3].indexOf(i.container.styles.position),0!==i.container.styles.overflowX){var o=l_(i.curves),n=A_(i.curves);p_(o,n)||s.unshift(new c_(n,6))}}else s.unshift.apply(s,r);i=i.parent}return s.filter((function(t){return Hf(t.target,e)}))},e}(),m_=function(e,t,i,s){e.container.elements.forEach((function(r){var o=Hf(r.flags,4),n=Hf(r.flags,2),a=new g_(r,e);Hf(r.styles.display,2048)&&s.push(a);var l=Hf(r.flags,8)?[]:s;if(o||n){var A=o||r.styles.isPositioned()?i:t,h=new f_(a);if(r.styles.isPositioned()||r.styles.opacity<1||r.styles.isTransformed()){var c=r.styles.zIndex.order;if(c<0){var u=0;A.negativeZIndex.some((function(e,t){return c>e.element.container.styles.zIndex.order?(u=t,!1):u>0})),A.negativeZIndex.splice(u,0,h)}else if(c>0){var d=0;A.positiveZIndex.some((function(e,t){return c>=e.element.container.styles.zIndex.order?(d=t+1,!1):d>0})),A.positiveZIndex.splice(d,0,h)}else A.zeroOrAutoZIndexOrTransformedOrOpacity.push(h)}else r.styles.isFloating()?A.nonPositionedFloats.push(h):A.nonPositionedInlineLevel.push(h);m_(a,h,o?h:i,l)}else r.styles.isInlineLevel()?t.inlineLevel.push(a):t.nonInlineLevel.push(a),m_(a,t,i,l);Hf(r.flags,8)&&__(r,l)}))},__=function(e,t){for(var i=e instanceof Hg?e.start:1,s=e instanceof Hg&&e.reversed,r=0;r0&&e.intrinsicHeight>0){var s=B_(e),r=A_(t);this.path(r),this.ctx.save(),this.ctx.clip(),this.ctx.drawImage(i,0,0,e.intrinsicWidth,e.intrinsicHeight,s.left,s.top,s.width,s.height),this.ctx.restore()}},t.prototype.renderNodeContent=function(e){return Yc(this,void 0,void 0,(function(){var i,s,r,o,n,a,l,A,h,c,u,d,p,f,g,m,_,v;return Zc(this,(function(b){switch(b.label){case 0:this.applyEffects(e.getEffects(4)),i=e.container,s=e.curves,r=i.styles,o=0,n=i.textNodes,b.label=1;case 1:return o0&&B>0&&(m=s.ctx.createPattern(p,"repeat"),s.renderRepeat(v,m,P,C))):function(e){return 2===e.type}(i)&&(_=w_(e,t,[null,null,null]),v=_[0],b=_[1],y=_[2],x=_[3],B=_[4],w=0===i.position.length?[Gd]:i.position,P=Kd(w[0],x),C=Kd(w[w.length-1],B),M=function(e,t,i,s,r){var o=0,n=0;switch(e.size){case 0:0===e.shape?o=n=Math.min(Math.abs(t),Math.abs(t-s),Math.abs(i),Math.abs(i-r)):1===e.shape&&(o=Math.min(Math.abs(t),Math.abs(t-s)),n=Math.min(Math.abs(i),Math.abs(i-r)));break;case 2:if(0===e.shape)o=n=Math.min(pp(t,i),pp(t,i-r),pp(t-s,i),pp(t-s,i-r));else if(1===e.shape){var a=Math.min(Math.abs(i),Math.abs(i-r))/Math.min(Math.abs(t),Math.abs(t-s)),l=fp(s,r,t,i,!0),A=l[0],h=l[1];n=a*(o=pp(A-t,(h-i)/a))}break;case 1:0===e.shape?o=n=Math.max(Math.abs(t),Math.abs(t-s),Math.abs(i),Math.abs(i-r)):1===e.shape&&(o=Math.max(Math.abs(t),Math.abs(t-s)),n=Math.max(Math.abs(i),Math.abs(i-r)));break;case 3:if(0===e.shape)o=n=Math.max(pp(t,i),pp(t,i-r),pp(t-s,i),pp(t-s,i-r));else if(1===e.shape){a=Math.max(Math.abs(i),Math.abs(i-r))/Math.max(Math.abs(t),Math.abs(t-s));var c=fp(s,r,t,i,!1);A=c[0],h=c[1],n=a*(o=pp(A-t,(h-i)/a))}}return Array.isArray(e.size)&&(o=Kd(e.size[0],s),n=2===e.size.length?Kd(e.size[1],r):o),[o,n]}(i,P,C,x,B),E=M[0],F=M[1],E>0&&F>0&&(I=s.ctx.createRadialGradient(b+P,y+C,0,b+P,y+C,E),up(i.stops,2*E).forEach((function(e){return I.addColorStop(e.stop,ep(e.color))})),s.path(v),s.ctx.fillStyle=I,E!==F?(D=e.bounds.left+.5*e.bounds.width,S=e.bounds.top+.5*e.bounds.height,R=1/(T=F/E),s.ctx.save(),s.ctx.translate(D,S),s.ctx.transform(1,0,0,T,0,0),s.ctx.translate(-D,-S),s.ctx.fillRect(b,R*(y-S)+S,x,B*R),s.ctx.restore()):s.ctx.fill())),L.label=6;case 6:return t--,[2]}}))},s=this,r=0,o=e.styles.backgroundImage.slice(0).reverse(),a.label=1;case 1:return r0?2!==l.style?[3,5]:[4,this.renderDashedDottedBorder(l.color,l.width,o,e.curves,2)]:[3,11]:[3,13];case 4:return h.sent(),[3,11];case 5:return 3!==l.style?[3,7]:[4,this.renderDashedDottedBorder(l.color,l.width,o,e.curves,3)];case 6:return h.sent(),[3,11];case 7:return 4!==l.style?[3,9]:[4,this.renderDoubleBorder(l.color,l.width,o,e.curves)];case 8:return h.sent(),[3,11];case 9:return[4,this.renderSolidBorder(l.color,o,e.curves)];case 10:h.sent(),h.label=11;case 11:o++,h.label=12;case 12:return n++,[3,3];case 13:return[2]}}))}))},t.prototype.renderDashedDottedBorder=function(e,t,i,s,r){return Yc(this,void 0,void 0,(function(){var o,n,a,l,A,h,c,u,d,p,f,g,m,_,v,b;return Zc(this,(function(y){return this.ctx.save(),o=function(e,t){switch(t){case 0:return b_(e.topLeftBorderStroke,e.topRightBorderStroke);case 1:return b_(e.topRightBorderStroke,e.bottomRightBorderStroke);case 2:return b_(e.bottomRightBorderStroke,e.bottomLeftBorderStroke);default:return b_(e.bottomLeftBorderStroke,e.topLeftBorderStroke)}}(s,i),n=v_(s,i),2===r&&(this.path(n),this.ctx.clip()),o_(n[0])?(a=n[0].start.x,l=n[0].start.y):(a=n[0].x,l=n[0].y),o_(n[1])?(A=n[1].end.x,h=n[1].end.y):(A=n[1].x,h=n[1].y),c=0===i||2===i?Math.abs(a-A):Math.abs(l-h),this.ctx.beginPath(),3===r?this.formatPath(o):this.formatPath(n.slice(0,2)),u=t<3?3*t:2*t,d=t<3?2*t:t,3===r&&(u=t,d=t),p=!0,c<=2*u?p=!1:c<=2*u+d?(u*=f=c/(2*u+d),d*=f):(g=Math.floor((c+d)/(u+d)),m=(c-g*u)/(g-1),d=(_=(c-(g+1)*u)/g)<=0||Math.abs(d-m){})),tv(this,"_reject",(()=>{})),this.name=e,this.workerThread=t,this.result=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}postMessage(e,t){this.workerThread.postMessage({source:"loaders.gl",type:e,payload:t})}done(e){X_(this.isRunning),this.isRunning=!1,this._resolve(e)}error(e){X_(this.isRunning),this.isRunning=!1,this._reject(e)}}class sv{}const rv=new Map;function ov(e){X_(e.source&&!e.url||!e.source&&e.url);let t=rv.get(e.source||e.url);return t||(e.url&&(t=function(e){if(!e.startsWith("http"))return e;return nv((t=e,"try {\n importScripts('".concat(t,"');\n} catch (error) {\n console.error(error);\n throw error;\n}")));var t}(e.url),rv.set(e.url,t)),e.source&&(t=nv(e.source),rv.set(e.source,t))),X_(t),t}function nv(e){const t=new Blob([e],{type:"application/javascript"});return URL.createObjectURL(t)}function av(e,t=!0,i){const s=i||new Set;if(e){if(lv(e))s.add(e);else if(lv(e.buffer))s.add(e.buffer);else if(ArrayBuffer.isView(e));else if(t&&"object"==typeof e)for(const i in e)av(e[i],t,s)}else;return void 0===i?Array.from(s):[]}function lv(e){return!!e&&(e instanceof ArrayBuffer||("undefined"!=typeof MessagePort&&e instanceof MessagePort||("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)))}const Av=()=>{};class hv{static isSupported(){return"undefined"!=typeof Worker&&Z_||void 0!==typeof sv}constructor(e){tv(this,"name",void 0),tv(this,"source",void 0),tv(this,"url",void 0),tv(this,"terminated",!1),tv(this,"worker",void 0),tv(this,"onMessage",void 0),tv(this,"onError",void 0),tv(this,"_loadableURL","");const{name:t,source:i,url:s}=e;X_(i||s),this.name=t,this.source=i,this.url=s,this.onMessage=Av,this.onError=e=>console.log(e),this.worker=Z_?this._createBrowserWorker():this._createNodeWorker()}destroy(){this.onMessage=Av,this.onError=Av,this.worker.terminate(),this.terminated=!0}get isRunning(){return Boolean(this.onMessage)}postMessage(e,t){t=t||av(e),this.worker.postMessage(e,t)}_getErrorFromErrorEvent(e){let t="Failed to load ";return t+="worker ".concat(this.name," from ").concat(this.url,". "),e.message&&(t+="".concat(e.message," in ")),e.lineno&&(t+=":".concat(e.lineno,":").concat(e.colno)),new Error(t)}_createBrowserWorker(){this._loadableURL=ov({source:this.source,url:this.url});const e=new Worker(this._loadableURL,{name:this.name});return e.onmessage=e=>{e.data?this.onMessage(e.data):this.onError(new Error("No data received"))},e.onerror=e=>{this.onError(this._getErrorFromErrorEvent(e)),this.terminated=!0},e.onmessageerror=e=>console.error(e),e}_createNodeWorker(){let e;if(this.url){const t=this.url.includes(":/")||this.url.startsWith("/")?this.url:"./".concat(this.url);e=new sv(t,{eval:!1})}else{if(!this.source)throw new Error("no worker");e=new sv(this.source,{eval:!0})}return e.on("message",(e=>{this.onMessage(e)})),e.on("error",(e=>{this.onError(e)})),e.on("exit",(e=>{})),e}}class cv{static isSupported(){return hv.isSupported()}constructor(e){tv(this,"name","unnamed"),tv(this,"source",void 0),tv(this,"url",void 0),tv(this,"maxConcurrency",1),tv(this,"maxMobileConcurrency",1),tv(this,"onDebug",(()=>{})),tv(this,"reuseWorkers",!0),tv(this,"props",{}),tv(this,"jobQueue",[]),tv(this,"idleQueue",[]),tv(this,"count",0),tv(this,"isDestroyed",!1),this.source=e.source,this.url=e.url,this.setProps(e)}destroy(){this.idleQueue.forEach((e=>e.destroy())),this.isDestroyed=!0}setProps(e){this.props={...this.props,...e},void 0!==e.name&&(this.name=e.name),void 0!==e.maxConcurrency&&(this.maxConcurrency=e.maxConcurrency),void 0!==e.maxMobileConcurrency&&(this.maxMobileConcurrency=e.maxMobileConcurrency),void 0!==e.reuseWorkers&&(this.reuseWorkers=e.reuseWorkers),void 0!==e.onDebug&&(this.onDebug=e.onDebug)}async startJob(e,t=((e,t,i)=>e.done(i)),i=((e,t)=>e.error(t))){const s=new Promise((s=>(this.jobQueue.push({name:e,onMessage:t,onError:i,onStart:s}),this)));return this._startQueuedJob(),await s}async _startQueuedJob(){if(!this.jobQueue.length)return;const e=this._getAvailableWorker();if(!e)return;const t=this.jobQueue.shift();if(t){this.onDebug({message:"Starting job",name:t.name,workerThread:e,backlog:this.jobQueue.length});const i=new iv(t.name,e);e.onMessage=e=>t.onMessage(i,e.type,e.payload),e.onError=e=>t.onError(i,e),t.onStart(i);try{await i.result}finally{this.returnWorkerToQueue(e)}}}returnWorkerToQueue(e){this.isDestroyed||!this.reuseWorkers||this.count>this._getMaxConcurrency()?(e.destroy(),this.count--):this.idleQueue.push(e),this.isDestroyed||this._startQueuedJob()}_getAvailableWorker(){if(this.idleQueue.length>0)return this.idleQueue.shift()||null;if(this.count{}};class dv{static isSupported(){return hv.isSupported()}static getWorkerFarm(e={}){return dv._workerFarm=dv._workerFarm||new dv({}),dv._workerFarm.setProps(e),dv._workerFarm}constructor(e){tv(this,"props",void 0),tv(this,"workerPools",new Map),this.props={...uv},this.setProps(e),this.workerPools=new Map}destroy(){for(const e of this.workerPools.values())e.destroy();this.workerPools=new Map}setProps(e){this.props={...this.props,...e};for(const e of this.workerPools.values())e.setProps(this._getWorkerPoolProps())}getWorkerPool(e){const{name:t,source:i,url:s}=e;let r=this.workerPools.get(t);return r||(r=new cv({name:t,source:i,url:s}),r.setProps(this._getWorkerPoolProps()),this.workerPools.set(t,r)),r}_getWorkerPoolProps(){return{maxConcurrency:this.props.maxConcurrency,maxMobileConcurrency:this.props.maxMobileConcurrency,reuseWorkers:this.props.reuseWorkers,onDebug:this.props.onDebug}}}tv(dv,"_workerFarm",void 0);var pv=Object.freeze({__proto__:null,default:{}});const fv={};async function gv(e,t=null,i={}){return t&&(e=function(e,t,i){if(e.startsWith("http"))return e;const s=i.modules||{};if(s[e])return s[e];if(!Z_)return"modules/".concat(t,"/dist/libs/").concat(e);if(i.CDN)return X_(i.CDN.startsWith("http")),"".concat(i.CDN,"/").concat(t,"@").concat("3.2.6","/dist/libs/").concat(e);if(q_)return"../src/libs/".concat(e);return"modules/".concat(t,"/src/libs/").concat(e)}(e,t,i)),fv[e]=fv[e]||async function(e){if(e.endsWith("wasm")){const t=await fetch(e);return await t.arrayBuffer()}if(!Z_)try{return pv&&void 0}catch{return null}if(q_)return importScripts(e);const t=await fetch(e);return function(e,t){if(!Z_)return;if(q_)return eval.call(Y_,e),null;const i=document.createElement("script");i.id=t;try{i.appendChild(document.createTextNode(e))}catch(t){i.text=e}return document.body.appendChild(i),null}(await t.text(),e)}(e),await fv[e]}async function mv(e,t,i,s,r){const o=e.id,n=function(e,t={}){const i=t[e.id]||{},s="".concat(e.id,"-worker.js");let r=i.workerUrl;if(r||"compression"!==e.id||(r=t.workerUrl),"test"===t._workerType&&(r="modules/".concat(e.module,"/dist/").concat(s)),!r){let t=e.version;"latest"===t&&(t="latest");const i=t?"@".concat(t):"";r="https://unpkg.com/@loaders.gl/".concat(e.module).concat(i,"/dist/").concat(s)}return X_(r),r}(e,i),a=dv.getWorkerFarm(i).getWorkerPool({name:o,url:n});i=JSON.parse(JSON.stringify(i)),s=JSON.parse(JSON.stringify(s||{}));const l=await a.startJob("process-on-worker",_v.bind(null,r));l.postMessage("process",{input:t,options:i,context:s});const A=await l.result;return await A.result}async function _v(e,t,i,s){switch(i){case"done":t.done(s);break;case"error":t.error(new Error(s.error));break;case"process":const{id:r,input:o,options:n}=s;try{const i=await e(o,n);t.postMessage("done",{id:r,result:i})}catch(e){const i=e instanceof Error?e.message:"unknown error";t.postMessage("error",{id:r,error:i})}break;default:console.warn("parse-with-worker unknown message ".concat(i))}}function vv(e,t,i){if(e.byteLength<=t+i)return"";const s=new DataView(e);let r="";for(let e=0;e=0),z_(t>0),e+(t-1)&~(t-1)}function Pv(e,t,i){let s;if(e instanceof ArrayBuffer)s=new Uint8Array(e);else{const t=e.byteOffset,i=e.byteLength;s=new Uint8Array(e.buffer||e.arrayBuffer,t,i)}return t.set(s,i),i+wv(s.byteLength,4)}async function Cv(e){const t=[];for await(const i of e)t.push(i);return function(...e){const t=e.map((e=>e instanceof ArrayBuffer?new Uint8Array(e):e)),i=t.reduce(((e,t)=>e+t.byteLength),0),s=new Uint8Array(i);let r=0;for(const e of t)s.set(e,r),r+=e.byteLength;return s.buffer}(...t)}const Mv={};const Ev=e=>"function"==typeof e,Fv=e=>null!==e&&"object"==typeof e,Iv=e=>Fv(e)&&e.constructor==={}.constructor,Dv=e=>"undefined"!=typeof Response&&e instanceof Response||e&&e.arrayBuffer&&e.text&&e.json,Sv=e=>"undefined"!=typeof Blob&&e instanceof Blob,Tv=e=>(e=>"undefined"!=typeof ReadableStream&&e instanceof ReadableStream||Fv(e)&&Ev(e.tee)&&Ev(e.cancel)&&Ev(e.getReader))(e)||(e=>Fv(e)&&Ev(e.read)&&Ev(e.pipe)&&(e=>"boolean"==typeof e)(e.readable))(e),Rv=/^data:([-\w.]+\/[-\w.+]+)(;|,)/,Lv=/^([-\w.]+\/[-\w.+]+)/;function Uv(e){const t=Lv.exec(e);return t?t[1]:e}function kv(e){const t=Rv.exec(e);return t?t[1]:""}const Ov=/\?.*/;function Nv(e){if(Dv(e)){const t=Qv(e.url||"");return{url:t,type:Uv(e.headers.get("content-type")||"")||kv(t)}}return Sv(e)?{url:Qv(e.name||""),type:e.type||""}:"string"==typeof e?{url:Qv(e),type:kv(e)}:{url:"",type:""}}function Qv(e){return e.replace(Ov,"")}async function Vv(e){if(Dv(e))return e;const t={},i=function(e){return Dv(e)?e.headers["content-length"]||-1:Sv(e)?e.size:"string"==typeof e?e.length:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:-1}(e);i>=0&&(t["content-length"]=String(i));const{url:s,type:r}=Nv(e);r&&(t["content-type"]=r);const o=await async function(e){const t=5;if("string"==typeof e)return"data:,".concat(e.slice(0,t));if(e instanceof Blob){const t=e.slice(0,5);return await new Promise((e=>{const i=new FileReader;i.onload=t=>{var i;return e(null==t||null===(i=t.target)||void 0===i?void 0:i.result)},i.readAsDataURL(t)}))}if(e instanceof ArrayBuffer){const i=function(e){let t="";const i=new Uint8Array(e);for(let e=0;e=0)}();class Xv{constructor(e,t,i="sessionStorage"){this.storage=function(e){try{const t=window[e],i="__storage_test__";return t.setItem(i,i),t.removeItem(i),t}catch(e){return null}}(i),this.id=e,this.config={},Object.assign(this.config,t),this._loadConfiguration()}getConfiguration(){return this.config}setConfiguration(e){return this.config={},this.updateConfiguration(e)}updateConfiguration(e){if(Object.assign(this.config,e),this.storage){const e=JSON.stringify(this.config);this.storage.setItem(this.id,e)}return this}_loadConfiguration(){let e={};if(this.storage){const t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}}function Jv(e,t,i,s=600){const r=e.src.replace(/\(/g,"%28").replace(/\)/g,"%29");e.width>s&&(i=Math.min(i,s/e.width));const o=e.width*i,n=e.height*i,a=["font-size:1px;","padding:".concat(Math.floor(n/2),"px ").concat(Math.floor(o/2),"px;"),"line-height:".concat(n,"px;"),"background:url(".concat(r,");"),"background-size:".concat(o,"px ").concat(n,"px;"),"color:transparent;"].join("");return["".concat(t," %c+"),a]}const Yv={BLACK:30,RED:31,GREEN:32,YELLOW:33,BLUE:34,MAGENTA:35,CYAN:36,WHITE:37,BRIGHT_BLACK:90,BRIGHT_RED:91,BRIGHT_GREEN:92,BRIGHT_YELLOW:93,BRIGHT_BLUE:94,BRIGHT_MAGENTA:95,BRIGHT_CYAN:96,BRIGHT_WHITE:97};function Zv(e){return"string"==typeof e?Yv[e.toUpperCase()]||Yv.WHITE:e}function qv(e,t){if(!e)throw new Error(t||"Assertion failed")}function $v(){let e;if(Kv&&Gv.performance)e=Gv.performance.now();else if(zv.hrtime){const t=zv.hrtime();e=1e3*t[0]+t[1]/1e6}else e=Date.now();return e}const eb={debug:Kv&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},tb={enabled:!0,level:0};function ib(){}const sb={},rb={once:!0};function ob(e){for(const t in e)for(const i in e[t])return i||"untitled";return"empty"}class nb{constructor({id:e}={id:""}){this.id=e,this.VERSION=Wv,this._startTs=$v(),this._deltaTs=$v(),this.LOG_THROTTLE_TIMEOUT=0,this._storage=new Xv("__probe-".concat(this.id,"__"),tb),this.userData={},this.timeStamp("".concat(this.id," started")),function(e,t=["constructor"]){const i=Object.getPrototypeOf(e),s=Object.getOwnPropertyNames(i);for(const i of s)"function"==typeof e[i]&&(t.find((e=>i===e))||(e[i]=e[i].bind(e)))}(this),Object.seal(this)}set level(e){this.setLevel(e)}get level(){return this.getLevel()}isEnabled(){return this._storage.config.enabled}getLevel(){return this._storage.config.level}getTotal(){return Number(($v()-this._startTs).toPrecision(10))}getDelta(){return Number(($v()-this._deltaTs).toPrecision(10))}set priority(e){this.level=e}get priority(){return this.level}getPriority(){return this.level}enable(e=!0){return this._storage.updateConfiguration({enabled:e}),this}setLevel(e){return this._storage.updateConfiguration({level:e}),this}assert(e,t){qv(e,t)}warn(e){return this._getLogFunction(0,e,eb.warn,arguments,rb)}error(e){return this._getLogFunction(0,e,eb.error,arguments)}deprecated(e,t){return this.warn("`".concat(e,"` is deprecated and will be removed in a later version. Use `").concat(t,"` instead"))}removed(e,t){return this.error("`".concat(e,"` has been removed. Use `").concat(t,"` instead"))}probe(e,t){return this._getLogFunction(e,t,eb.log,arguments,{time:!0,once:!0})}log(e,t){return this._getLogFunction(e,t,eb.debug,arguments)}info(e,t){return this._getLogFunction(e,t,console.info,arguments)}once(e,t){return this._getLogFunction(e,t,eb.debug||eb.info,arguments,rb)}table(e,t,i){return t?this._getLogFunction(e,t,console.table||ib,i&&[i],{tag:ob(t)}):ib}image({logLevel:e,priority:t,image:i,message:s="",scale:r=1}){return this._shouldLog(e||t)?Kv?function({image:e,message:t="",scale:i=1}){if("string"==typeof e){const s=new Image;return s.onload=()=>{const e=Jv(s,t,i);console.log(...e)},s.src=e,ib}const s=e.nodeName||"";if("img"===s.toLowerCase())return console.log(...Jv(e,t,i)),ib;if("canvas"===s.toLowerCase()){const s=new Image;return s.onload=()=>console.log(...Jv(s,t,i)),s.src=e.toDataURL(),ib}return ib}({image:i,message:s,scale:r}):function({image:e,message:t="",scale:i=1}){let s=null;try{s=module.require("asciify-image")}catch(e){}if(s)return()=>s(e,{fit:"box",width:"".concat(Math.round(80*i),"%")}).then((e=>console.log(e)));return ib}({image:i,message:s,scale:r}):ib}settings(){console.table?console.table(this._storage.config):console.log(this._storage.config)}get(e){return this._storage.config[e]}set(e,t){this._storage.updateConfiguration({[e]:t})}time(e,t){return this._getLogFunction(e,t,console.time?console.time:console.info)}timeEnd(e,t){return this._getLogFunction(e,t,console.timeEnd?console.timeEnd:console.info)}timeStamp(e,t){return this._getLogFunction(e,t,console.timeStamp||ib)}group(e,t,i={collapsed:!1}){i=lb({logLevel:e,message:t,opts:i});const{collapsed:s}=i;return i.method=(s?console.groupCollapsed:console.group)||console.info,this._getLogFunction(i)}groupCollapsed(e,t,i={}){return this.group(e,t,Object.assign({},i,{collapsed:!0}))}groupEnd(e){return this._getLogFunction(e,"",console.groupEnd||ib)}withGroup(e,t,i){this.group(e,t)();try{i()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&this.getLevel()>=ab(e)}_getLogFunction(e,t,i,s=[],r){if(this._shouldLog(e)){r=lb({logLevel:e,message:t,args:s,opts:r}),qv(i=i||r.method),r.total=this.getTotal(),r.delta=this.getDelta(),this._deltaTs=$v();const o=r.tag||r.message;if(r.once){if(sb[o])return ib;sb[o]=$v()}return t=function(e,t,i){if("string"==typeof t){const s=i.time?function(e,t=8){const i=Math.max(t-e.length,0);return"".concat(" ".repeat(i)).concat(e)}(function(e){let t;return t=e<10?"".concat(e.toFixed(2),"ms"):e<100?"".concat(e.toFixed(1),"ms"):e<1e3?"".concat(e.toFixed(0),"ms"):"".concat((e/1e3).toFixed(2),"s"),t}(i.total)):"";t=i.time?"".concat(e,": ").concat(s," ").concat(t):"".concat(e,": ").concat(t),t=function(e,t,i){return Kv||"string"!=typeof e||(t&&(t=Zv(t),e="[".concat(t,"m").concat(e,"")),i&&(t=Zv(i),e="[".concat(i+10,"m").concat(e,""))),e}(t,i.color,i.background)}return t}(this.id,r.message,r),i.bind(console,t,...r.args)}return ib}}function ab(e){if(!e)return 0;let t;switch(typeof e){case"number":t=e;break;case"object":t=e.logLevel||e.priority||0;break;default:return 0}return qv(Number.isFinite(t)&&t>=0),t}function lb(e){const{logLevel:t,message:i}=e;e.logLevel=ab(t);const s=e.args?Array.from(e.args):[];for(;s.length&&s.shift()!==i;);switch(e.args=s,typeof t){case"string":case"function":void 0!==i&&s.unshift(i),e.message=t;break;case"object":Object.assign(e,t)}"function"==typeof e.message&&(e.message=e.message());const r=typeof e.message;return qv("string"===r||"object"===r),Object.assign(e,e.opts)}nb.VERSION=Wv;const Ab=new nb({id:"loaders.gl"});class hb{log(){return()=>{}}info(){return()=>{}}warn(){return()=>{}}error(){return()=>{}}}const cb={fetch:null,mimeType:void 0,nothrow:!1,log:new class{constructor(){tv(this,"console",void 0),this.console=console}log(...e){return this.console.log.bind(this.console,...e)}info(...e){return this.console.info.bind(this.console,...e)}warn(...e){return this.console.warn.bind(this.console,...e)}error(...e){return this.console.error.bind(this.console,...e)}},CDN:"https://unpkg.com/@loaders.gl",worker:!0,maxConcurrency:3,maxMobileConcurrency:1,reuseWorkers:W_,_nodeWorkers:!1,_workerType:"",limit:0,_limitMB:0,batchSize:"auto",batchDebounceMs:0,metadata:!1,transforms:[]},ub={throws:"nothrow",dataType:"(no longer used)",uri:"baseUri",method:"fetch.method",headers:"fetch.headers",body:"fetch.body",mode:"fetch.mode",credentials:"fetch.credentials",cache:"fetch.cache",redirect:"fetch.redirect",referrer:"fetch.referrer",referrerPolicy:"fetch.referrerPolicy",integrity:"fetch.integrity",keepalive:"fetch.keepalive",signal:"fetch.signal"};function db(){globalThis.loaders=globalThis.loaders||{};const{loaders:e}=globalThis;return e._state=e._state||{},e._state}const pb=()=>{const e=db();return e.globalOptions=e.globalOptions||{...cb},e.globalOptions};function fb(e,t,i,s){return i=i||[],function(e,t){mb(e,null,cb,ub,t);for(const i of t){const s=e&&e[i.id]||{},r=i.options&&i.options[i.id]||{},o=i.deprecatedOptions&&i.deprecatedOptions[i.id]||{};mb(s,i.id,r,o,t)}}(e,i=Array.isArray(i)?i:[i]),function(e,t,i){const s={...e.options||{}};(function(e,t){t&&!("baseUri"in e)&&(e.baseUri=t)})(s,i),null===s.log&&(s.log=new hb);return vb(s,pb()),vb(s,t),s}(t,e,s)}function gb(e,t){const i=pb(),s=e||i;return"function"==typeof s.fetch?s.fetch:Fv(s.fetch)?e=>Hv(e,s):null!=t&&t.fetch?null==t?void 0:t.fetch:Hv}function mb(e,t,i,s,r){const o=t||"Top level",n=t?"".concat(t,"."):"";for(const a in e){const l=!t&&Fv(e[a]),A="baseUri"===a&&!t,h="workerUrl"===a&&t;if(!(a in i)&&!A&&!h)if(a in s)Ab.warn("".concat(o," loader option '").concat(n).concat(a,"' no longer supported, use '").concat(s[a],"'"))();else if(!l){const e=_b(a,r);Ab.warn("".concat(o," loader option '").concat(n).concat(a,"' not recognized. ").concat(e))()}}}function _b(e,t){const i=e.toLowerCase();let s="";for(const r of t)for(const t in r.options){if(e===t)return"Did you mean '".concat(r.id,".").concat(t,"'?");const o=t.toLowerCase();(i.startsWith(o)||o.startsWith(i))&&(s=s||"Did you mean '".concat(r.id,".").concat(t,"'?"))}return s}function vb(e,t){for(const i in t)if(i in t){const s=t[i];Iv(s)&&Iv(e[i])?e[i]={...e[i],...t[i]}:e[i]=t[i]}}function bb(e){var t;if(!e)return!1;Array.isArray(e)&&(e=e[0]);return Array.isArray(null===(t=e)||void 0===t?void 0:t.extensions)}function yb(e){var t,i;let s;return z_(e,"null loader"),z_(bb(e),"invalid loader"),Array.isArray(e)&&(s=e[1],e=e[0],e={...e,options:{...e.options,...s}}),(null!==(t=e)&&void 0!==t&&t.parseTextSync||null!==(i=e)&&void 0!==i&&i.parseText)&&(e.text=!0),e.text||(e.binary=!0),e}function xb(){return(()=>{const e=db();return e.loaderRegistry=e.loaderRegistry||[],e.loaderRegistry})()}function Bb(){return!("object"==typeof process&&"[object process]"===String(process)&&!process.browser)||function(e){if("undefined"!=typeof window&&"object"==typeof window.process&&"renderer"===window.process.type)return!0;if("undefined"!=typeof process&&"object"==typeof process.versions&&Boolean(process.versions.electron))return!0;const t="object"==typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent,i=e||t;return!!(i&&i.indexOf("Electron")>=0)}()}const wb={self:"undefined"!=typeof self&&self,window:"undefined"!=typeof window&&window,global:"undefined"!=typeof global&&global,document:"undefined"!=typeof document&&document,process:"object"==typeof process&&process},Pb=wb.window||wb.self||wb.global,Cb=wb.process||{},Mb="undefined"!=typeof __VERSION__?__VERSION__:"untranspiled source";Bb();class Eb{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"sessionStorage";tv(this,"storage",void 0),tv(this,"id",void 0),tv(this,"config",{}),this.storage=function(e){try{const t=window[e],i="__storage_test__";return t.setItem(i,i),t.removeItem(i),t}catch(e){return null}}(i),this.id=e,this.config={},Object.assign(this.config,t),this._loadConfiguration()}getConfiguration(){return this.config}setConfiguration(e){return this.config={},this.updateConfiguration(e)}updateConfiguration(e){if(Object.assign(this.config,e),this.storage){const e=JSON.stringify(this.config);this.storage.setItem(this.id,e)}return this}_loadConfiguration(){let e={};if(this.storage){const t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}}function Fb(e,t,i){let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:600;const r=e.src.replace(/\(/g,"%28").replace(/\)/g,"%29");e.width>s&&(i=Math.min(i,s/e.width));const o=e.width*i,n=e.height*i,a=["font-size:1px;","padding:".concat(Math.floor(n/2),"px ").concat(Math.floor(o/2),"px;"),"line-height:".concat(n,"px;"),"background:url(".concat(r,");"),"background-size:".concat(o,"px ").concat(n,"px;"),"color:transparent;"].join("");return["".concat(t," %c+"),a]}let Ib;function Db(e){return"string"==typeof e?Ib[e.toUpperCase()]||Ib.WHITE:e}function Sb(e,t){if(!e)throw new Error(t||"Assertion failed")}function Tb(){let e;var t,i;if(Bb&&"performance"in Pb)e=null==Pb||null===(t=Pb.performance)||void 0===t||null===(i=t.now)||void 0===i?void 0:i.call(t);else if("hrtime"in Cb){var s;const t=null==Cb||null===(s=Cb.hrtime)||void 0===s?void 0:s.call(Cb);e=1e3*t[0]+t[1]/1e6}else e=Date.now();return e}!function(e){e[e.BLACK=30]="BLACK",e[e.RED=31]="RED",e[e.GREEN=32]="GREEN",e[e.YELLOW=33]="YELLOW",e[e.BLUE=34]="BLUE",e[e.MAGENTA=35]="MAGENTA",e[e.CYAN=36]="CYAN",e[e.WHITE=37]="WHITE",e[e.BRIGHT_BLACK=90]="BRIGHT_BLACK",e[e.BRIGHT_RED=91]="BRIGHT_RED",e[e.BRIGHT_GREEN=92]="BRIGHT_GREEN",e[e.BRIGHT_YELLOW=93]="BRIGHT_YELLOW",e[e.BRIGHT_BLUE=94]="BRIGHT_BLUE",e[e.BRIGHT_MAGENTA=95]="BRIGHT_MAGENTA",e[e.BRIGHT_CYAN=96]="BRIGHT_CYAN",e[e.BRIGHT_WHITE=97]="BRIGHT_WHITE"}(Ib||(Ib={}));const Rb={debug:Bb&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},Lb={enabled:!0,level:0};function Ub(){}const kb={},Ob={once:!0};class Nb{constructor(){let{id:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{id:""};tv(this,"id",void 0),tv(this,"VERSION",Mb),tv(this,"_startTs",Tb()),tv(this,"_deltaTs",Tb()),tv(this,"_storage",void 0),tv(this,"userData",{}),tv(this,"LOG_THROTTLE_TIMEOUT",0),this.id=e,this._storage=new Eb("__probe-".concat(this.id,"__"),Lb),this.userData={},this.timeStamp("".concat(this.id," started")),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:["constructor"];const i=Object.getPrototypeOf(e),s=Object.getOwnPropertyNames(i);for(const i of s)"function"==typeof e[i]&&(t.find((e=>i===e))||(e[i]=e[i].bind(e)))}(this),Object.seal(this)}set level(e){this.setLevel(e)}get level(){return this.getLevel()}isEnabled(){return this._storage.config.enabled}getLevel(){return this._storage.config.level}getTotal(){return Number((Tb()-this._startTs).toPrecision(10))}getDelta(){return Number((Tb()-this._deltaTs).toPrecision(10))}set priority(e){this.level=e}get priority(){return this.level}getPriority(){return this.level}enable(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this._storage.updateConfiguration({enabled:e}),this}setLevel(e){return this._storage.updateConfiguration({level:e}),this}get(e){return this._storage.config[e]}set(e,t){this._storage.updateConfiguration({[e]:t})}settings(){console.table?console.table(this._storage.config):console.log(this._storage.config)}assert(e,t){Sb(e,t)}warn(e){return this._getLogFunction(0,e,Rb.warn,arguments,Ob)}error(e){return this._getLogFunction(0,e,Rb.error,arguments)}deprecated(e,t){return this.warn("`".concat(e,"` is deprecated and will be removed in a later version. Use `").concat(t,"` instead"))}removed(e,t){return this.error("`".concat(e,"` has been removed. Use `").concat(t,"` instead"))}probe(e,t){return this._getLogFunction(e,t,Rb.log,arguments,{time:!0,once:!0})}log(e,t){return this._getLogFunction(e,t,Rb.debug,arguments)}info(e,t){return this._getLogFunction(e,t,console.info,arguments)}once(e,t){for(var i=arguments.length,s=new Array(i>2?i-2:0),r=2;r{const t=Fb(e,i,s);console.log(...t)},e.src=t,Ub}const r=t.nodeName||"";if("img"===r.toLowerCase())return console.log(...Fb(t,i,s)),Ub;if("canvas"===r.toLowerCase()){const e=new Image;return e.onload=()=>console.log(...Fb(e,i,s)),e.src=t.toDataURL(),Ub}return Ub}({image:s,message:r,scale:o}):function(e){let{image:t,message:i="",scale:s=1}=e,r=null;try{r=module.require("asciify-image")}catch(e){}if(r)return()=>r(t,{fit:"box",width:"".concat(Math.round(80*s),"%")}).then((e=>console.log(e)));return Ub}({image:s,message:r,scale:o}):Ub}time(e,t){return this._getLogFunction(e,t,console.time?console.time:console.info)}timeEnd(e,t){return this._getLogFunction(e,t,console.timeEnd?console.timeEnd:console.info)}timeStamp(e,t){return this._getLogFunction(e,t,console.timeStamp||Ub)}group(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{collapsed:!1};const s=Vb({logLevel:e,message:t,opts:i}),{collapsed:r}=i;return s.method=(r?console.groupCollapsed:console.group)||console.info,this._getLogFunction(s)}groupCollapsed(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.group(e,t,Object.assign({},i,{collapsed:!0}))}groupEnd(e){return this._getLogFunction(e,"",console.groupEnd||Ub)}withGroup(e,t,i){this.group(e,t)();try{i()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&this.getLevel()>=Qb(e)}_getLogFunction(e,t,i,s,r){if(this._shouldLog(e)){r=Vb({logLevel:e,message:t,args:s,opts:r}),Sb(i=i||r.method),r.total=this.getTotal(),r.delta=this.getDelta(),this._deltaTs=Tb();const o=r.tag||r.message;if(r.once){if(kb[o])return Ub;kb[o]=Tb()}return t=function(e,t,i){if("string"==typeof t){const s=i.time?function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8;const i=Math.max(t-e.length,0);return"".concat(" ".repeat(i)).concat(e)}(function(e){let t;return t=e<10?"".concat(e.toFixed(2),"ms"):e<100?"".concat(e.toFixed(1),"ms"):e<1e3?"".concat(e.toFixed(0),"ms"):"".concat((e/1e3).toFixed(2),"s"),t}(i.total)):"";t=i.time?"".concat(e,": ").concat(s," ").concat(t):"".concat(e,": ").concat(t),t=function(e,t,i){return Bb||"string"!=typeof e||(t&&(t=Db(t),e="[".concat(t,"m").concat(e,"")),i&&(t=Db(i),e="[".concat(i+10,"m").concat(e,""))),e}(t,i.color,i.background)}return t}(this.id,r.message,r),i.bind(console,t,...r.args)}return Ub}}function Qb(e){if(!e)return 0;let t;switch(typeof e){case"number":t=e;break;case"object":t=e.logLevel||e.priority||0;break;default:return 0}return Sb(Number.isFinite(t)&&t>=0),t}function Vb(e){const{logLevel:t,message:i}=e;e.logLevel=Qb(t);const s=e.args?Array.from(e.args):[];for(;s.length&&s.shift()!==i;);switch(typeof t){case"string":case"function":void 0!==i&&s.unshift(i),e.message=t;break;case"object":Object.assign(e,t)}"function"==typeof e.message&&(e.message=e.message());const r=typeof e.message;return Sb("string"===r||"object"===r),Object.assign(e,{args:s},e.opts)}function Hb(e){for(const t in e)for(const i in e[t])return i||"untitled";return"empty"}tv(Nb,"VERSION",Mb);const jb=new Nb({id:"loaders.gl"}),Gb=/\.([^.]+)$/;function zb(e,t=[],i,s){if(!Wb(e))return null;if(t&&!Array.isArray(t))return yb(t);let r=[];t&&(r=r.concat(t)),null!=i&&i.ignoreRegisteredLoaders||r.push(...xb()),function(e){for(const t of e)yb(t)}(r);const o=function(e,t,i,s){const{url:r,type:o}=Nv(e),n=r||(null==s?void 0:s.url);let a=null,l="";null!=i&&i.mimeType&&(a=Xb(t,null==i?void 0:i.mimeType),l="match forced by supplied MIME type ".concat(null==i?void 0:i.mimeType));var A;a=a||function(e,t){const i=t&&Gb.exec(t),s=i&&i[1];return s?function(e,t){t=t.toLowerCase();for(const i of e)for(const e of i.extensions)if(e.toLowerCase()===t)return i;return null}(e,s):null}(t,n),l=l||(a?"matched url ".concat(n):""),a=a||Xb(t,o),l=l||(a?"matched MIME type ".concat(o):""),a=a||function(e,t){if(!t)return null;for(const i of e)if("string"==typeof t){if(Jb(t,i))return i}else if(ArrayBuffer.isView(t)){if(Yb(t.buffer,t.byteOffset,i))return i}else if(t instanceof ArrayBuffer){if(Yb(t,0,i))return i}return null}(t,e),l=l||(a?"matched initial data ".concat(Zb(e)):""),a=a||Xb(t,null==i?void 0:i.fallbackMimeType),l=l||(a?"matched fallback MIME type ".concat(o):""),l&&jb.log(1,"selectLoader selected ".concat(null===(A=a)||void 0===A?void 0:A.name,": ").concat(l,"."));return a}(e,r,i,s);if(!(o||null!=i&&i.nothrow))throw new Error(Kb(e));return o}function Wb(e){return!(e instanceof Response&&204===e.status)}function Kb(e){const{url:t,type:i}=Nv(e);let s="No valid loader found (";s+=t?"".concat(function(e){const t=e&&e.lastIndexOf("/");return t>=0?e.substr(t+1):""}(t),", "):"no url provided, ",s+="MIME type: ".concat(i?'"'.concat(i,'"'):"not provided",", ");const r=e?Zb(e):"";return s+=r?' first bytes: "'.concat(r,'"'):"first bytes: not available",s+=")",s}function Xb(e,t){for(const i of e){if(i.mimeTypes&&i.mimeTypes.includes(t))return i;if(t==="application/x.".concat(i.id))return i}return null}function Jb(e,t){if(t.testText)return t.testText(e);return(Array.isArray(t.tests)?t.tests:[t.tests]).some((t=>e.startsWith(t)))}function Yb(e,t,i){return(Array.isArray(i.tests)?i.tests:[i.tests]).some((s=>function(e,t,i,s){if(s instanceof ArrayBuffer)return function(e,t,i){if(i=i||e.byteLength,e.byteLength60?"".concat(t.slice(0,60),"..."):t}catch(e){}return t}(e);throw new Error(t)}}(i),t.binary?await i.arrayBuffer():await i.text()}if(Tv(e)&&(e=ty(e,i)),(r=e)&&"function"==typeof r[Symbol.iterator]||(e=>e&&"function"==typeof e[Symbol.asyncIterator])(e))return Cv(e);var r;throw new Error(iy)}async function ry(e,t,i,s){X_(!s||"object"==typeof s),!t||Array.isArray(t)||bb(t)||(s=void 0,i=t,t=void 0),e=await e,i=i||{};const{url:r}=Nv(e),o=function(e,t){if(!t&&e&&!Array.isArray(e))return e;let i;if(e&&(i=Array.isArray(e)?e:[e]),t&&t.loaders){const e=Array.isArray(t.loaders)?t.loaders:[t.loaders];i=i?[...i,...e]:e}return i&&i.length?i:null}(t,s),n=await async function(e,t=[],i,s){if(!Wb(e))return null;let r=zb(e,t,{...i,nothrow:!0},s);if(r)return r;if(Sv(e)&&(r=zb(e=await e.slice(0,10).arrayBuffer(),t,i,s)),!(r||null!=i&&i.nothrow))throw new Error(Kb(e));return r}(e,o,i);return n?(s=function(e,t,i=null){if(i)return i;const s={fetch:gb(t,e),...e};return Array.isArray(s.loaders)||(s.loaders=null),s}({url:r,parse:ry,loaders:o},i=fb(i,n,o,r),s),await async function(e,t,i,s){if(function(e,t="3.2.6"){X_(e,"no worker provided");const i=e.version}(e),Dv(t)){const e=t,{ok:i,redirected:r,status:o,statusText:n,type:a,url:l}=e,A=Object.fromEntries(e.headers.entries());s.response={headers:A,ok:i,redirected:r,status:o,statusText:n,type:a,url:l}}if(t=await sy(t,e,i),e.parseTextSync&&"string"==typeof t)return i.dataType="text",e.parseTextSync(t,i,s,e);if(function(e,t){return!!dv.isSupported()&&!!(Z_||null!=t&&t._nodeWorkers)&&e.worker&&(null==t?void 0:t.worker)}(e,i))return await mv(e,t,i,s,ry);if(e.parseText&&"string"==typeof t)return await e.parseText(t,i,s,e);if(e.parse)return await e.parse(t,i,s,e);throw X_(!e.parseSync),new Error("".concat(e.id," loader - no parser found and worker is disabled"))}(n,e,i,s)):null}const oy="https://unpkg.com/@loaders.gl/textures@".concat("3.2.6","/dist/libs/basis_encoder.wasm"),ny="https://unpkg.com/@loaders.gl/textures@".concat("3.2.6","/dist/libs/basis_encoder.js");let ay,ly;async function Ay(e){const t=e.modules||{};return t.basis?t.basis:(ay=ay||async function(e){let t=null,i=null;return[t,i]=await Promise.all([await gv("basis_transcoder.js","textures",e),await gv("basis_transcoder.wasm","textures",e)]),t=t||globalThis.BASIS,await function(e,t){const i={};t&&(i.wasmBinary=t);return new Promise((t=>{e(i).then((e=>{const{BasisFile:i,initializeBasis:s}=e;s(),t({BasisFile:i})}))}))}(t,i)}(e),await ay)}async function hy(e){const t=e.modules||{};return t.basisEncoder?t.basisEncoder:(ly=ly||async function(e){let t=null,i=null;return[t,i]=await Promise.all([await gv(ny,"textures",e),await gv(oy,"textures",e)]),t=t||globalThis.BASIS,await function(e,t){const i={};t&&(i.wasmBinary=t);return new Promise((t=>{e(i).then((e=>{const{BasisFile:i,KTX2File:s,initializeBasis:r,BasisEncoder:o}=e;r(),t({BasisFile:i,KTX2File:s,BasisEncoder:o})}))}))}(t,i)}(e),await ly)}const cy=33776,uy=33779,dy=35840,py=35842,fy=36196,gy=37808,my=["","WEBKIT_","MOZ_"],_y={WEBGL_compressed_texture_s3tc:"dxt",WEBGL_compressed_texture_s3tc_srgb:"dxt-srgb",WEBGL_compressed_texture_etc1:"etc1",WEBGL_compressed_texture_etc:"etc2",WEBGL_compressed_texture_pvrtc:"pvrtc",WEBGL_compressed_texture_atc:"atc",WEBGL_compressed_texture_astc:"astc",EXT_texture_compression_rgtc:"rgtc"};let vy=null;function by(e){if(!vy){e=e||function(){try{return document.createElement("canvas").getContext("webgl")}catch(e){return null}}()||void 0,vy=new Set;for(const t of my)for(const i in _y)if(e&&e.getExtension("".concat(t).concat(i))){const e=_y[i];vy.add(e)}}return vy}var yy,xy,By,wy,Py,Cy,My,Ey,Fy;(Fy=yy||(yy={}))[Fy.NONE=0]="NONE",Fy[Fy.BASISLZ=1]="BASISLZ",Fy[Fy.ZSTD=2]="ZSTD",Fy[Fy.ZLIB=3]="ZLIB",function(e){e[e.BASICFORMAT=0]="BASICFORMAT"}(xy||(xy={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.ETC1S=163]="ETC1S",e[e.UASTC=166]="UASTC"}(By||(By={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.SRGB=1]="SRGB"}(wy||(wy={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.LINEAR=1]="LINEAR",e[e.SRGB=2]="SRGB",e[e.ITU=3]="ITU",e[e.NTSC=4]="NTSC",e[e.SLOG=5]="SLOG",e[e.SLOG2=6]="SLOG2"}(Py||(Py={})),function(e){e[e.ALPHA_STRAIGHT=0]="ALPHA_STRAIGHT",e[e.ALPHA_PREMULTIPLIED=1]="ALPHA_PREMULTIPLIED"}(Cy||(Cy={})),function(e){e[e.RGB=0]="RGB",e[e.RRR=3]="RRR",e[e.GGG=4]="GGG",e[e.AAA=15]="AAA"}(My||(My={})),function(e){e[e.RGB=0]="RGB",e[e.RGBA=3]="RGBA",e[e.RRR=4]="RRR",e[e.RRRG=5]="RRRG"}(Ey||(Ey={}));const Iy=[171,75,84,88,32,50,48,187,13,10,26,10];const Dy={etc1:{basisFormat:0,compressed:!0,format:fy},etc2:{basisFormat:1,compressed:!0},bc1:{basisFormat:2,compressed:!0,format:cy},bc3:{basisFormat:3,compressed:!0,format:uy},bc4:{basisFormat:4,compressed:!0},bc5:{basisFormat:5,compressed:!0},"bc7-m6-opaque-only":{basisFormat:6,compressed:!0},"bc7-m5":{basisFormat:7,compressed:!0},"pvrtc1-4-rgb":{basisFormat:8,compressed:!0,format:dy},"pvrtc1-4-rgba":{basisFormat:9,compressed:!0,format:py},"astc-4x4":{basisFormat:10,compressed:!0,format:gy},"atc-rgb":{basisFormat:11,compressed:!0},"atc-rgba-interpolated-alpha":{basisFormat:12,compressed:!0},rgba32:{basisFormat:13,compressed:!1},rgb565:{basisFormat:14,compressed:!1},bgr565:{basisFormat:15,compressed:!1},rgba4444:{basisFormat:16,compressed:!1}};function Sy(e,t,i){const s=new e(new Uint8Array(t));try{if(!s.startTranscoding())throw new Error("Failed to start basis transcoding");const e=s.getNumImages(),t=[];for(let r=0;r{try{i.onload=()=>t(i),i.onerror=t=>s(new Error("Could not load image ".concat(e,": ").concat(t)))}catch(e){s(e)}}))}(o||s,t)}finally{o&&r.revokeObjectURL(o)}}const Yy={};let Zy=!0;async function qy(e,t,i){let s;if(Ky(i)){s=await Jy(e,t,i)}else s=Xy(e,i);const r=t&&t.imagebitmap;return await async function(e,t=null){!function(e){for(const t in e||Yy)return!1;return!0}(t)&&Zy||(t=null);if(t)try{return await createImageBitmap(e,t)}catch(e){console.warn(e),Zy=!1}return await createImageBitmap(e)}(s,r)}function $y(e){const t=ex(e);return function(e){const t=ex(e);if(!(t.byteLength>=24&&2303741511===t.getUint32(0,false)))return null;return{mimeType:"image/png",width:t.getUint32(16,false),height:t.getUint32(20,false)}}(t)||function(e){const t=ex(e);if(!(t.byteLength>=3&&65496===t.getUint16(0,false)&&255===t.getUint8(2)))return null;const{tableMarkers:i,sofMarkers:s}=function(){const e=new Set([65499,65476,65484,65501,65534]);for(let t=65504;t<65520;++t)e.add(t);const t=new Set([65472,65473,65474,65475,65477,65478,65479,65481,65482,65483,65485,65486,65487,65502]);return{tableMarkers:e,sofMarkers:t}}();let r=2;for(;r+9=10&&1195984440===t.getUint32(0,false)))return null;return{mimeType:"image/gif",width:t.getUint16(6,true),height:t.getUint16(8,true)}}(t)||function(e){const t=ex(e);if(!(t.byteLength>=14&&16973===t.getUint16(0,false)&&t.getUint32(2,true)===t.byteLength))return null;return{mimeType:"image/bmp",width:t.getUint32(18,true),height:t.getUint32(22,true)}}(t)}function ex(e){if(e instanceof DataView)return e;if(ArrayBuffer.isView(e))return new DataView(e.buffer);if(e instanceof ArrayBuffer)return new DataView(e);throw new Error("toDataView")}const tx={id:"image",module:"images",name:"Images",version:"3.2.6",mimeTypes:["image/png","image/jpeg","image/gif","image/webp","image/bmp","image/vnd.microsoft.icon","image/svg+xml"],extensions:["png","jpg","jpeg","gif","webp","bmp","ico","svg"],parse:async function(e,t,i){const s=((t=t||{}).image||{}).type||"auto",{url:r}=i||{};let o;switch(function(e){switch(e){case"auto":case"data":return function(){if(Vy)return"imagebitmap";if(Qy)return"image";if(jy)return"data";throw new Error("Install '@loaders.gl/polyfills' to parse images under Node.js")}();default:return function(e){switch(e){case"auto":return Vy||Qy||jy;case"imagebitmap":return Vy;case"image":return Qy;case"data":return jy;default:throw new Error("@loaders.gl/images: image ".concat(e," not supported in this environment"))}}(e),e}}(s)){case"imagebitmap":o=await qy(e,t,r);break;case"image":o=await Jy(e,t,r);break;case"data":o=await async function(e,t){const{mimeType:i}=$y(e)||{},s=globalThis._parseImageNode;return z_(s),await s(e,i)}(e);break;default:z_(!1)}return"data"===s&&(o=function(e){switch(Gy(e)){case"data":return e;case"image":case"imagebitmap":const t=document.createElement("canvas"),i=t.getContext("2d");if(!i)throw new Error("getImageData");return t.width=e.width,t.height=e.height,i.drawImage(e,0,0),i.getImageData(0,0,e.width,e.height);default:throw new Error("getImageData")}}(o)),o},tests:[e=>Boolean($y(new DataView(e)))],options:{image:{type:"auto",decode:!0}}},ix=["image/png","image/jpeg","image/gif"],sx={};function rx(e){return void 0===sx[e]&&(sx[e]=function(e){switch(e){case"image/webp":return function(){if(!W_)return!1;try{return 0===document.createElement("canvas").toDataURL("image/webp").indexOf("data:image/webp")}catch{return!1}}();case"image/svg":return W_;default:if(!W_){const{_parseImageNode:t}=globalThis;return Boolean(t)&&ix.includes(e)}return!0}}(e)),sx[e]}function ox(e,t){if(!e)throw new Error(t||"assert failed: gltf")}function nx(e,t){if(e.startsWith("data:")||e.startsWith("http:")||e.startsWith("https:"))return e;const i=t.baseUri||t.uri;if(!i)throw new Error("'baseUri' must be provided to resolve relative url ".concat(e));return i.substr(0,i.lastIndexOf("/")+1)+e}const ax=["SCALAR","VEC2","VEC3","VEC4"],lx=[[Int8Array,5120],[Uint8Array,5121],[Int16Array,5122],[Uint16Array,5123],[Uint32Array,5125],[Float32Array,5126],[Float64Array,5130]],Ax=new Map(lx),hx={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},cx={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},ux={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array};function dx(e){return ax[e-1]||ax[0]}function px(e){const t=Ax.get(e.constructor);if(!t)throw new Error("Illegal typed array");return t}function fx(e,t){const i=ux[e.componentType],s=hx[e.type],r=cx[e.componentType],o=e.count*s,n=e.count*s*r;return ox(n>=0&&n<=t.byteLength),{ArrayType:i,length:o,byteLength:n}}const gx={asset:{version:"2.0",generator:"loaders.gl"},buffers:[]};class mx{constructor(e){tv(this,"gltf",void 0),tv(this,"sourceBuffers",void 0),tv(this,"byteLength",void 0),this.gltf=e||{json:{...gx},buffers:[]},this.sourceBuffers=[],this.byteLength=0,this.gltf.buffers&&this.gltf.buffers[0]&&(this.byteLength=this.gltf.buffers[0].byteLength,this.sourceBuffers=[this.gltf.buffers[0]])}get json(){return this.gltf.json}getApplicationData(e){return this.json[e]}getExtraData(e){return(this.json.extras||{})[e]}getExtension(e){const t=this.getUsedExtensions().find((t=>t===e)),i=this.json.extensions||{};return t?i[e]||!0:null}getRequiredExtension(e){const t=this.getRequiredExtensions().find((t=>t===e));return t?this.getExtension(e):null}getRequiredExtensions(){return this.json.extensionsRequired||[]}getUsedExtensions(){return this.json.extensionsUsed||[]}getObjectExtension(e,t){return(e.extensions||{})[t]}getScene(e){return this.getObject("scenes",e)}getNode(e){return this.getObject("nodes",e)}getSkin(e){return this.getObject("skins",e)}getMesh(e){return this.getObject("meshes",e)}getMaterial(e){return this.getObject("materials",e)}getAccessor(e){return this.getObject("accessors",e)}getTexture(e){return this.getObject("textures",e)}getSampler(e){return this.getObject("samplers",e)}getImage(e){return this.getObject("images",e)}getBufferView(e){return this.getObject("bufferViews",e)}getBuffer(e){return this.getObject("buffers",e)}getObject(e,t){if("object"==typeof t)return t;const i=this.json[e]&&this.json[e][t];if(!i)throw new Error("glTF file error: Could not find ".concat(e,"[").concat(t,"]"));return i}getTypedArrayForBufferView(e){const t=(e=this.getBufferView(e)).buffer,i=this.gltf.buffers[t];ox(i);const s=(e.byteOffset||0)+i.byteOffset;return new Uint8Array(i.arrayBuffer,s,e.byteLength)}getTypedArrayForAccessor(e){e=this.getAccessor(e);const t=this.getBufferView(e.bufferView),i=this.getBuffer(t.buffer).data,{ArrayType:s,length:r}=fx(e,t);return new s(i,t.byteOffset+e.byteOffset,r)}getTypedArrayForImageData(e){e=this.getAccessor(e);const t=this.getBufferView(e.bufferView),i=this.getBuffer(t.buffer).data,s=t.byteOffset||0;return new Uint8Array(i,s,t.byteLength)}addApplicationData(e,t){return this.json[e]=t,this}addExtraData(e,t){return this.json.extras=this.json.extras||{},this.json.extras[e]=t,this}addObjectExtension(e,t,i){return e.extensions=e.extensions||{},e.extensions[t]=i,this.registerUsedExtension(t),this}setObjectExtension(e,t,i){(e.extensions||{})[t]=i}removeObjectExtension(e,t){const i=e.extensions||{},s=i[t];return delete i[t],s}addExtension(e,t={}){return ox(t),this.json.extensions=this.json.extensions||{},this.json.extensions[e]=t,this.registerUsedExtension(e),t}addRequiredExtension(e,t={}){return ox(t),this.addExtension(e,t),this.registerRequiredExtension(e),t}registerUsedExtension(e){this.json.extensionsUsed=this.json.extensionsUsed||[],this.json.extensionsUsed.find((t=>t===e))||this.json.extensionsUsed.push(e)}registerRequiredExtension(e){this.registerUsedExtension(e),this.json.extensionsRequired=this.json.extensionsRequired||[],this.json.extensionsRequired.find((t=>t===e))||this.json.extensionsRequired.push(e)}removeExtension(e){this.json.extensionsRequired&&this._removeStringFromArray(this.json.extensionsRequired,e),this.json.extensionsUsed&&this._removeStringFromArray(this.json.extensionsUsed,e),this.json.extensions&&delete this.json.extensions[e]}setDefaultScene(e){this.json.scene=e}addScene(e){const{nodeIndices:t}=e;return this.json.scenes=this.json.scenes||[],this.json.scenes.push({nodes:t}),this.json.scenes.length-1}addNode(e){const{meshIndex:t,matrix:i}=e;this.json.nodes=this.json.nodes||[];const s={mesh:t};return i&&(s.matrix=i),this.json.nodes.push(s),this.json.nodes.length-1}addMesh(e){const{attributes:t,indices:i,material:s,mode:r=4}=e,o={primitives:[{attributes:this._addAttributes(t),mode:r}]};if(i){const e=this._addIndices(i);o.primitives[0].indices=e}return Number.isFinite(s)&&(o.primitives[0].material=s),this.json.meshes=this.json.meshes||[],this.json.meshes.push(o),this.json.meshes.length-1}addPointCloud(e){const t={primitives:[{attributes:this._addAttributes(e),mode:0}]};return this.json.meshes=this.json.meshes||[],this.json.meshes.push(t),this.json.meshes.length-1}addImage(e,t){const i=$y(e),s=t||(null==i?void 0:i.mimeType),r={bufferView:this.addBufferView(e),mimeType:s};return this.json.images=this.json.images||[],this.json.images.push(r),this.json.images.length-1}addBufferView(e){const t=e.byteLength;ox(Number.isFinite(t)),this.sourceBuffers=this.sourceBuffers||[],this.sourceBuffers.push(e);const i={buffer:0,byteOffset:this.byteLength,byteLength:t};return this.byteLength+=wv(t,4),this.json.bufferViews=this.json.bufferViews||[],this.json.bufferViews.push(i),this.json.bufferViews.length-1}addAccessor(e,t){const i={bufferView:e,type:dx(t.size),componentType:t.componentType,count:t.count,max:t.max,min:t.min};return this.json.accessors=this.json.accessors||[],this.json.accessors.push(i),this.json.accessors.length-1}addBinaryBuffer(e,t={size:3}){const i=this.addBufferView(e);let s={min:t.min,max:t.max};s.min&&s.max||(s=this._getAccessorMinMax(e,t.size));const r={size:t.size,componentType:px(e),count:Math.round(e.length/t.size),min:s.min,max:s.max};return this.addAccessor(i,Object.assign(r,t))}addTexture(e){const{imageIndex:t}=e,i={source:t};return this.json.textures=this.json.textures||[],this.json.textures.push(i),this.json.textures.length-1}addMaterial(e){return this.json.materials=this.json.materials||[],this.json.materials.push(e),this.json.materials.length-1}createBinaryChunk(){var e,t;this.gltf.buffers=[];const i=this.byteLength,s=new ArrayBuffer(i),r=new Uint8Array(s);let o=0;for(const e of this.sourceBuffers||[])o=Pv(e,r,o);null!==(e=this.json)&&void 0!==e&&null!==(t=e.buffers)&&void 0!==t&&t[0]?this.json.buffers[0].byteLength=i:this.json.buffers=[{byteLength:i}],this.gltf.binary=s,this.sourceBuffers=[s]}_removeStringFromArray(e,t){let i=!0;for(;i;){const s=e.indexOf(t);s>-1?e.splice(s,1):i=!1}}_addAttributes(e={}){const t={};for(const i in e){const s=e[i],r=this._getGltfAttributeName(i),o=this.addBinaryBuffer(s.value,s);t[r]=o}return t}_addIndices(e){return this.addBinaryBuffer(e,{size:1})}_getGltfAttributeName(e){switch(e.toLowerCase()){case"position":case"positions":case"vertices":return"POSITION";case"normal":case"normals":return"NORMAL";case"color":case"colors":return"COLOR_0";case"texcoord":case"texcoords":return"TEXCOORD_0";default:return e}}_getAccessorMinMax(e,t){const i={min:null,max:null};if(e.length96?s-71:s>64?s-65:s>47?s+4:s>46?63:62}let i=0;for(let s=0;st[e.name]));return new Dx(i,this.metadata)}selectAt(...e){const t=e.map((e=>this.fields[e])).filter(Boolean);return new Dx(t,this.metadata)}assign(e){let t,i=this.metadata;if(e instanceof Dx){const s=e;t=s.fields,i=Sx(Sx(new Map,this.metadata),s.metadata)}else t=e;const s=Object.create(null);for(const e of this.fields)s[e.name]=e;for(const e of t)s[e.name]=e;const r=Object.values(s);return new Dx(r,i)}}function Sx(e,t){return new Map([...e||new Map,...t||new Map])}class Tx{constructor(e,t,i=!1,s=new Map){tv(this,"name",void 0),tv(this,"type",void 0),tv(this,"nullable",void 0),tv(this,"metadata",void 0),this.name=e,this.type=t,this.nullable=i,this.metadata=s}get typeId(){return this.type&&this.type.typeId}clone(){return new Tx(this.name,this.type,this.nullable,this.metadata)}compareTo(e){return this.name===e.name&&this.type===e.type&&this.nullable===e.nullable&&this.metadata===e.metadata}toString(){return"".concat(this.type).concat(this.nullable?", nullable":"").concat(this.metadata?", metadata: ".concat(this.metadata):"")}}let Rx,Lx,Ux,kx;!function(e){e[e.NONE=0]="NONE",e[e.Null=1]="Null",e[e.Int=2]="Int",e[e.Float=3]="Float",e[e.Binary=4]="Binary",e[e.Utf8=5]="Utf8",e[e.Bool=6]="Bool",e[e.Decimal=7]="Decimal",e[e.Date=8]="Date",e[e.Time=9]="Time",e[e.Timestamp=10]="Timestamp",e[e.Interval=11]="Interval",e[e.List=12]="List",e[e.Struct=13]="Struct",e[e.Union=14]="Union",e[e.FixedSizeBinary=15]="FixedSizeBinary",e[e.FixedSizeList=16]="FixedSizeList",e[e.Map=17]="Map",e[e.Dictionary=-1]="Dictionary",e[e.Int8=-2]="Int8",e[e.Int16=-3]="Int16",e[e.Int32=-4]="Int32",e[e.Int64=-5]="Int64",e[e.Uint8=-6]="Uint8",e[e.Uint16=-7]="Uint16",e[e.Uint32=-8]="Uint32",e[e.Uint64=-9]="Uint64",e[e.Float16=-10]="Float16",e[e.Float32=-11]="Float32",e[e.Float64=-12]="Float64",e[e.DateDay=-13]="DateDay",e[e.DateMillisecond=-14]="DateMillisecond",e[e.TimestampSecond=-15]="TimestampSecond",e[e.TimestampMillisecond=-16]="TimestampMillisecond",e[e.TimestampMicrosecond=-17]="TimestampMicrosecond",e[e.TimestampNanosecond=-18]="TimestampNanosecond",e[e.TimeSecond=-19]="TimeSecond",e[e.TimeMillisecond=-20]="TimeMillisecond",e[e.TimeMicrosecond=-21]="TimeMicrosecond",e[e.TimeNanosecond=-22]="TimeNanosecond",e[e.DenseUnion=-23]="DenseUnion",e[e.SparseUnion=-24]="SparseUnion",e[e.IntervalDayTime=-25]="IntervalDayTime",e[e.IntervalYearMonth=-26]="IntervalYearMonth"}(Rx||(Rx={}));class Ox{static isNull(e){return e&&e.typeId===Rx.Null}static isInt(e){return e&&e.typeId===Rx.Int}static isFloat(e){return e&&e.typeId===Rx.Float}static isBinary(e){return e&&e.typeId===Rx.Binary}static isUtf8(e){return e&&e.typeId===Rx.Utf8}static isBool(e){return e&&e.typeId===Rx.Bool}static isDecimal(e){return e&&e.typeId===Rx.Decimal}static isDate(e){return e&&e.typeId===Rx.Date}static isTime(e){return e&&e.typeId===Rx.Time}static isTimestamp(e){return e&&e.typeId===Rx.Timestamp}static isInterval(e){return e&&e.typeId===Rx.Interval}static isList(e){return e&&e.typeId===Rx.List}static isStruct(e){return e&&e.typeId===Rx.Struct}static isUnion(e){return e&&e.typeId===Rx.Union}static isFixedSizeBinary(e){return e&&e.typeId===Rx.FixedSizeBinary}static isFixedSizeList(e){return e&&e.typeId===Rx.FixedSizeList}static isMap(e){return e&&e.typeId===Rx.Map}static isDictionary(e){return e&&e.typeId===Rx.Dictionary}get typeId(){return Rx.NONE}compareTo(e){return this===e}}Lx=Symbol.toStringTag;class Nx extends Ox{constructor(e,t){super(),tv(this,"isSigned",void 0),tv(this,"bitWidth",void 0),this.isSigned=e,this.bitWidth=t}get typeId(){return Rx.Int}get[Lx](){return"Int"}toString(){return"".concat(this.isSigned?"I":"Ui","nt").concat(this.bitWidth)}}class Qx extends Nx{constructor(){super(!0,8)}}class Vx extends Nx{constructor(){super(!0,16)}}class Hx extends Nx{constructor(){super(!0,32)}}class jx extends Nx{constructor(){super(!1,8)}}class Gx extends Nx{constructor(){super(!1,16)}}class zx extends Nx{constructor(){super(!1,32)}}const Wx=32,Kx=64;Ux=Symbol.toStringTag;class Xx extends Ox{constructor(e){super(),tv(this,"precision",void 0),this.precision=e}get typeId(){return Rx.Float}get[Ux](){return"Float"}toString(){return"Float".concat(this.precision)}}class Jx extends Xx{constructor(){super(Wx)}}class Yx extends Xx{constructor(){super(Kx)}}kx=Symbol.toStringTag;class Zx extends Ox{constructor(e,t){super(),tv(this,"listSize",void 0),tv(this,"children",void 0),this.listSize=e,this.children=[t]}get typeId(){return Rx.FixedSizeList}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get[kx](){return"FixedSizeList"}toString(){return"FixedSizeList[".concat(this.listSize,"]<").concat(this.valueType,">")}}function qx(e,t,i){const s=function(e){switch(e.constructor){case Int8Array:return new Qx;case Uint8Array:return new jx;case Int16Array:return new Vx;case Uint16Array:return new Gx;case Int32Array:return new Hx;case Uint32Array:return new zx;case Float32Array:return new Jx;case Float64Array:return new Yx;default:throw new Error("array type not supported")}}(t.value),r=i||function(e){const t=new Map;"byteOffset"in e&&t.set("byteOffset",e.byteOffset.toString(10));"byteStride"in e&&t.set("byteStride",e.byteStride.toString(10));"normalized"in e&&t.set("normalized",e.normalized.toString());return t}(t);return new Tx(e,new Zx(t.size,new Tx("value",s)),!1,r)}function $x(e,t,i){return qx(e,t,i?eB(i.metadata):void 0)}function eB(e){const t=new Map;for(const i in e)t.set("".concat(i,".string"),JSON.stringify(e[i]));return t}const tB={POSITION:"POSITION",NORMAL:"NORMAL",COLOR:"COLOR_0",TEX_COORD:"TEXCOORD_0"},iB={1:Int8Array,2:Uint8Array,3:Int16Array,4:Uint16Array,5:Int32Array,6:Uint32Array,9:Float32Array};class sB{constructor(e){tv(this,"draco",void 0),tv(this,"decoder",void 0),tv(this,"metadataQuerier",void 0),this.draco=e,this.decoder=new this.draco.Decoder,this.metadataQuerier=new this.draco.MetadataQuerier}destroy(){this.draco.destroy(this.decoder),this.draco.destroy(this.metadataQuerier)}parseSync(e,t={}){const i=new this.draco.DecoderBuffer;i.Init(new Int8Array(e),e.byteLength),this._disableAttributeTransforms(t);const s=this.decoder.GetEncodedGeometryType(i),r=s===this.draco.TRIANGULAR_MESH?new this.draco.Mesh:new this.draco.PointCloud;try{let e;switch(s){case this.draco.TRIANGULAR_MESH:e=this.decoder.DecodeBufferToMesh(i,r);break;case this.draco.POINT_CLOUD:e=this.decoder.DecodeBufferToPointCloud(i,r);break;default:throw new Error("DRACO: Unknown geometry type.")}if(!e.ok()||!r.ptr){const t="DRACO decompression failed: ".concat(e.error_msg());throw new Error(t)}const o=this._getDracoLoaderData(r,s,t),n=this._getMeshData(r,o,t),a=function(e){let t=1/0,i=1/0,s=1/0,r=-1/0,o=-1/0,n=-1/0;const a=e.POSITION?e.POSITION.value:[],l=a&&a.length;for(let e=0;er?l:r,o=A>o?A:o,n=h>n?h:n}return[[t,i,s],[r,o,n]]}(n.attributes),l=function(e,t,i){const s=eB(t.metadata),r=[],o=function(e){const t={};for(const i in e){const s=e[i];t[s.name||"undefined"]=s}return t}(t.attributes);for(const t in e){const i=$x(t,e[t],o[t]);r.push(i)}if(i){const e=$x("indices",i);r.push(e)}return new Dx(r,s)}(n.attributes,o,n.indices);return{loader:"draco",loaderData:o,header:{vertexCount:r.num_points(),boundingBox:a},...n,schema:l}}finally{this.draco.destroy(i),r&&this.draco.destroy(r)}}_getDracoLoaderData(e,t,i){const s=this._getTopLevelMetadata(e),r=this._getDracoAttributes(e,i);return{geometry_type:t,num_attributes:e.num_attributes(),num_points:e.num_points(),num_faces:e instanceof this.draco.Mesh?e.num_faces():0,metadata:s,attributes:r}}_getDracoAttributes(e,t){const i={};for(let s=0;sthis.decoder[e])).includes(s)){const t=new this.draco.AttributeQuantizationTransform;try{if(t.InitFromAttribute(e))return{quantization_bits:t.quantization_bits(),range:t.range(),min_values:new Float32Array([1,2,3]).map((e=>t.min_value(e)))}}finally{this.draco.destroy(t)}}return null}_getOctahedronTransform(e,t){const{octahedronAttributes:i=[]}=t,s=e.attribute_type();if(i.map((e=>this.decoder[e])).includes(s)){const t=new this.draco.AttributeQuantizationTransform;try{if(t.InitFromAttribute(e))return{quantization_bits:t.quantization_bits()}}finally{this.draco.destroy(t)}}return null}}const rB="https://www.gstatic.com/draco/versioned/decoders/".concat("1.4.1","/draco_decoder.js"),oB="https://www.gstatic.com/draco/versioned/decoders/".concat("1.4.1","/draco_wasm_wrapper.js"),nB="https://www.gstatic.com/draco/versioned/decoders/".concat("1.4.1","/draco_decoder.wasm");let aB;async function lB(e){const t=e.modules||{};return aB=t.draco3d?aB||t.draco3d.createDecoderModule({}).then((e=>({draco:e}))):aB||async function(e){let t,i;if("js"===(e.draco&&e.draco.decoderType))t=await gv(rB,"draco",e);else[t,i]=await Promise.all([await gv(oB,"draco",e),await gv(nB,"draco",e)]);return t=t||globalThis.DracoDecoderModule,await function(e,t){const i={};t&&(i.wasmBinary=t);return new Promise((t=>{e({...i,onModuleLoaded:e=>t({draco:e})})}))}(t,i)}(e),await aB}const AB={...Ix,parse:async function(e,t){const{draco:i}=await lB(t),s=new sB(i);try{return s.parseSync(e,null==t?void 0:t.draco)}finally{s.destroy()}}};function hB(e){const{buffer:t,size:i,count:s}=function(e){let t=e,i=1,s=0;e&&e.value&&(t=e.value,i=e.size||1);t&&(ArrayBuffer.isView(t)||(t=function(e,t,i=!1){if(!e)return null;if(Array.isArray(e))return new t(e);if(i&&!(e instanceof t))return new t(e);return e}(t,Float32Array)),s=t.length/i);return{buffer:t,size:i,count:s}}(e);return{value:t,size:i,byteOffset:0,count:s,type:dx(i),componentType:px(t)}}async function cB(e,t,i,s){const r=e.getObjectExtension(t,"KHR_draco_mesh_compression");if(!r)return;const o=e.getTypedArrayForBufferView(r.bufferView),n=Bv(o.buffer,o.byteOffset),{parse:a}=s,l={...i};delete l["3d-tiles"];const A=await a(n,AB,l,s),h=function(e){const t={};for(const i in e){const s=e[i];if("indices"!==i){const e=hB(s);t[i]=e}}return t}(A.attributes);for(const[i,s]of Object.entries(h))if(i in t.attributes){const r=t.attributes[i],o=e.getAccessor(r);null!=o&&o.min&&null!=o&&o.max&&(s.min=o.min,s.max=o.max)}t.attributes=h,A.indices&&(t.indices=hB(A.indices)),function(e){if(!e.attributes&&Object.keys(e.attributes).length>0)throw new Error("glTF: Empty primitive detected: Draco decompression failure?")}(t)}function uB(e,t,i=4,s,r){var o;if(!s.DracoWriter)throw new Error("options.gltf.DracoWriter not provided");const n=s.DracoWriter.encodeSync({attributes:e}),a=null==r||null===(o=r.parseSync)||void 0===o?void 0:o.call(r,{attributes:e}),l=s._addFauxAttributes(a.attributes);return{primitives:[{attributes:l,mode:i,extensions:{KHR_draco_mesh_compression:{bufferView:s.addBufferView(n),attributes:l}}}]}}function*dB(e){for(const t of e.json.meshes||[])for(const e of t.primitives)yield e}var pB=Object.freeze({__proto__:null,name:"KHR_draco_mesh_compression",preprocess:function(e,t,i){const s=new mx(e);for(const e of dB(s))s.getObjectExtension(e,"KHR_draco_mesh_compression")},decode:async function(e,t,i){var s;if(null==t||null===(s=t.gltf)||void 0===s||!s.decompressMeshes)return;const r=new mx(e),o=[];for(const e of dB(r))r.getObjectExtension(e,"KHR_draco_mesh_compression")&&o.push(cB(r,e,t,i));await Promise.all(o),r.removeExtension("KHR_draco_mesh_compression")},encode:function(e,t={}){const i=new mx(e);for(const e of i.json.meshes||[])uB(e),i.addRequiredExtension("KHR_draco_mesh_compression")}});var fB=Object.freeze({__proto__:null,name:"KHR_lights_punctual",decode:async function(e){const t=new mx(e),{json:i}=t,s=t.getExtension("KHR_lights_punctual");s&&(t.json.lights=s.lights,t.removeExtension("KHR_lights_punctual"));for(const e of i.nodes||[]){const i=t.getObjectExtension(e,"KHR_lights_punctual");i&&(e.light=i.light),t.removeObjectExtension(e,"KHR_lights_punctual")}},encode:async function(e){const t=new mx(e),{json:i}=t;if(i.lights){const e=t.addExtension("KHR_lights_punctual");ox(!e.lights),e.lights=i.lights,delete i.lights}if(t.json.lights){for(const e of t.json.lights){const i=e.node;t.addObjectExtension(i,"KHR_lights_punctual",e)}delete t.json.lights}}});function gB(e,t){const i=Object.assign({},e.values);return Object.keys(e.uniforms||{}).forEach((t=>{e.uniforms[t].value&&!(t in i)&&(i[t]=e.uniforms[t].value)})),Object.keys(i).forEach((e=>{"object"==typeof i[e]&&void 0!==i[e].index&&(i[e].texture=t.getTexture(i[e].index))})),i}const mB=[Mx,Ex,Fx,pB,fB,Object.freeze({__proto__:null,name:"KHR_materials_unlit",decode:async function(e){const t=new mx(e),{json:i}=t;t.removeExtension("KHR_materials_unlit");for(const e of i.materials||[]){e.extensions&&e.extensions.KHR_materials_unlit&&(e.unlit=!0),t.removeObjectExtension(e,"KHR_materials_unlit")}},encode:function(e){const t=new mx(e),{json:i}=t;if(t.materials)for(const e of i.materials||[])e.unlit&&(delete e.unlit,t.addObjectExtension(e,"KHR_materials_unlit",{}),t.addExtension("KHR_materials_unlit"))}}),Object.freeze({__proto__:null,name:"KHR_techniques_webgl",decode:async function(e){const t=new mx(e),{json:i}=t,s=t.getExtension("KHR_techniques_webgl");if(s){const e=function(e,t){const{programs:i=[],shaders:s=[],techniques:r=[]}=e,o=new TextDecoder;return s.forEach((e=>{if(!Number.isFinite(e.bufferView))throw new Error("KHR_techniques_webgl: no shader code");e.code=o.decode(t.getTypedArrayForBufferView(e.bufferView))})),i.forEach((e=>{e.fragmentShader=s[e.fragmentShader],e.vertexShader=s[e.vertexShader]})),r.forEach((e=>{e.program=i[e.program]})),r}(s,t);for(const s of i.materials||[]){const i=t.getObjectExtension(s,"KHR_techniques_webgl");i&&(s.technique=Object.assign({},i,e[i.technique]),s.technique.values=gB(s.technique,t)),t.removeObjectExtension(s,"KHR_techniques_webgl")}t.removeExtension("KHR_techniques_webgl")}},encode:async function(e,t){}})];function _B(e,t){var i;const s=(null==t||null===(i=t.gltf)||void 0===i?void 0:i.excludeExtensions)||{};return!(e in s&&!s[e])}const vB={accessors:"accessor",animations:"animation",buffers:"buffer",bufferViews:"bufferView",images:"image",materials:"material",meshes:"mesh",nodes:"node",samplers:"sampler",scenes:"scene",skins:"skin",textures:"texture"},bB={accessor:"accessors",animations:"animation",buffer:"buffers",bufferView:"bufferViews",image:"images",material:"materials",mesh:"meshes",node:"nodes",sampler:"samplers",scene:"scenes",skin:"skins",texture:"textures"};class yB{constructor(){tv(this,"idToIndexMap",{animations:{},accessors:{},buffers:{},bufferViews:{},images:{},materials:{},meshes:{},nodes:{},samplers:{},scenes:{},skins:{},textures:{}}),tv(this,"json",void 0)}normalize(e,t){this.json=e.json;const i=e.json;switch(i.asset&&i.asset.version){case"2.0":return;case void 0:case"1.0":break;default:return void console.warn("glTF: Unknown version ".concat(i.asset.version))}if(!t.normalize)throw new Error("glTF v1 is not supported.");console.warn("Converting glTF v1 to glTF v2 format. This is experimental and may fail."),this._addAsset(i),this._convertTopLevelObjectsToArrays(i),function(e){const t=new mx(e),{json:i}=t;for(const e of i.images||[]){const i=t.getObjectExtension(e,"KHR_binary_glTF");i&&Object.assign(e,i),t.removeObjectExtension(e,"KHR_binary_glTF")}i.buffers&&i.buffers[0]&&delete i.buffers[0].uri,t.removeExtension("KHR_binary_glTF")}(e),this._convertObjectIdsToArrayIndices(i),this._updateObjects(i),this._updateMaterial(i)}_addAsset(e){e.asset=e.asset||{},e.asset.version="2.0",e.asset.generator=e.asset.generator||"Normalized to glTF 2.0 by loaders.gl"}_convertTopLevelObjectsToArrays(e){for(const t in vB)this._convertTopLevelObjectToArray(e,t)}_convertTopLevelObjectToArray(e,t){const i=e[t];if(i&&!Array.isArray(i)){e[t]=[];for(const s in i){const r=i[s];r.id=r.id||s;const o=e[t].length;e[t].push(r),this.idToIndexMap[t][s]=o}}}_convertObjectIdsToArrayIndices(e){for(const t in vB)this._convertIdsToIndices(e,t);"scene"in e&&(e.scene=this._convertIdToIndex(e.scene,"scene"));for(const t of e.textures)this._convertTextureIds(t);for(const t of e.meshes)this._convertMeshIds(t);for(const t of e.nodes)this._convertNodeIds(t);for(const t of e.scenes)this._convertSceneIds(t)}_convertTextureIds(e){e.source&&(e.source=this._convertIdToIndex(e.source,"image"))}_convertMeshIds(e){for(const t of e.primitives){const{attributes:e,indices:i,material:s}=t;for(const t in e)e[t]=this._convertIdToIndex(e[t],"accessor");i&&(t.indices=this._convertIdToIndex(i,"accessor")),s&&(t.material=this._convertIdToIndex(s,"material"))}}_convertNodeIds(e){e.children&&(e.children=e.children.map((e=>this._convertIdToIndex(e,"node")))),e.meshes&&(e.meshes=e.meshes.map((e=>this._convertIdToIndex(e,"mesh"))))}_convertSceneIds(e){e.nodes&&(e.nodes=e.nodes.map((e=>this._convertIdToIndex(e,"node"))))}_convertIdsToIndices(e,t){e[t]||(console.warn("gltf v1: json doesn't contain attribute ".concat(t)),e[t]=[]);for(const i of e[t])for(const e in i){const t=i[e],s=this._convertIdToIndex(t,e);i[e]=s}}_convertIdToIndex(e,t){const i=bB[t];if(i in this.idToIndexMap){const s=this.idToIndexMap[i][e];if(!Number.isFinite(s))throw new Error("gltf v1: failed to resolve ".concat(t," with id ").concat(e));return s}return e}_updateObjects(e){for(const e of this.json.buffers)delete e.type}_updateMaterial(e){for(const s of e.materials){var t,i;s.pbrMetallicRoughness={baseColorFactor:[1,1,1,1],metallicFactor:1,roughnessFactor:1};const r=(null===(t=s.values)||void 0===t?void 0:t.tex)||(null===(i=s.values)||void 0===i?void 0:i.texture2d_0),o=e.textures.findIndex((e=>e.id===r));-1!==o&&(s.pbrMetallicRoughness.baseColorTexture={index:o})}}}const xB={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},BB={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},wB=10240,PB=10241,CB=10242,MB=10243,EB=10497,FB={magFilter:wB,minFilter:PB,wrapS:CB,wrapT:MB},IB={[wB]:9729,[PB]:9986,[CB]:EB,[MB]:EB};class DB{constructor(){tv(this,"baseUri",""),tv(this,"json",{}),tv(this,"buffers",[]),tv(this,"images",[])}postProcess(e,t={}){const{json:i,buffers:s=[],images:r=[],baseUri:o=""}=e;return ox(i),this.baseUri=o,this.json=i,this.buffers=s,this.images=r,this._resolveTree(this.json,t),this.json}_resolveTree(e,t={}){e.bufferViews&&(e.bufferViews=e.bufferViews.map(((e,t)=>this._resolveBufferView(e,t)))),e.images&&(e.images=e.images.map(((e,t)=>this._resolveImage(e,t)))),e.samplers&&(e.samplers=e.samplers.map(((e,t)=>this._resolveSampler(e,t)))),e.textures&&(e.textures=e.textures.map(((e,t)=>this._resolveTexture(e,t)))),e.accessors&&(e.accessors=e.accessors.map(((e,t)=>this._resolveAccessor(e,t)))),e.materials&&(e.materials=e.materials.map(((e,t)=>this._resolveMaterial(e,t)))),e.meshes&&(e.meshes=e.meshes.map(((e,t)=>this._resolveMesh(e,t)))),e.nodes&&(e.nodes=e.nodes.map(((e,t)=>this._resolveNode(e,t)))),e.skins&&(e.skins=e.skins.map(((e,t)=>this._resolveSkin(e,t)))),e.scenes&&(e.scenes=e.scenes.map(((e,t)=>this._resolveScene(e,t)))),void 0!==e.scene&&(e.scene=e.scenes[this.json.scene])}getScene(e){return this._get("scenes",e)}getNode(e){return this._get("nodes",e)}getSkin(e){return this._get("skins",e)}getMesh(e){return this._get("meshes",e)}getMaterial(e){return this._get("materials",e)}getAccessor(e){return this._get("accessors",e)}getCamera(e){return null}getTexture(e){return this._get("textures",e)}getSampler(e){return this._get("samplers",e)}getImage(e){return this._get("images",e)}getBufferView(e){return this._get("bufferViews",e)}getBuffer(e){return this._get("buffers",e)}_get(e,t){if("object"==typeof t)return t;const i=this.json[e]&&this.json[e][t];return i||console.warn("glTF file error: Could not find ".concat(e,"[").concat(t,"]")),i}_resolveScene(e,t){return e.id=e.id||"scene-".concat(t),e.nodes=(e.nodes||[]).map((e=>this.getNode(e))),e}_resolveNode(e,t){return e.id=e.id||"node-".concat(t),e.children&&(e.children=e.children.map((e=>this.getNode(e)))),void 0!==e.mesh?e.mesh=this.getMesh(e.mesh):void 0!==e.meshes&&e.meshes.length&&(e.mesh=e.meshes.reduce(((e,t)=>{const i=this.getMesh(t);return e.id=i.id,e.primitives=e.primitives.concat(i.primitives),e}),{primitives:[]})),void 0!==e.camera&&(e.camera=this.getCamera(e.camera)),void 0!==e.skin&&(e.skin=this.getSkin(e.skin)),e}_resolveSkin(e,t){return e.id=e.id||"skin-".concat(t),e.inverseBindMatrices=this.getAccessor(e.inverseBindMatrices),e}_resolveMesh(e,t){return e.id=e.id||"mesh-".concat(t),e.primitives&&(e.primitives=e.primitives.map((e=>{const t=(e={...e}).attributes;e.attributes={};for(const i in t)e.attributes[i]=this.getAccessor(t[i]);return void 0!==e.indices&&(e.indices=this.getAccessor(e.indices)),void 0!==e.material&&(e.material=this.getMaterial(e.material)),e}))),e}_resolveMaterial(e,t){if(e.id=e.id||"material-".concat(t),e.normalTexture&&(e.normalTexture={...e.normalTexture},e.normalTexture.texture=this.getTexture(e.normalTexture.index)),e.occlusionTexture&&(e.occlustionTexture={...e.occlustionTexture},e.occlusionTexture.texture=this.getTexture(e.occlusionTexture.index)),e.emissiveTexture&&(e.emmisiveTexture={...e.emmisiveTexture},e.emissiveTexture.texture=this.getTexture(e.emissiveTexture.index)),e.emissiveFactor||(e.emissiveFactor=e.emmisiveTexture?[1,1,1]:[0,0,0]),e.pbrMetallicRoughness){e.pbrMetallicRoughness={...e.pbrMetallicRoughness};const t=e.pbrMetallicRoughness;t.baseColorTexture&&(t.baseColorTexture={...t.baseColorTexture},t.baseColorTexture.texture=this.getTexture(t.baseColorTexture.index)),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture={...t.metallicRoughnessTexture},t.metallicRoughnessTexture.texture=this.getTexture(t.metallicRoughnessTexture.index))}return e}_resolveAccessor(e,t){var i,s;if(e.id=e.id||"accessor-".concat(t),void 0!==e.bufferView&&(e.bufferView=this.getBufferView(e.bufferView)),e.bytesPerComponent=(i=e.componentType,BB[i]),e.components=(s=e.type,xB[s]),e.bytesPerElement=e.bytesPerComponent*e.components,e.bufferView){const t=e.bufferView.buffer,{ArrayType:i,byteLength:s}=fx(e,e.bufferView),r=(e.bufferView.byteOffset||0)+(e.byteOffset||0)+t.byteOffset;let o=t.arrayBuffer.slice(r,r+s);e.bufferView.byteStride&&(o=this._getValueFromInterleavedBuffer(t,r,e.bufferView.byteStride,e.bytesPerElement,e.count)),e.value=new i(o)}return e}_getValueFromInterleavedBuffer(e,t,i,s,r){const o=new Uint8Array(r*s);for(let n=0;n20);const s=t.getUint32(i+0,TB),r=t.getUint32(i+4,TB);return i+=8,z_(0===r),LB(e,t,i,s),i+=s,i+=UB(e,t,i,e.header.byteLength)}(e,r,i);case 2:return function(e,t,i,s){return z_(e.header.byteLength>20),function(e,t,i,s){for(;i+8<=e.header.byteLength;){const r=t.getUint32(i+0,TB),o=t.getUint32(i+4,TB);switch(i+=8,o){case 1313821514:LB(e,t,i,r);break;case 5130562:UB(e,t,i,r);break;case 0:s.strict||LB(e,t,i,r);break;case 1:s.strict||UB(e,t,i,r)}i+=wv(r,4)}}(e,t,i,s),i+e.header.byteLength}(e,r,i,{});default:throw new Error("Invalid GLB version ".concat(e.version,". Only supports v1 and v2."))}}function LB(e,t,i,s){const r=new Uint8Array(t.buffer,i,s),o=new TextDecoder("utf8").decode(r);return e.json=JSON.parse(o),wv(s,4)}function UB(e,t,i,s){return e.header.hasBinChunk=!0,e.binChunks.push({byteOffset:i,byteLength:s,arrayBuffer:t.buffer}),wv(s,4)}async function kB(e,t,i=0,s,r){var o,n,a,l;!function(e,t,i,s){s.uri&&(e.baseUri=s.uri);if(t instanceof ArrayBuffer&&!function(e,t=0,i={}){const s=new DataView(e),{magic:r=SB}=i,o=s.getUint32(t,!1);return o===r||o===SB}(t,i,s)){t=(new TextDecoder).decode(t)}if("string"==typeof t)e.json=bv(t);else if(t instanceof ArrayBuffer){const r={};i=RB(r,t,i,s.glb),ox("glTF"===r.type,"Invalid GLB magic string ".concat(r.type)),e._glb=r,e.json=r.json}else ox(!1,"GLTF: must be ArrayBuffer or string");const r=e.json.buffers||[];if(e.buffers=new Array(r.length).fill(null),e._glb&&e._glb.header.hasBinChunk){const{binChunks:t}=e._glb;e.buffers[0]={arrayBuffer:t[0].arrayBuffer,byteOffset:t[0].byteOffset,byteLength:t[0].byteLength}}const o=e.json.images||[];e.images=new Array(o.length).fill({})}(e,t,i,s),function(e,t={}){(new yB).normalize(e,t)}(e,{normalize:null==s||null===(o=s.gltf)||void 0===o?void 0:o.normalize}),function(e,t={},i){const s=mB.filter((e=>_B(e.name,t)));for(const o of s){var r;null===(r=o.preprocess)||void 0===r||r.call(o,e,t,i)}}(e,s,r);const A=[];if(null!=s&&null!==(n=s.gltf)&&void 0!==n&&n.loadBuffers&&e.json.buffers&&await async function(e,t,i){const s=e.json.buffers||[];for(let n=0;n_B(e.name,t)));for(const o of s){var r;await(null===(r=o.decode)||void 0===r?void 0:r.call(o,e,t,i))}}(e,s,r);return A.push(h),await Promise.all(A),null!=s&&null!==(l=s.gltf)&&void 0!==l&&l.postProcess?function(e,t){return(new DB).postProcess(e,t)}(e,s):e}async function OB(e,t,i,s,r){const{fetch:o,parse:n}=r;let a;if(t.uri){const e=nx(t.uri,s),i=await o(e);a=await i.arrayBuffer()}if(Number.isFinite(t.bufferView)){const i=function(e,t,i){const s=e.bufferViews[i];ox(s);const r=t[s.buffer];ox(r);const o=(s.byteOffset||0)+r.byteOffset;return new Uint8Array(r.arrayBuffer,o,s.byteLength)}(e.json,e.buffers,t.bufferView);a=Bv(i.buffer,i.byteOffset,i.byteLength)}ox(a,"glTF image has no data");let l=await n(a,[tx,Oy],{mimeType:t.mimeType,basis:s.basis||{format:ky()}},r);l&&l[0]&&(l={compressed:!0,mipmaps:!1,width:l[0].width,height:l[0].height,data:l[0]}),e.images=e.images||[],e.images[i]=l}const NB={name:"glTF",id:"gltf",module:"gltf",version:"3.2.6",extensions:["gltf","glb"],mimeTypes:["model/gltf+json","model/gltf-binary"],text:!0,binary:!0,tests:["glTF"],parse:async function(e,t={},i){(t={...NB.options,...t}).gltf={...NB.options.gltf,...t.gltf};const{byteOffset:s=0}=t;return await kB({},e,s,t,i)},options:{gltf:{normalize:!0,loadBuffers:!0,loadImages:!0,decompressMeshes:!0,postProcess:!0},log:console},deprecatedOptions:{fetchImages:"gltf.loadImages",createImages:"gltf.loadImages",decompress:"gltf.decompressMeshes",postProcess:"gltf.postProcess",gltf:{decompress:"gltf.decompressMeshes"}}};class QB{constructor(e){}load(e,t,i,s,r,o,n){!function(e,t,i,s,r,o,n){const a=e.viewer.scene.canvas.spinner;a.processes++;"glb"===t.split(".").pop()?e.dataSource.getGLB(t,(n=>{s.basePath=VB(t),HB(e,t,n,i,s,r,o),a.processes--}),(e=>{a.processes--,n(e)})):e.dataSource.getGLTF(t,(n=>{s.basePath=VB(t),HB(e,t,n,i,s,r,o),a.processes--}),(e=>{a.processes--,n(e)}))}(e,t,i,s=s||{},r,(function(){M.scheduleTask((function(){r.scene.fire("modelLoaded",r.id),r.fire("loaded",!0,!1)})),o&&o()}),(function(t){e.error(t),n&&n(t),r.fire("error",t)}))}parse(e,t,i,s,r,o,n){HB(e,"",t,i,s=s||{},r,(function(){r.scene.fire("modelLoaded",r.id),r.fire("loaded",!0,!1),o&&o()}))}}function VB(e){const t=e.lastIndexOf("/");return 0!==t?e.substring(0,t+1):""}function HB(e,t,i,s,r,o,n){const a=e.viewer.scene.canvas.spinner;a.processes++,ry(i,NB,{baseUri:r.basePath}).then((i=>{const l={src:t,entityId:r.entityId,metaModelJSON:s,autoMetaModel:r.autoMetaModel,metaObjects:[],loadBuffer:r.loadBuffer,basePath:r.basePath,handlenode:r.handlenode,backfaces:!!r.backfaces,gltfData:i,scene:o.scene,plugin:e,sceneModel:o,numObjects:0,nodes:[],nextId:0,log:t=>{e.log(t)}};!function(e){const t=e.gltfData.textures;if(t)for(let i=0,s=t.length;i{const i=t.mesh;i&&(i.instances||=0,i.instances+=1),t.children&&e(t.children)}))}(s);const r=[];let o=null;!function t(i,s,n){i.forEach((i=>{const a=i.name;let l=null!=a&&a||0===s&&"entity-"+e.nextId++;if(l){for(;e.sceneModel.objects[l];)l="entity-"+e.nextId++;r.push(o),o=[]}const A=function(e,t){let i;e.matrix&&(i=e.matrix,t=t?c.mulMat4(t,i,c.mat4()):i);e.translation&&(i=c.translationMat4v(e.translation),t=t?c.mulMat4(t,i,c.mat4()):i);e.rotation&&(i=c.quaternionToMat4(e.rotation),t=t?c.mulMat4(t,i,c.mat4()):i);e.scale&&(i=c.scalingMat4v(e.scale),t=t?c.mulMat4(t,i,c.mat4()):i);return t}(i,n);i.mesh&&function(e,t,i,s){const r=e.mesh;if(!r)return;const o=r.primitives.length;if(o>0)for(let e=0;e0&&(e.sceneModel.createEntity({id:l,meshIds:o,isObject:!0}),e.autoMetaModel&&e.metaObjects.push({id:l,type:"Default",name:l,parent:e.sceneModel.id})),o=r.pop())}))}(s,0,null)}(l),o.finalize(),r.autoMetaModel&&e.viewer.metaScene.createMetaModel(o.id,{metaObjects:l.metaObjects}),a.processes--,n()}))}function jB(e,t){if(!t.source||!t.source.image)return;const i="texture-"+e.nextId++;let s=1005;switch(t.sampler.minFilter){case 9728:s=1003;break;case 9729:s=1006;break;case 9984:s=1004;break;case 9985:s=1007;break;case 9986:s=1005;break;case 9987:s=1008}let r=1006;switch(t.sampler.magFilter){case 9728:r=1003;break;case 9729:r=1006}let o=1e3;switch(t.sampler.wrapS){case 33071:o=1001;break;case 33648:o=1002;break;case 10497:o=1e3}let n=1e3;switch(t.sampler.wrapT){case 33071:n=1001;break;case 33648:n=1002;break;case 10497:n=1e3}let a=1e3;switch(t.sampler.wrapR){case 33071:a=1001;break;case 33648:a=1002;break;case 10497:a=1e3}e.sceneModel.createTexture({id:i,image:t.source.image,flipY:!!t.flipY,minFilter:s,magFilter:r,wrapS:o,wrapT:n,wrapR:a,encoding:3001}),t._textureId=i}function GB(e,t){const i={};switch(t.normalTexture&&(i.normalTextureId=t.normalTexture.texture._textureId),t.occlusionTexture&&(i.occlusionTextureId=t.occlusionTexture.texture._textureId),t.emissiveTexture&&(i.emissiveTextureId=t.emissiveTexture.texture._textureId),t.alphaMode){case"OPAQUE":break;case"MASK":const e=t.alphaCutoff;i.alphaCutoff=void 0!==e?e:.5}const s=t.pbrMetallicRoughness;if(t.pbrMetallicRoughness){const r=t.pbrMetallicRoughness,o=r.baseColorTexture||r.colorTexture;o&&(o.texture?i.colorTextureId=o.texture._textureId:i.colorTextureId=e.gltfData.textures[o.index]._textureId),s.metallicRoughnessTexture&&(i.metallicRoughnessTextureId=s.metallicRoughnessTexture.texture._textureId)}const r=t.extensions;if(r){const t=r.KHR_materials_pbrSpecularGlossiness;if(t){t.specularTexture;const s=t.specularColorTexture;null!=s&&(i.colorTextureId=e.gltfData.textures[s.index]._textureId)}}return void 0!==i.normalTextureId||void 0!==i.occlusionTextureId||void 0!==i.emissiveTextureId||void 0!==i.colorTextureId||void 0!==i.metallicRoughnessTextureId?(i.id=`textureSet-${e.nextId++};`,e.sceneModel.createTextureSet(i),i.id):null}function zB(e,t){const i=t.extensions,s={color:new Float32Array([1,1,1,1]),opacity:1,metallic:0,roughness:1,doubleSided:!0};if(i){const e=i.KHR_materials_pbrSpecularGlossiness;if(e){const t=e.diffuseFactor;null!=t&&s.color.set(t)}const t=i.KHR_materials_common;if(t){const e=t.technique,i=t.values||{},r="BLINN"===e,o="PHONG"===e,n="LAMBERT"===e,a=i.diffuse;a&&(r||o||n)&&(_.isString(a)||s.color.set(a));const l=i.transparency;null!=l&&(s.opacity=l);const A=i.transparent;null!=A&&(s.opacity=A)}}const r=t.pbrMetallicRoughness;if(r){const e=r.baseColorFactor;e&&(s.color[0]=e[0],s.color[1]=e[1],s.color[2]=e[2],s.opacity=e[3]);const t=r.metallicFactor;null!=t&&(s.metallic=t);const i=r.roughnessFactor;null!=i&&(s.roughness=i)}return s.doubleSided=!1!==t.doubleSided,s}const WB={DEFAULT:{}};function KB(e,t,i={}){const s="lightgrey",r=i.hoverColor||"rgba(0,0,0,0.4)",o=i.textColor||"black",n=500,a=n+n/3,l=a/24,A=[{boundary:[6,6,6,6],color:i.frontColor||i.color||"#55FF55"},{boundary:[18,6,6,6],color:i.backColor||i.color||"#55FF55"},{boundary:[12,6,6,6],color:i.rightColor||i.color||"#FF5555"},{boundary:[0,6,6,6],color:i.leftColor||i.color||"#FF5555"},{boundary:[6,0,6,6],color:i.topColor||i.color||"#7777FF"},{boundary:[6,12,6,6],color:i.bottomColor||i.color||"#7777FF"}],h=[{label:"NavCube.front",boundaries:[[7,7,4,4]],dir:[0,1,0],up:[0,0,1]},{label:"NavCube.back",boundaries:[[19,7,4,4]],dir:[0,-1,0],up:[0,0,1]},{label:"NavCube.right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,0,1]},{label:"NavCube.left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,0,1]},{label:"NavCube.top",boundaries:[[7,1,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"NavCube.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]}];i.frontColor||i.color,i.backColor||i.color,i.rightColor||i.color,i.leftColor||i.color,i.topColor||i.color,i.bottomColor||i.color;const u=[{yUp:"",label:"NavCube.front",boundaries:[[7,7,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"NavCube.back",boundaries:[[19,7,4,4]],dir:[0,0,1],up:[0,1,0]},{label:"NavCube.right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,1,0]},{label:"NavCube.left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,1,0]},{label:"NavCube.top",boundaries:[[7,1,4,4]],dir:[0,-1,0],up:[0,0,-1]},{label:"NavCube.bottom",boundaries:[[7,13,4,4]],dir:[0,1,0],up:[0,0,1]},{boundaries:[[7,5,4,2]],dir:[0,-.7071,-.7071],up:[0,.7071,-.7071]},{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,-.7071,.7071],up:[0,.7071,.7071]},{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:[.5,.7071,-.5],up:[-.5,.7071,.5]},{boundaries:[[23,11,1,1],[6,17,1,1],[0,11,1,1]],dir:[.5,.7071,.5],up:[-.5,.7071,-.5]},{boundaries:[[5,5,2,2]],dir:[.5,-.7071,-.5],up:[.5,.7071,-.5]},{boundaries:[[11,17,1,1],[17,11,2,1]],dir:[-.5,.7071,.5],up:[.5,.7071,-.5]},{boundaries:[[17,6,2,1],[11,0,1,1]],dir:[-.5,-.7071,.5],up:[-.5,.7071,.5]},{boundaries:[[11,11,2,2]],dir:[-.5,.7071,-.5],up:[.5,.7071,.5]},{boundaries:[[0,6,1,1],[6,0,1,1],[23,6,1,1]],dir:[.5,-.7071,.5],up:[.5,.7071,.5]},{boundaries:[[11,5,2,2]],dir:[-.5,-.7071,-.5],up:[-.5,.7071,-.5]}];for(let e=0,t=h.length;e=r[0]*l&&t<=(r[0]+r[2])*l&&i>=r[1]*l&&i<=(r[1]+r[3])*l)return s}}return-1},this.setAreaHighlighted=function(e,t){var i=d[e];if(!i)throw"Area not found: "+e;i.highlighted=!!t,g()},this.getAreaDir=function(e){var t=d[e];if(!t)throw"Unknown area: "+e;return t.dir},this.getAreaUp=function(e){var t=d[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)}}const XB=c.vec3(),JB=c.vec3();c.mat4();const YB=c.vec3();class ZB{load(e,t,i={}){var s=e.scene.canvas.spinner;s.processes++,qB(e,t,(function(t){!function(e,t,i){for(var s=t.basePath,r=Object.keys(t.materialLibraries),o=r.length,n=0,a=o;n=0?i-1:i+t/3)}function r(e,t){var i=parseInt(e,10);return 3*(i>=0?i-1:i+t/3)}function o(e,t){var i=parseInt(e,10);return 2*(i>=0?i-1:i+t/2)}function n(e,t,i,s){var r=e.positions,o=e.object.geometry.positions;o.push(r[t+0]),o.push(r[t+1]),o.push(r[t+2]),o.push(r[i+0]),o.push(r[i+1]),o.push(r[i+2]),o.push(r[s+0]),o.push(r[s+1]),o.push(r[s+2])}function a(e,t){var i=e.positions,s=e.object.geometry.positions;s.push(i[t+0]),s.push(i[t+1]),s.push(i[t+2])}function l(e,t,i,s){var r=e.normals,o=e.object.geometry.normals;o.push(r[t+0]),o.push(r[t+1]),o.push(r[t+2]),o.push(r[i+0]),o.push(r[i+1]),o.push(r[i+2]),o.push(r[s+0]),o.push(r[s+1]),o.push(r[s+2])}function A(e,t,i,s){var r=e.uv,o=e.object.geometry.uv;o.push(r[t+0]),o.push(r[t+1]),o.push(r[i+0]),o.push(r[i+1]),o.push(r[s+0]),o.push(r[s+1])}function h(e,t){var i=e.uv,s=e.object.geometry.uv;s.push(i[t+0]),s.push(i[t+1])}function c(e,t,i,a,h,c,u,d,p,f,g,m,_){var v,b=e.positions.length,y=s(t,b),x=s(i,b),B=s(a,b);if(void 0===h?n(e,y,x,B):(n(e,y,x,v=s(h,b)),n(e,x,B,v)),void 0!==c){var w=e.uv.length;y=o(c,w),x=o(u,w),B=o(d,w),void 0===h?A(e,y,x,B):(A(e,y,x,v=o(p,w)),A(e,x,B,v))}if(void 0!==f){var P=e.normals.length;y=r(f,P),x=f===g?y:r(g,P),B=f===m?y:r(m,P),void 0===h?l(e,y,x,B):(l(e,y,x,v=r(_,P)),l(e,x,B,v))}}function u(e,t,i){e.object.geometry.type="Line";for(var r=e.positions.length,n=e.uv.length,l=0,A=t.length;l=0?n.substring(0,a):n).toLowerCase(),A=(A=a>=0?n.substring(a+1):"").trim(),l.toLowerCase()){case"newmtl":i(e,u),u={id:A},d=!0;break;case"ka":u.ambient=s(A);break;case"kd":u.diffuse=s(A);break;case"ks":u.specular=s(A);break;case"map_kd":u.diffuseMap||(u.diffuseMap=t(e,o,A,"sRGB"));break;case"map_ks":u.specularMap||(u.specularMap=t(e,o,A,"linear"));break;case"map_bump":case"bump":u.normalMap||(u.normalMap=t(e,o,A));break;case"ns":u.shininess=parseFloat(A);break;case"d":(h=parseFloat(A))<1&&(u.alpha=h,u.alphaMode="blend");break;case"tr":(h=parseFloat(A))>0&&(u.alpha=1-h,u.alphaMode="blend")}d&&i(e,u)};function t(e,t,i,s){var r={},o=i.split(/\s+/),n=o.indexOf("-bm");return n>=0&&o.splice(n,2),(n=o.indexOf("-s"))>=0&&(r.scale=[parseFloat(o[n+1]),parseFloat(o[n+2])],o.splice(n,4)),(n=o.indexOf("-o"))>=0&&(r.translate=[parseFloat(o[n+1]),parseFloat(o[n+2])],o.splice(n,4)),r.src=t+o.join(" ").trim(),r.flipY=!0,r.encoding=s||"linear",new Ss(e,r).id}function i(e,t){new Jt(e,t)}function s(t){var i=t.split(e,3);return[parseFloat(i[0]),parseFloat(i[1]),parseFloat(i[2])]}}();function iw(e,t){for(var i=0,s=t.objects.length;i0&&(n.normals=o.normals),o.uv.length>0&&(n.uv=o.uv);for(var a=new Array(n.positions.length/3),l=0;l{this._setPos(this._sectionPlane.pos)})),this._onSectionPlaneDir=e.on("dir",(()=>{this._ignoreNextSectionPlaneDirUpdate?this._ignoreNextSectionPlaneDirUpdate=!1:this._setDir(this._sectionPlane.dir)})))}get sectionPlane(){return this._sectionPlane}_setPos(e){this._pos.set(e),W(this._pos,this._origin,this._rtcPos),this._rootNode.origin=this._origin,this._rootNode.position=this._rtcPos}_setDir(e){this._baseDir.set(e),this._rootNode.quaternion=c.vec3PairToQuaternion(rw,e,ow)}_setSectionPlaneDir(e){this._sectionPlane&&(this._ignoreNextSectionPlaneDirUpdate=!0,this._sectionPlane.dir=e)}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=!1,t=this._viewer.scene,i=.01;this._rootNode=new gs(t,{position:[0,0,0],scale:[5,5,5],isObject:!1});const s=this._rootNode,r={arrowHead:new Gt(s,is({radiusTop:.001,radiusBottom:.07,radialSegments:32,heightSegments:1,height:.2,openEnded:!1})),arrowHeadBig:new Gt(s,is({radiusTop:.001,radiusBottom:.09,radialSegments:32,heightSegments:1,height:.25,openEnded:!1})),arrowHeadHandle:new Gt(s,is({radiusTop:.09,radiusBottom:.09,radialSegments:8,heightSegments:1,height:.37,openEnded:!1})),curve:new Gt(s,Qs({radius:.8,tube:i,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),curveHandle:new Gt(s,Qs({radius:.8,tube:.06,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),hoop:new Gt(s,Qs({radius:.8,tube:i,radialSegments:64,tubeSegments:8,arc:2*Math.PI})),axis:new Gt(s,is({radiusTop:i,radiusBottom:i,radialSegments:20,heightSegments:1,height:1,openEnded:!1})),axisHandle:new Gt(s,is({radiusTop:.08,radiusBottom:.08,radialSegments:20,heightSegments:1,height:1,openEnded:!1}))},o={pickable:new Jt(s,{diffuse:[1,1,0],alpha:0,alphaMode:"blend"}),red:new Jt(s,{diffuse:[1,0,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightRed:new Zt(s,{edges:!1,fill:!0,fillColor:[1,0,0],fillAlpha:.6}),green:new Jt(s,{diffuse:[0,1,0],emissive:[0,1,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightGreen:new Zt(s,{edges:!1,fill:!0,fillColor:[0,1,0],fillAlpha:.6}),blue:new Jt(s,{diffuse:[0,0,1],emissive:[0,0,1],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightBlue:new Zt(s,{edges:!1,fill:!0,fillColor:[0,0,1],fillAlpha:.2}),center:new Jt(s,{diffuse:[0,0,0],emissive:[0,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80}),highlightBall:new Zt(s,{edges:!1,fill:!0,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1}),highlightPlane:new Zt(s,{edges:!0,edgeWidth:3,fill:!1,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1})};this._displayMeshes={plane:s.addChild(new es(s,{geometry:new Gt(s,{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 Jt(s,{emissive:[0,0,0],diffuse:[0,0,0],backfaces:!0}),opacity:.6,ghosted:!0,ghostMaterial:new Zt(s,{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],isObject:!1}),e),planeFrame:s.addChild(new es(s,{geometry:new Gt(s,Qs({center:[0,0,0],radius:1.7,tube:.02,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new Jt(s,{emissive:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],shininess:0}),highlightMaterial:new Zt(s,{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],isObject:!1}),e),xCurve:s.addChild(new es(s,{geometry:r.curve,material:o.red,matrix:function(){const e=c.rotationMat4v(90*c.DEGTORAD,[0,1,0],c.identityMat4()),t=c.rotationMat4v(270*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xCurveHandle:s.addChild(new es(s,{geometry:r.curveHandle,material:o.pickable,matrix:function(){const e=c.rotationMat4v(90*c.DEGTORAD,[0,1,0],c.identityMat4()),t=c.rotationMat4v(270*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xCurveArrow1:s.addChild(new es(s,{geometry:r.arrowHead,material:o.red,matrix:function(){const e=c.translateMat4c(0,-.07,-.8,c.identityMat4()),t=c.scaleMat4v([.6,.6,.6],c.identityMat4()),i=c.rotationMat4v(0*c.DEGTORAD,[0,0,1],c.identityMat4());return c.mulMat4(c.mulMat4(e,t,c.identityMat4()),i,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xCurveArrow2:s.addChild(new es(s,{geometry:r.arrowHead,material:o.red,matrix:function(){const e=c.translateMat4c(0,-.8,-.07,c.identityMat4()),t=c.scaleMat4v([.6,.6,.6],c.identityMat4()),i=c.rotationMat4v(90*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(c.mulMat4(e,t,c.identityMat4()),i,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yCurve:s.addChild(new es(s,{geometry:r.curve,material:o.green,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),yCurveHandle:s.addChild(new es(s,{geometry:r.curveHandle,material:o.pickable,rotation:[-90,0,0],pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),yCurveArrow1:s.addChild(new es(s,{geometry:r.arrowHead,material:o.green,matrix:function(){const e=c.translateMat4c(.07,0,-.8,c.identityMat4()),t=c.scaleMat4v([.6,.6,.6],c.identityMat4()),i=c.rotationMat4v(90*c.DEGTORAD,[0,0,1],c.identityMat4());return c.mulMat4(c.mulMat4(e,t,c.identityMat4()),i,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yCurveArrow2:s.addChild(new es(s,{geometry:r.arrowHead,material:o.green,matrix:function(){const e=c.translateMat4c(.8,0,-.07,c.identityMat4()),t=c.scaleMat4v([.6,.6,.6],c.identityMat4()),i=c.rotationMat4v(90*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(c.mulMat4(e,t,c.identityMat4()),i,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurve:s.addChild(new es(s,{geometry:r.curve,material:o.blue,matrix:c.rotationMat4v(180*c.DEGTORAD,[1,0,0],c.identityMat4()),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveHandle:s.addChild(new es(s,{geometry:r.curveHandle,material:o.pickable,matrix:c.rotationMat4v(180*c.DEGTORAD,[1,0,0],c.identityMat4()),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveCurveArrow1:s.addChild(new es(s,{geometry:r.arrowHead,material:o.blue,matrix:function(){const e=c.translateMat4c(.8,-.07,0,c.identityMat4()),t=c.scaleMat4v([.6,.6,.6],c.identityMat4());return c.mulMat4(e,t,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveArrow2:s.addChild(new es(s,{geometry:r.arrowHead,material:o.blue,matrix:function(){const e=c.translateMat4c(.05,-.8,0,c.identityMat4()),t=c.scaleMat4v([.6,.6,.6],c.identityMat4()),i=c.rotationMat4v(90*c.DEGTORAD,[0,0,1],c.identityMat4());return c.mulMat4(c.mulMat4(e,t,c.identityMat4()),i,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),center:s.addChild(new es(s,{geometry:new Gt(s,ss({radius:.05})),material:o.center,pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisArrow:s.addChild(new es(s,{geometry:r.arrowHead,material:o.red,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[0,0,1],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisArrowHandle:s.addChild(new es(s,{geometry:r.arrowHeadHandle,material:o.pickable,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[0,0,1],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxis:s.addChild(new es(s,{geometry:r.axis,material:o.red,matrix:function(){const e=c.translateMat4c(0,.5,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[0,0,1],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisHandle:s.addChild(new es(s,{geometry:r.axisHandle,material:o.pickable,matrix:function(){const e=c.translateMat4c(0,.5,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[0,0,1],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrow:s.addChild(new es(s,{geometry:r.arrowHead,material:o.green,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(180*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrowHandle:s.addChild(new es(s,{geometry:r.arrowHeadHandle,material:o.pickable,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(180*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,opacity:.2,isObject:!1}),e),yShaft:s.addChild(new es(s,{geometry:r.axis,material:o.green,position:[0,-.5,0],pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yShaftHandle:s.addChild(new es(s,{geometry:r.axisHandle,material:o.pickable,position:[0,-.5,0],pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrow:s.addChild(new es(s,{geometry:r.arrowHead,material:o.blue,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[.8,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrowHandle:s.addChild(new es(s,{geometry:r.arrowHeadHandle,material:o.pickable,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[.8,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zShaft:s.addChild(new es(s,{geometry:r.axis,material:o.blue,matrix:function(){const e=c.translateMat4c(0,.5,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),clippable:!1,pickable:!1,collidable:!0,visible:!1,isObject:!1}),e),zAxisHandle:s.addChild(new es(s,{geometry:r.axisHandle,material:o.pickable,matrix:function(){const e=c.translateMat4c(0,.5,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),clippable:!1,pickable:!0,collidable:!0,visible:!1,isObject:!1}),e)},this._affordanceMeshes={planeFrame:s.addChild(new es(s,{geometry:new Gt(s,Qs({center:[0,0,0],radius:2,tube:i,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new Jt(s,{ambient:[1,1,1],diffuse:[0,0,0],emissive:[1,1,0]}),highlighted:!0,highlightMaterial:new Zt(s,{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],isObject:!1}),e),xHoop:s.addChild(new es(s,{geometry:r.hoop,material:o.red,highlighted:!0,highlightMaterial:o.highlightRed,matrix:function(){const e=c.rotationMat4v(90*c.DEGTORAD,[0,1,0],c.identityMat4()),t=c.rotationMat4v(270*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yHoop:s.addChild(new es(s,{geometry:r.hoop,material:o.green,highlighted:!0,highlightMaterial:o.highlightGreen,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zHoop:s.addChild(new es(s,{geometry:r.hoop,material:o.blue,highlighted:!0,highlightMaterial:o.highlightBlue,matrix:c.rotationMat4v(180*c.DEGTORAD,[1,0,0],c.identityMat4()),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xAxisArrow:s.addChild(new es(s,{geometry:r.arrowHeadBig,material:o.red,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[0,0,1],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrow:s.addChild(new es(s,{geometry:r.arrowHeadBig,material:o.green,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(180*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrow:s.addChild(new es(s,{geometry:r.arrowHeadBig,material:o.blue,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[.8,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e)}}_bindEvents(){const e=this;var t=!1;const i=-1,s=0,r=1,o=2,n=3,a=4,l=5,A=this._rootNode;var h=null,u=null;const d=c.vec2(),p=c.vec3([1,0,0]),f=c.vec3([0,1,0]),g=c.vec3([0,0,1]),m=this._viewer.scene.canvas.canvas,_=this._viewer.camera,v=this._viewer.scene;{const e=c.vec3([0,0,0]);let t=-1;this._onCameraViewMatrix=v.camera.on("viewMatrix",(()=>{})),this._onCameraProjMatrix=v.camera.on("projMatrix",(()=>{})),this._onSceneTick=v.on("tick",(()=>{const i=Math.abs(c.lenVec3(c.subVec3(v.camera.eye,this._pos,e)));if(i!==t&&"perspective"===_.projection){const e=.07*(Math.tan(_.perspective.fov*c.DEGTORAD)*i);A.scale=[e,e,e],t=i}if("ortho"===_.projection){const e=_.ortho.scale/10;A.scale=[e,e,e],t=i}}))}const b=function(){const e=new Float64Array(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}}(),y=function(){const t=c.mat4();return function(i,s){return c.quaternionToMat4(e._rootNode.quaternion,t),c.transformVec3(t,i,s),c.normalizeVec3(s),s}}();var x=function(){const e=c.vec3();return function(t){const i=Math.abs(t[0]);return i>Math.abs(t[1])&&i>Math.abs(t[2])?c.cross3Vec3(t,[0,1,0],e):c.cross3Vec3(t,[1,0,0],e),c.cross3Vec3(e,t,e),c.normalizeVec3(e),e}}();const B=function(){const t=c.vec3(),i=c.vec3(),s=c.vec4();return function(r,o,n){y(r,s);const a=x(s,o,n);P(o,a,t),P(n,a,i),c.subVec3(i,t);const l=c.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 w=function(){const t=c.vec4(),i=c.vec4(),s=c.vec4(),r=c.vec4();return function(o,n,a){y(o,r);if(!(P(n,r,t)&&P(a,r,i))){const e=x(r,n,a);P(n,e,t,1),P(a,e,i,1);var l=c.dotVec3(t,r);t[0]-=l*r[0],t[1]-=l*r[1],t[2]-=l*r[2],l=c.dotVec3(i,r),i[0]-=l*r[0],i[1]-=l*r[1],i[2]-=l*r[2]}c.normalizeVec3(t),c.normalizeVec3(i),l=c.dotVec3(t,i),l=c.clamp(l,-1,1);var A=Math.acos(l)*c.RADTODEG;c.cross3Vec3(t,i,s),c.dotVec3(s,r)<0&&(A=-A),e._rootNode.rotate(o,A),C()}}(),P=function(){const t=c.vec4([0,0,0,1]),i=c.mat4();return function(s,r,o,n){n=n||0,t[0]=s[0]/m.width*2-1,t[1]=-(s[1]/m.height*2-1),t[2]=0,t[3]=1,c.mulMat4(_.projMatrix,_.viewMatrix,i),c.inverseMat4(i),c.transformVec4(i,t,t),c.mulVec4Scalar(t,1/t[3]);var a=_.eye;c.subVec4(t,a,t);const l=e._sectionPlane.pos;var A=-c.dotVec3(l,r)-n,h=c.dotVec3(r,t);if(Math.abs(h)>.005){var u=-(c.dotVec3(r,a)+A)/h;return c.mulVec3Scalar(t,u,o),c.addVec3(o,a),c.subVec3(o,l,o),!0}return!1}}();const C=function(){const t=c.vec3(),i=c.mat4();return function(){e.sectionPlane&&(c.quaternionToMat4(A.quaternion,i),c.transformVec3(i,[0,0,1],t),e._setSectionPlaneDir(t))}}();var M,E=!1;this._onCameraControlHover=this._viewer.cameraControl.on("hoverEnter",(e=>{if(!this._visible)return;if(E)return;var A;t=!1,M&&(M.visible=!1);switch(e.entity.id){case this._displayMeshes.xAxisArrowHandle.id:case this._displayMeshes.xAxisHandle.id:A=this._affordanceMeshes.xAxisArrow,h=s;break;case this._displayMeshes.yAxisArrowHandle.id:case this._displayMeshes.yShaftHandle.id:A=this._affordanceMeshes.yAxisArrow,h=r;break;case this._displayMeshes.zAxisArrowHandle.id:case this._displayMeshes.zAxisHandle.id:A=this._affordanceMeshes.zAxisArrow,h=o;break;case this._displayMeshes.xCurveHandle.id:A=this._affordanceMeshes.xHoop,h=n;break;case this._displayMeshes.yCurveHandle.id:A=this._affordanceMeshes.yHoop,h=a;break;case this._displayMeshes.zCurveHandle.id:A=this._affordanceMeshes.zHoop,h=l;break;default:return void(h=i)}A&&(A.visible=!0),M=A,t=!0})),this._onCameraControlHoverLeave=this._viewer.cameraControl.on("hoverOutEntity",(e=>{this._visible&&(M&&(M.visible=!1),M=null,h=i)})),m.addEventListener("mousedown",this._canvasMouseDownListener=e=>{if(e.preventDefault(),this._visible&&t&&(this._viewer.cameraControl.pointerEnabled=!1,1===e.which)){E=!0;var i=b(e);u=h,d[0]=i[0],d[1]=i[1]}}),m.addEventListener("mousemove",this._canvasMouseMoveListener=e=>{if(!this._visible)return;if(!E)return;var t=b(e);const i=t[0],A=t[1];switch(u){case s:B(p,d,t);break;case r:B(f,d,t);break;case o:B(g,d,t);break;case n:w(p,d,t);break;case a:w(f,d,t);break;case l:w(g,d,t)}d[0]=i,d[1]=A}),m.addEventListener("mouseup",this._canvasMouseUpListener=e=>{this._visible&&(this._viewer.cameraControl.pointerEnabled=!0,E&&(e.which,E=!1,t=!1))}),m.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._setSectionPlane(null),this._rootNode.destroy(),this._displayMeshes={},this._affordanceMeshes={}}}class aw{constructor(e,t,i){this.id=i.id,this._sectionPlane=i,this._mesh=new es(t,{id:i.id,geometry:new Gt(t,zt({xSize:.5,ySize:.5,zSize:.001})),material:new Jt(t,{emissive:[1,1,1],diffuse:[0,0,0],backfaces:!1}),edgeMaterial:new $t(t,{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),highlightMaterial:new Zt(t,{fill:!0,fillColor:[.5,1,.5],fillAlpha:.7,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),selectedMaterial:new Zt(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=c.vec3([0,0,0]),t=c.vec3(),i=c.vec3([0,0,1]),s=c.vec4(4),r=c.vec3(),o=()=>{const o=this._sectionPlane.scene.center,n=[-this._sectionPlane.dir[0],-this._sectionPlane.dir[1],-this._sectionPlane.dir[2]];c.subVec3(o,this._sectionPlane.pos,e);const a=-c.dotVec3(n,e);c.normalizeVec3(n),c.mulVec3Scalar(n,a,t);const l=c.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 lw{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 Ai(this._viewer,{canvasId:this._canvas.id,transparent:!0}),this._scene.clearLights(),new Dt(this._scene,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new Dt(this._scene,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new Dt(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=c.rotationMat4c(-90*c.DEGTORAD,1,0,0),i=c.vec3(),s=c.vec3(),r=c.vec3();this._synchCamera=()=>{const o=this._viewer.camera.eye,n=this._viewer.camera.look,a=this._viewer.camera.up;c.mulVec3Scalar(c.normalizeVec3(c.subVec3(o,n,i)),7),this._zUp?(c.transformVec3(t,i,s),c.transformVec3(t,a,r),e.look=[0,0,0],e.eye=c.transformVec3(t,i,s),e.up=c.transformPoint3(t,a,r)):(e.look=[0,0,0],e.eye=i,e.up=a)}}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}));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 aw(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._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 Aw=c.AABB3(),hw=c.vec3();class cw{constructor(e,t,i,s,r,o){this.plugin=e,this.storeyId=r,this.modelId=s,this.storeyAABB=i.slice(),this.aabb=this.storeyAABB,this.modelAABB=t.slice(),this.numObjects=o}}class uw{constructor(e,t,i,s,r,o){this.storeyId=e,this.imageData=t,this.format=i,this.width=s,this.height=r}}const dw=c.vec3(),pw=c.mat4();const fw=new Float64Array([0,0,1]),gw=new Float64Array(4);class mw{constructor(e){this.id=null,this._viewer=e.viewer,this._plugin=e,this._visible=!1,this._pos=c.vec3(),this._origin=c.vec3(),this._rtcPos=c.vec3(),this._baseDir=c.vec3(),this._rootNode=null,this._displayMeshes=null,this._affordanceMeshes=null,this._ignoreNextSectionPlaneDirUpdate=!1,this._createNodes(),this._bindEvents()}_setSectionPlane(e){this._sectionPlane&&(this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._onSectionPlanePos=null,this._onSectionPlaneDir=null,this._sectionPlane=null),e&&(this.id=e.id,this._setPos(e.pos),this._setDir(e.dir),this._sectionPlane=e,this._onSectionPlanePos=e.on("pos",(()=>{this._setPos(this._sectionPlane.pos)})),this._onSectionPlaneDir=e.on("dir",(()=>{this._ignoreNextSectionPlaneDirUpdate?this._ignoreNextSectionPlaneDirUpdate=!1:this._setDir(this._sectionPlane.dir)})))}get sectionPlane(){return this._sectionPlane}_setPos(e){this._pos.set(e),W(this._pos,this._origin,this._rtcPos),this._rootNode.origin=this._origin,this._rootNode.position=this._rtcPos}_setDir(e){this._baseDir.set(e),this._rootNode.quaternion=c.vec3PairToQuaternion(fw,e,gw)}_setSectionPlaneDir(e){this._sectionPlane&&(this._ignoreNextSectionPlaneDirUpdate=!0,this._sectionPlane.dir=e)}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=!1,t=this._viewer.scene,i=.01;this._rootNode=new gs(t,{position:[0,0,0],scale:[5,5,5]});const s=this._rootNode,r={arrowHead:new Gt(s,is({radiusTop:.001,radiusBottom:.07,radialSegments:32,heightSegments:1,height:.2,openEnded:!1})),arrowHeadBig:new Gt(s,is({radiusTop:.001,radiusBottom:.09,radialSegments:32,heightSegments:1,height:.25,openEnded:!1})),axis:new Gt(s,is({radiusTop:i,radiusBottom:i,radialSegments:20,heightSegments:1,height:1,openEnded:!1}))},o={red:new Jt(s,{diffuse:[1,0,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),green:new Jt(s,{diffuse:[0,1,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),blue:new Jt(s,{diffuse:[0,0,1],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightRed:new Zt(s,{edges:!1,fill:!0,fillColor:[1,0,0],fillAlpha:.6})};this._displayMeshes={plane:s.addChild(new es(s,{geometry:new Gt(s,{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 Jt(s,{emissive:[0,0,0],diffuse:[0,0,0],backfaces:!0}),opacity:.6,ghosted:!0,pickable:!1,collidable:!0,clippable:!1,visible:!1,scale:[2.4,2.4,1]}),e),planeFrame:s.addChild(new es(s,{geometry:new Gt(s,Qs({center:[0,0,0],radius:1.7,tube:.02,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new Jt(s,{emissive:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],shininess:0}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,.1],rotation:[0,0,45]}),e),center:s.addChild(new es(s,{geometry:new Gt(s,ss({radius:.05})),material:o.center,pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),zAxisArrow:s.addChild(new es(s,{geometry:r.arrowHead,material:o.blue,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[.8,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),zShaft:s.addChild(new es(s,{geometry:r.axis,material:o.blue,matrix:function(){const e=c.translateMat4c(0,.5,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),clippable:!1,pickable:!1,collidable:!0,visible:!1}),e)},this._affordanceMeshes={planeFrame:s.addChild(new es(s,{geometry:new Gt(s,Qs({center:[0,0,0],radius:2,tube:i,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new Jt(s,{ambient:[1,1,1],diffuse:[0,0,0],emissive:[1,1,0]}),highlighted:!0,highlightMaterial:new Zt(s,{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]}),e),zAxisArrow:s.addChild(new es(s,{geometry:r.arrowHeadBig,material:o.blue,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[.8,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e)}}_bindEvents(){const e=this._rootNode,t=c.vec2(),i=this._viewer.camera,s=this._viewer.scene;let r=0,o=!1;{const t=c.vec3([0,0,0]);let n=-1;this._onCameraViewMatrix=s.camera.on("viewMatrix",(()=>{})),this._onCameraProjMatrix=s.camera.on("projMatrix",(()=>{})),this._onSceneTick=s.on("tick",(()=>{o=!1;const l=Math.abs(c.lenVec3(c.subVec3(s.camera.eye,this._pos,t)));if(l!==n&&"perspective"===i.projection){const t=.07*(Math.tan(i.perspective.fov*c.DEGTORAD)*l);e.scale=[t,t,t],n=l}if("ortho"===i.projection){const t=i.ortho.scale/10;e.scale=[t,t,t],n=l}0!==r&&(a(r),r=0)}))}const n=function(){const e=new Float64Array(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}}(),a=e=>{const t=this._sectionPlane.pos,i=this._sectionPlane.dir;c.addVec3(t,c.mulVec3Scalar(i,.1*e*this._plugin.getDragSensitivity(),c.vec3())),this._sectionPlane.pos=t};{let e=!1;this._plugin._controlElement.addEventListener("mousedown",this._canvasMouseDownListener=i=>{if(i.preventDefault(),this._visible&&(this._viewer.cameraControl.pointerEnabled=!1,1===i.which)){e=!0;var s=n(i);t[0]=s[0],t[1]=s[1]}}),this._plugin._controlElement.addEventListener("mousemove",this._canvasMouseMoveListener=i=>{if(!this._visible)return;if(!e)return;if(o)return;var s=n(i);const r=s[0],l=s[1];a(l-t[1]),t[0]=r,t[1]=l}),this._plugin._controlElement.addEventListener("mouseup",this._canvasMouseUpListener=t=>{this._visible&&(this._viewer.cameraControl.pointerEnabled=!0,e&&(t.which,e=!1))}),this._plugin._controlElement.addEventListener("wheel",this._canvasWheelListener=e=>{this._visible&&(r+=Math.max(-1,Math.min(1,40*-e.deltaY)))})}{let e,t,i=null;this._plugin._controlElement.addEventListener("touchstart",this._handleTouchStart=t=>{t.stopPropagation(),t.preventDefault(),this._visible&&(e=t.touches[0].clientY,i=e,r=0)}),this._plugin._controlElement.addEventListener("touchmove",this._handleTouchMove=e=>{e.stopPropagation(),e.preventDefault(),this._visible&&(o||(o=!0,t=e.touches[0].clientY,null!==i&&(r+=t-i),i=t))}),this._plugin._controlElement.addEventListener("touchend",this._handleTouchEnd=i=>{i.stopPropagation(),i.preventDefault(),this._visible&&(e=null,t=null,r=0)})}}_destroy(){this._unbindEvents(),this._destroyNodes()}_unbindEvents(){const e=this._viewer,t=e.scene,i=t.canvas.canvas,s=e.camera,r=this._plugin._controlElement;t.off(this._onSceneTick),i.removeEventListener("mousedown",this._canvasMouseDownListener),i.removeEventListener("mousemove",this._canvasMouseMoveListener),i.removeEventListener("mouseup",this._canvasMouseUpListener),i.removeEventListener("wheel",this._canvasWheelListener),r.removeEventListener("touchstart",this._handleTouchStart),r.removeEventListener("touchmove",this._handleTouchMove),r.removeEventListener("touchend",this._handleTouchEnd),s.off(this._onCameraViewMatrix),s.off(this._onCameraProjMatrix)}_destroyNodes(){this._setSectionPlane(null),this._rootNode.destroy(),this._displayMeshes={},this._affordanceMeshes={}}}class _w{constructor(e,t,i){this.id=i.id,this._sectionPlane=i,this._mesh=new es(t,{id:i.id,geometry:new Gt(t,zt({xSize:.5,ySize:.5,zSize:.001})),material:new Jt(t,{emissive:[1,1,1],diffuse:[0,0,0],backfaces:!1}),edgeMaterial:new $t(t,{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),highlightMaterial:new Zt(t,{fill:!0,fillColor:[.5,1,.5],fillAlpha:.7,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),selectedMaterial:new Zt(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=c.vec3([0,0,0]),t=c.vec3(),i=c.vec3([0,0,1]),s=c.vec4(4),r=c.vec3(),o=()=>{const o=this._sectionPlane.scene.center,n=[-this._sectionPlane.dir[0],-this._sectionPlane.dir[1],-this._sectionPlane.dir[2]];c.subVec3(o,this._sectionPlane.pos,e);const a=-c.dotVec3(n,e);c.normalizeVec3(n),c.mulVec3Scalar(n,a,t);const l=c.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 vw{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 Ai(this._viewer,{canvasId:this._canvas.id,transparent:!0}),this._scene.clearLights(),new Dt(this._scene,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new Dt(this._scene,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new Dt(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=c.rotationMat4c(-90*c.DEGTORAD,1,0,0),i=c.vec3(),s=c.vec3(),r=c.vec3();this._synchCamera=()=>{const o=this._viewer.camera.eye,n=this._viewer.camera.look,a=this._viewer.camera.up;c.mulVec3Scalar(c.normalizeVec3(c.subVec3(o,n,i)),7),this._zUp?(c.transformVec3(t,i,s),c.transformVec3(t,a,r),e.look=[0,0,0],e.eye=c.transformVec3(t,i,s),e.up=c.transformPoint3(t,a,r)):(e.look=[0,0,0],e.eye=i,e.up=a)}}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}));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 _w(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._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 bw=c.AABB3(),yw=c.vec3();class xw{constructor(e={}){this.cacheBuster=!1!==e.cacheBuster}_cacheBusterURL(e){if(!this.cacheBuster)return e;const t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}getSTL(e,t,i){e=this._cacheBusterURL(e);const s=new XMLHttpRequest;s.overrideMimeType("application/json"),s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i(s.statusText))},s.send(null)}}const Bw=c.vec3();class ww{load(e,t,i,s,r,o){s=s||{};const n=e.viewer.scene.canvas.spinner;n.processes++,e.dataSource.getSTL(i,(function(i){!function(e,t,i,s){try{const r=Iw(i);Pw(r)?Cw(e,r,t,s):Mw(e,Fw(i),t,s)}catch(e){t.fire("error",e)}}(e,t,i,s);try{const o=Iw(i);Pw(o)?Cw(e,o,t,s):Mw(e,Fw(i),t,s),n.processes--,M.scheduleTask((function(){t.fire("loaded",!0,!1)})),r&&r()}catch(i){n.processes--,e.error(i),o&&o(i),t.fire("error",i)}}),(function(i){n.processes--,e.error(i),o&&o(i),t.fire("error",i)}))}parse(e,t,i,s){const r=e.viewer.scene.canvas.spinner;r.processes++;try{const o=Iw(i);Pw(o)?Cw(e,o,t,s):Mw(e,Fw(i),t,s),r.processes--,M.scheduleTask((function(){t.fire("loaded",!0,!1)}))}catch(e){r.processes--,t.fire("error",e)}}}function Pw(e){const t=new DataView(e);if(84+50*t.getUint32(80,!0)===t.byteLength)return!0;const i=[115,111,108,105,100];for(var s=0;s<5;s++)if(i[s]!==t.getUint8(s,!1))return!0;return!1}function Cw(e,t,i,s){const r=new DataView(t),o=r.getUint32(80,!0);let n,a,l,A,h,c,u,d=!1,p=null,f=null,g=null,m=!1;for(let e=0;e<70;e++)1129270351===r.getUint32(e,!1)&&82===r.getUint8(e+4)&&61===r.getUint8(e+5)&&(d=!0,A=[],h=r.getUint8(e+6)/255,c=r.getUint8(e+7)/255,u=r.getUint8(e+8)/255,r.getUint8(e+9));const _=new bs(i,{roughness:.5});let v=[],b=[],y=s.splitMeshes;for(let e=0;e>5&31)/31,l=(e>>10&31)/31):(n=h,a=c,l=u),(y&&n!==p||a!==f||l!==g)&&(null!==p&&(m=!0),p=n,f=a,g=l)}for(let e=1;e<=3;e++){let i=t+12*e;v.push(r.getFloat32(i,!0)),v.push(r.getFloat32(i+4,!0)),v.push(r.getFloat32(i+8,!0)),b.push(o,x,B),d&&A.push(n,a,l,1)}y&&m&&(Ew(i,v,b,A,_,s),v=[],b=[],A=A?[]:null,m=!1)}v.length>0&&Ew(i,v,b,A,_,s)}function Mw(e,t,i,s){const r=/facet([\s\S]*?)endfacet/g;let o=0;const n=/[\s]+([+-]?(?:\d+.\d+|\d+.|\d+|.\d+)(?:[eE][+-]?\d+)?)/.source,a=new RegExp("vertex"+n+n+n,"g"),l=new RegExp("normal"+n+n+n,"g"),A=[],h=[];let c,u,d,p,f,g,m;for(;null!==(p=r.exec(t));){for(f=0,g=0,m=p[0];null!==(p=l.exec(m));)c=parseFloat(p[1]),u=parseFloat(p[2]),d=parseFloat(p[3]),g++;for(;null!==(p=a.exec(m));)A.push(parseFloat(p[1]),parseFloat(p[2]),parseFloat(p[3])),h.push(c,u,d),f++;1!==g&&e.error("Error in normal of face "+o),3!==f&&e.error("Error in positions of face "+o),o++}Ew(i,A,h,null,new bs(i,{roughness:.5}),s)}function Ew(e,t,i,s,r,o){const n=new Int32Array(t.length/3);for(let e=0,t=n.length;e0?i:null,s=s&&s.length>0?s:null,o.smoothNormals&&c.faceToVertexNormals(t,i,o);const a=Bw;K(t,t,a);const l=new Gt(e,{primitive:"triangles",positions:t,normals:i,colors:s,indices:n}),A=new es(e,{origin:0!==a[0]||0!==a[1]||0!==a[2]?a:null,geometry:l,material:r,edges:o.edges});e.addChild(A)}function Fw(e){return"string"!=typeof e?function(e){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let i=0,s=e.length;i0){const i=document.createElement("a");i.href="#",i.id=`switch-${e.nodeId}`,i.textContent="+",i.classList.add("plus"),t&&i.addEventListener("click",t),o.appendChild(i)}const n=document.createElement("input");n.id=`checkbox-${e.nodeId}`,n.type="checkbox",n.checked=e.checked,n.style["pointer-events"]="all",i&&n.addEventListener("change",i),o.appendChild(n);const a=document.createElement("span");return a.textContent=e.title,o.appendChild(a),s&&(a.oncontextmenu=s),r&&(a.onclick=r),o}createDisabledNodeElement(e){const t=document.createElement("li"),i=document.createElement("a");i.href="#",i.textContent="!",i.classList.add("warn"),i.classList.add("warning"),t.appendChild(i);const s=document.createElement("span");return s.textContent=e,t.appendChild(s),t}addChildren(e,t){const i=document.createElement("ul");t.forEach((e=>{i.appendChild(e)})),e.parentElement.appendChild(i)}expand(e,t,i){e.classList.remove("plus"),e.classList.add("minus"),e.textContent="-",e.removeEventListener("click",t),e.addEventListener("click",i)}collapse(e,t,i){if(!e)return;const s=e.parentElement;if(!s)return;const r=s.querySelector("ul");r&&(s.removeChild(r),e.classList.remove("minus"),e.classList.add("plus"),e.textContent="+",e.removeEventListener("click",i),e.addEventListener("click",t))}isExpanded(e){return void 0!==e.parentElement.getElementsByTagName("li")[0]}getId(e){return e.parentElement.id}getIdFromCheckbox(e){return e.id.replace("checkbox-","")}getSwitchElement(e){return document.getElementById(`switch-${e}`)}isChecked(e){return e.checked}setCheckbox(e,t,i=!1){const s=document.getElementById(`checkbox-${e}`);s&&(t!==s.checked&&(s.checked=t),i!==s.indeterminate&&(s.indeterminate=i,i&&(s.checked=!1)))}setXRayed(e,t){const i=document.getElementById(e);i&&(t?i.classList.add("xrayed-node"):i.classList.remove("xrayed-node"))}setHighlighted(e,t){const i=document.getElementById(e);i&&(t?(i.scrollIntoView({block:"center"}),i.classList.add("highlighted-node")):i.classList.remove("highlighted-node"))}}const Sw=[];class Tw{constructor(e){this._scene=e,this._objects=[],this._objectsViewCulled=[],this._objectsDetailCulled=[],this._objectsChanged=[],this._objectsChangedList=[],this._modelInfos={},this._numObjects=0,this._lenObjectsChangedList=0,this._dirty=!0,this._onModelLoaded=e.on("modelLoaded",(t=>{const i=e.models[t];i&&this._addModel(i)})),this._onTick=e.on("tick",(()=>{this._dirty&&this._build(),this._applyChanges()}))}_addModel(e){const t={model:e,onDestroyed:e.on("destroyed",(()=>{this._removeModel(e)}))};this._modelInfos[e.id]=t,this._dirty=!0}_removeModel(e){const t=this._modelInfos[e.id];t&&(t.model.off(t.onDestroyed),delete this._modelInfos[e.id],this._dirty=!0)}_build(){if(!this._dirty)return;this._applyChanges();const e=this._scene.objects;for(let e=0;e0){for(let e=0;e-1?e+"&_="+t:e+"?_="+t}getManifest(e,t,i){_.loadJSON(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getMetaModel(e,t,i){_.loadJSON(this._cacheBusterURL(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),i=new Uint8Array(e);for(var n=0;n=0;)e[t]=0}const i=new Uint8Array([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]),s=new Uint8Array([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]),r=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),o=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),n=new Array(576);t(n);const a=new Array(60);t(a);const l=new Array(512);t(l);const A=new Array(256);t(A);const h=new Array(29);t(h);const c=new Array(30);function u(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}let d,p,f;function g(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}t(c);const m=e=>e<256?l[e]:l[256+(e>>>7)],_=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},v=(e,t,i)=>{e.bi_valid>16-i?(e.bi_buf|=t<>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<{v(e,i[2*t],i[2*t+1])},y=(e,t)=>{let i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1},x=(e,t,i)=>{const s=new Array(16);let r,o,n=0;for(r=1;r<=15;r++)n=n+i[r-1]<<1,s[r]=n;for(o=0;o<=t;o++){let t=e[2*o+1];0!==t&&(e[2*o]=y(s[t]++,t))}},B=e=>{let t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},w=e=>{e.bi_valid>8?_(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},P=(e,t,i,s)=>{const r=2*t,o=2*i;return e[r]{const s=e.heap[i];let r=i<<1;for(;r<=e.heap_len&&(r{let o,n,a,l,u=0;if(0!==e.sym_next)do{o=255&e.pending_buf[e.sym_buf+u++],o+=(255&e.pending_buf[e.sym_buf+u++])<<8,n=e.pending_buf[e.sym_buf+u++],0===o?b(e,n,t):(a=A[n],b(e,a+256+1,t),l=i[a],0!==l&&(n-=h[a],v(e,n,l)),o--,a=m(o),b(e,a,r),l=s[a],0!==l&&(o-=c[a],v(e,o,l)))}while(u{const i=t.dyn_tree,s=t.stat_desc.static_tree,r=t.stat_desc.has_stree,o=t.stat_desc.elems;let n,a,l,A=-1;for(e.heap_len=0,e.heap_max=573,n=0;n>1;n>=1;n--)C(e,i,n);l=o;do{n=e.heap[1],e.heap[1]=e.heap[e.heap_len--],C(e,i,1),a=e.heap[1],e.heap[--e.heap_max]=n,e.heap[--e.heap_max]=a,i[2*l]=i[2*n]+i[2*a],e.depth[l]=(e.depth[n]>=e.depth[a]?e.depth[n]:e.depth[a])+1,i[2*n+1]=i[2*a+1]=l,e.heap[1]=l++,C(e,i,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const i=t.dyn_tree,s=t.max_code,r=t.stat_desc.static_tree,o=t.stat_desc.has_stree,n=t.stat_desc.extra_bits,a=t.stat_desc.extra_base,l=t.stat_desc.max_length;let A,h,c,u,d,p,f=0;for(u=0;u<=15;u++)e.bl_count[u]=0;for(i[2*e.heap[e.heap_max]+1]=0,A=e.heap_max+1;A<573;A++)h=e.heap[A],u=i[2*i[2*h+1]+1]+1,u>l&&(u=l,f++),i[2*h+1]=u,h>s||(e.bl_count[u]++,d=0,h>=a&&(d=n[h-a]),p=i[2*h],e.opt_len+=p*(u+d),o&&(e.static_len+=p*(r[2*h+1]+d)));if(0!==f){do{for(u=l-1;0===e.bl_count[u];)u--;e.bl_count[u]--,e.bl_count[u+1]+=2,e.bl_count[l]--,f-=2}while(f>0);for(u=l;0!==u;u--)for(h=e.bl_count[u];0!==h;)c=e.heap[--A],c>s||(i[2*c+1]!==u&&(e.opt_len+=(u-i[2*c+1])*i[2*c],i[2*c+1]=u),h--)}})(e,t),x(i,A,e.bl_count)},F=(e,t,i)=>{let s,r,o=-1,n=t[1],a=0,l=7,A=4;for(0===n&&(l=138,A=3),t[2*(i+1)+1]=65535,s=0;s<=i;s++)r=n,n=t[2*(s+1)+1],++a{let s,r,o=-1,n=t[1],a=0,l=7,A=4;for(0===n&&(l=138,A=3),s=0;s<=i;s++)if(r=n,n=t[2*(s+1)+1],!(++a{v(e,0+(s?1:0),3),w(e),_(e,i),_(e,~i),i&&e.pending_buf.set(e.window.subarray(t,t+i),e.pending),e.pending+=i};var T={_tr_init:e=>{D||((()=>{let e,t,o,g,m;const _=new Array(16);for(o=0,g=0;g<28;g++)for(h[g]=o,e=0;e<1<>=7;g<30;g++)for(c[g]=m<<7,e=0;e<1<{let r,l,A=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0})(e)),E(e,e.l_desc),E(e,e.d_desc),A=(e=>{let t;for(F(e,e.dyn_ltree,e.l_desc.max_code),F(e,e.dyn_dtree,e.d_desc.max_code),E(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*o[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t})(e),r=e.opt_len+3+7>>>3,l=e.static_len+3+7>>>3,l<=r&&(r=l)):r=l=i+5,i+4<=r&&-1!==t?S(e,t,i,s):4===e.strategy||l===r?(v(e,2+(s?1:0),3),M(e,n,a)):(v(e,4+(s?1:0),3),((e,t,i,s)=>{let r;for(v(e,t-257,5),v(e,i-1,5),v(e,s-4,4),r=0;r(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(A[i]+256+1)]++,e.dyn_dtree[2*m(t)]++),e.sym_next===e.sym_end),_tr_align:e=>{v(e,2,3),b(e,256,n),(e=>{16===e.bi_valid?(_(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)}},R=(e,t,i,s)=>{let r=65535&e|0,o=e>>>16&65535|0,n=0;for(;0!==i;){n=i>2e3?2e3:i,i-=n;do{r=r+t[s++]|0,o=o+r|0}while(--n);r%=65521,o%=65521}return r|o<<16|0};const L=new Uint32Array((()=>{let e,t=[];for(var 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})());var U=(e,t,i,s)=>{const r=L,o=s+i;e^=-1;for(let i=s;i>>8^r[255&(e^t[i])];return-1^e},k={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"},O={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_MEM_ERROR:-4,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};const{_tr_init:N,_tr_stored_block:Q,_tr_flush_block:V,_tr_tally:H,_tr_align:j}=T,{Z_NO_FLUSH:G,Z_PARTIAL_FLUSH:z,Z_FULL_FLUSH:W,Z_FINISH:K,Z_BLOCK:X,Z_OK:J,Z_STREAM_END:Y,Z_STREAM_ERROR:Z,Z_DATA_ERROR:q,Z_BUF_ERROR:$,Z_DEFAULT_COMPRESSION:ee,Z_FILTERED:te,Z_HUFFMAN_ONLY:ie,Z_RLE:se,Z_FIXED:re,Z_DEFAULT_STRATEGY:oe,Z_UNKNOWN:ne,Z_DEFLATED:ae}=O,le=258,Ae=262,he=42,ce=113,ue=666,de=(e,t)=>(e.msg=k[t],t),pe=e=>2*e-(e>4?9:0),fe=e=>{let t=e.length;for(;--t>=0;)e[t]=0},ge=e=>{let t,i,s,r=e.w_size;t=e.hash_size,s=t;do{i=e.head[--s],e.head[s]=i>=r?i-r:0}while(--t);t=r,s=t;do{i=e.prev[--s],e.prev[s]=i>=r?i-r:0}while(--t)};let me=(e,t,i)=>(t<{const t=e.state;let i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,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))},ve=(e,t)=>{V(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,_e(e.strm)},be=(e,t)=>{e.pending_buf[e.pending++]=t},ye=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},xe=(e,t,i,s)=>{let r=e.avail_in;return r>s&&(r=s),0===r?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),i),1===e.state.wrap?e.adler=R(e.adler,t,r,i):2===e.state.wrap&&(e.adler=U(e.adler,t,r,i)),e.next_in+=r,e.total_in+=r,r)},Be=(e,t)=>{let i,s,r=e.max_chain_length,o=e.strstart,n=e.prev_length,a=e.nice_match;const l=e.strstart>e.w_size-Ae?e.strstart-(e.w_size-Ae):0,A=e.window,h=e.w_mask,c=e.prev,u=e.strstart+le;let d=A[o+n-1],p=A[o+n];e.prev_length>=e.good_match&&(r>>=2),a>e.lookahead&&(a=e.lookahead);do{if(i=t,A[i+n]===p&&A[i+n-1]===d&&A[i]===A[o]&&A[++i]===A[o+1]){o+=2,i++;do{}while(A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&on){if(e.match_start=t,n=s,s>=a)break;d=A[o+n-1],p=A[o+n]}}}while((t=c[t&h])>l&&0!=--r);return n<=e.lookahead?n:e.lookahead},we=e=>{const t=e.w_size;let i,s,r;do{if(s=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-Ae)&&(e.window.set(e.window.subarray(t,t+t-s),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),ge(e),s+=t),0===e.strm.avail_in)break;if(i=xe(e.strm,e.window,e.strstart+e.lookahead,s),e.lookahead+=i,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=me(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=me(e,e.ins_h,e.window[r+3-1]),e.prev[r&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=r,r++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead{let i,s,r,o=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,n=0,a=e.strm.avail_in;do{if(i=65535,r=e.bi_valid+42>>3,e.strm.avail_outs+e.strm.avail_in&&(i=s+e.strm.avail_in),i>r&&(i=r),i>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,_e(e.strm),s&&(s>i&&(s=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+s),e.strm.next_out),e.strm.next_out+=s,e.strm.avail_out-=s,e.strm.total_out+=s,e.block_start+=s,i-=s),i&&(xe(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i)}while(0===n);return a-=e.strm.avail_in,a&&(a>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=a&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-a,e.strm.next_in),e.strstart),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.block_start=e.strstart),e.high_waterr&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,r+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),r>e.strm.avail_in&&(r=e.strm.avail_in),r&&(xe(e.strm,e.window,e.strstart,r),e.strstart+=r,e.insert+=r>e.w_size-e.insert?e.w_size-e.insert:r),e.high_water>3,r=e.pending_buf_size-r>65535?65535:e.pending_buf_size-r,o=r>e.w_size?e.w_size:r,s=e.strstart-e.block_start,(s>=o||(s||t===K)&&t!==G&&0===e.strm.avail_in&&s<=r)&&(i=s>r?r:s,n=t===K&&0===e.strm.avail_in&&i===s?1:0,Q(e,e.block_start,i,n),e.block_start+=i,_e(e.strm)),n?3:1)},Ce=(e,t)=>{let i,s;for(;;){if(e.lookahead=3&&(e.ins_h=me(e,e.ins_h,e.window[e.strstart+3-1]),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-Ae&&(e.match_length=Be(e,i)),e.match_length>=3)if(s=H(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=me(e,e.ins_h,e.window[e.strstart+3-1]),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=me(e,e.ins_h,e.window[e.strstart+1]);else s=H(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(s&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===K?(ve(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(ve(e,!1),0===e.strm.avail_out)?1:2},Me=(e,t)=>{let i,s,r;for(;;){if(e.lookahead=3&&(e.ins_h=me(e,e.ins_h,e.window[e.strstart+3-1]),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=2,0!==i&&e.prev_length4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,s=H(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=me(e,e.ins_h,e.window[e.strstart+3-1]),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=2,e.strstart++,s&&(ve(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(s=H(e,0,e.window[e.strstart-1]),s&&ve(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(s=H(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===K?(ve(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(ve(e,!1),0===e.strm.avail_out)?1:2};function Ee(e,t,i,s,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=s,this.func=r}const Fe=[new Ee(0,0,0,0,Pe),new Ee(4,4,8,4,Ce),new Ee(4,5,16,8,Ce),new Ee(4,6,32,32,Ce),new Ee(4,4,16,16,Me),new Ee(8,16,32,32,Me),new Ee(8,16,128,128,Me),new Ee(8,32,128,256,Me),new Ee(32,128,258,1024,Me),new Ee(32,258,258,4096,Me)];function Ie(){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=ae,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 Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),fe(this.dyn_ltree),fe(this.dyn_dtree),fe(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),fe(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),fe(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const De=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==he&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==ce&&t.status!==ue?1:0},Se=e=>{if(De(e))return de(e,Z);e.total_in=e.total_out=0,e.data_type=ne;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?he:ce,e.adler=2===t.wrap?0:1,t.last_flush=-2,N(t),J},Te=e=>{const t=Se(e);var i;return t===J&&((i=e.state).window_size=2*i.w_size,fe(i.head),i.max_lazy_match=Fe[i.level].max_lazy,i.good_match=Fe[i.level].good_length,i.nice_match=Fe[i.level].nice_length,i.max_chain_length=Fe[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),t},Re=(e,t,i,s,r,o)=>{if(!e)return Z;let n=1;if(t===ee&&(t=6),s<0?(n=0,s=-s):s>15&&(n=2,s-=16),r<1||r>9||i!==ae||s<8||s>15||t<0||t>9||o<0||o>re||8===s&&1!==n)return de(e,Z);8===s&&(s=9);const a=new Ie;return e.state=a,a.strm=e,a.status=he,a.wrap=n,a.gzhead=null,a.w_bits=s,a.w_size=1<De(e)||2!==e.state.wrap?Z:(e.state.gzhead=t,J),ke=(e,t)=>{if(De(e)||t>X||t<0)return e?de(e,Z):Z;const i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===ue&&t!==K)return de(e,0===e.avail_out?$:Z);const s=i.last_flush;if(i.last_flush=t,0!==i.pending){if(_e(e),0===e.avail_out)return i.last_flush=-1,J}else if(0===e.avail_in&&pe(t)<=pe(s)&&t!==K)return de(e,$);if(i.status===ue&&0!==e.avail_in)return de(e,$);if(i.status===he&&0===i.wrap&&(i.status=ce),i.status===he){let t=ae+(i.w_bits-8<<4)<<8,s=-1;if(s=i.strategy>=ie||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=s<<6,0!==i.strstart&&(t|=32),t+=31-t%31,ye(i,t),0!==i.strstart&&(ye(i,e.adler>>>16),ye(i,65535&e.adler)),e.adler=1,i.status=ce,_e(e),0!==i.pending)return i.last_flush=-1,J}if(57===i.status)if(e.adler=0,be(i,31),be(i,139),be(i,8),i.gzhead)be(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),be(i,255&i.gzhead.time),be(i,i.gzhead.time>>8&255),be(i,i.gzhead.time>>16&255),be(i,i.gzhead.time>>24&255),be(i,9===i.level?2:i.strategy>=ie||i.level<2?4:0),be(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(be(i,255&i.gzhead.extra.length),be(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=U(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(be(i,0),be(i,0),be(i,0),be(i,0),be(i,0),be(i,9===i.level?2:i.strategy>=ie||i.level<2?4:0),be(i,3),i.status=ce,_e(e),0!==i.pending)return i.last_flush=-1,J;if(69===i.status){if(i.gzhead.extra){let t=i.pending,s=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+s>i.pending_buf_size;){let r=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+r),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>t&&(e.adler=U(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex+=r,_e(e),0!==i.pending)return i.last_flush=-1,J;t=0,s-=r}let r=new Uint8Array(i.gzhead.extra);i.pending_buf.set(r.subarray(i.gzindex,i.gzindex+s),i.pending),i.pending+=s,i.gzhead.hcrc&&i.pending>t&&(e.adler=U(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let t,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(e.adler=U(e.adler,i.pending_buf,i.pending-s,s)),_e(e),0!==i.pending)return i.last_flush=-1,J;s=0}t=i.gzindexs&&(e.adler=U(e.adler,i.pending_buf,i.pending-s,s)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let t,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(e.adler=U(e.adler,i.pending_buf,i.pending-s,s)),_e(e),0!==i.pending)return i.last_flush=-1,J;s=0}t=i.gzindexs&&(e.adler=U(e.adler,i.pending_buf,i.pending-s,s))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(_e(e),0!==i.pending))return i.last_flush=-1,J;be(i,255&e.adler),be(i,e.adler>>8&255),e.adler=0}if(i.status=ce,_e(e),0!==i.pending)return i.last_flush=-1,J}if(0!==e.avail_in||0!==i.lookahead||t!==G&&i.status!==ue){let s=0===i.level?Pe(i,t):i.strategy===ie?((e,t)=>{let i;for(;;){if(0===e.lookahead&&(we(e),0===e.lookahead)){if(t===G)return 1;break}if(e.match_length=0,i=H(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===K?(ve(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(ve(e,!1),0===e.strm.avail_out)?1:2})(i,t):i.strategy===se?((e,t)=>{let i,s,r,o;const n=e.window;for(;;){if(e.lookahead<=le){if(we(e),e.lookahead<=le&&t===G)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=e.strstart-1,s=n[r],s===n[++r]&&s===n[++r]&&s===n[++r])){o=e.strstart+le;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]&&re.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=H(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=H(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===K?(ve(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(ve(e,!1),0===e.strm.avail_out)?1:2})(i,t):Fe[i.level].func(i,t);if(3!==s&&4!==s||(i.status=ue),1===s||3===s)return 0===e.avail_out&&(i.last_flush=-1),J;if(2===s&&(t===z?j(i):t!==X&&(Q(i,0,0,!1),t===W&&(fe(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),_e(e),0===e.avail_out))return i.last_flush=-1,J}return t!==K?J:i.wrap<=0?Y:(2===i.wrap?(be(i,255&e.adler),be(i,e.adler>>8&255),be(i,e.adler>>16&255),be(i,e.adler>>24&255),be(i,255&e.total_in),be(i,e.total_in>>8&255),be(i,e.total_in>>16&255),be(i,e.total_in>>24&255)):(ye(i,e.adler>>>16),ye(i,65535&e.adler)),_e(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?J:Y)},Oe=e=>{if(De(e))return Z;const t=e.state.status;return e.state=null,t===ce?de(e,q):J},Ne=(e,t)=>{let i=t.length;if(De(e))return Z;const s=e.state,r=s.wrap;if(2===r||1===r&&s.status!==he||s.lookahead)return Z;if(1===r&&(e.adler=R(e.adler,t,i,0)),s.wrap=0,i>=s.w_size){0===r&&(fe(s.head),s.strstart=0,s.block_start=0,s.insert=0);let e=new Uint8Array(s.w_size);e.set(t.subarray(i-s.w_size,i),0),t=e,i=s.w_size}const o=e.avail_in,n=e.next_in,a=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,we(s);s.lookahead>=3;){let e=s.strstart,t=s.lookahead-2;do{s.ins_h=me(s,s.ins_h,s.window[e+3-1]),s.prev[e&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=e,e++}while(--t);s.strstart=e,s.lookahead=2,we(s)}return s.strstart+=s.lookahead,s.block_start=s.strstart,s.insert=s.lookahead,s.lookahead=0,s.match_length=s.prev_length=2,s.match_available=0,e.next_in=n,e.input=a,e.avail_in=o,s.wrap=r,J};const Qe=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var Ve=function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const t in i)Qe(i,t)&&(e[t]=i[t])}}return e},He=e=>{let t=0;for(let i=0,s=e.length;i=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;Ge[254]=Ge[254]=1;var ze=e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,i,s,r,o,n=e.length,a=0;for(r=0;r>>6,t[o++]=128|63&i):i<65536?(t[o++]=224|i>>>12,t[o++]=128|i>>>6&63,t[o++]=128|63&i):(t[o++]=240|i>>>18,t[o++]=128|i>>>12&63,t[o++]=128|i>>>6&63,t[o++]=128|63&i);return t},We=(e,t)=>{const i=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let s,r;const o=new Array(2*i);for(r=0,s=0;s4)o[r++]=65533,s+=n-1;else{for(t&=2===n?31:3===n?15:7;n>1&&s1?o[r++]=65533:t<65536?o[r++]=t:(t-=65536,o[r++]=55296|t>>10&1023,o[r++]=56320|1023&t)}}return((e,t)=>{if(t<65534&&e.subarray&&je)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let i="";for(let s=0;s{(t=t||e.length)>e.length&&(t=e.length);let i=t-1;for(;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+Ge[e[i]]>t?i:t},Xe=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};const Je=Object.prototype.toString,{Z_NO_FLUSH:Ye,Z_SYNC_FLUSH:Ze,Z_FULL_FLUSH:qe,Z_FINISH:$e,Z_OK:et,Z_STREAM_END:tt,Z_DEFAULT_COMPRESSION:it,Z_DEFAULT_STRATEGY:st,Z_DEFLATED:rt}=O;function ot(e){this.options=Ve({level:it,method:rt,chunkSize:16384,windowBits:15,memLevel:8,strategy:st},e||{});let 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 Xe,this.strm.avail_out=0;let i=Le(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==et)throw new Error(k[i]);if(t.header&&Ue(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?ze(t.dictionary):"[object ArrayBuffer]"===Je.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,i=Ne(this.strm,e),i!==et)throw new Error(k[i]);this._dict_set=!0}}function nt(e,t){const i=new ot(t);if(i.push(e,!0),i.err)throw i.msg||k[i.err];return i.result}ot.prototype.push=function(e,t){const i=this.strm,s=this.options.chunkSize;let r,o;if(this.ended)return!1;for(o=t===~~t?t:!0===t?$e:Ye,"string"==typeof e?i.input=ze(e):"[object ArrayBuffer]"===Je.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(s),i.next_out=0,i.avail_out=s),(o===Ze||o===qe)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(r=ke(i,o),r===tt)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),r=Oe(this.strm),this.onEnd(r),this.ended=!0,r===et;if(0!==i.avail_out){if(o>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},ot.prototype.onData=function(e){this.chunks.push(e)},ot.prototype.onEnd=function(e){e===et&&(this.result=He(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var at={Deflate:ot,deflate:nt,deflateRaw:function(e,t){return(t=t||{}).raw=!0,nt(e,t)},gzip:function(e,t){return(t=t||{}).gzip=!0,nt(e,t)},constants:O};const lt=16209;var At=function(e,t){let i,s,r,o,n,a,l,A,h,c,u,d,p,f,g,m,_,v,b,y,x,B,w,P;const C=e.state;i=e.next_in,w=e.input,s=i+(e.avail_in-5),r=e.next_out,P=e.output,o=r-(t-e.avail_out),n=r+(e.avail_out-257),a=C.dmax,l=C.wsize,A=C.whave,h=C.wnext,c=C.window,u=C.hold,d=C.bits,p=C.lencode,f=C.distcode,g=(1<>>24,u>>>=v,d-=v,v=_>>>16&255,0===v)P[r++]=65535&_;else{if(!(16&v)){if(0==(64&v)){_=p[(65535&_)+(u&(1<>>=v,d-=v),d<15&&(u+=w[i++]<>>24,u>>>=v,d-=v,v=_>>>16&255,!(16&v)){if(0==(64&v)){_=f[(65535&_)+(u&(1<a){e.msg="invalid distance too far back",C.mode=lt;break e}if(u>>>=v,d-=v,v=r-o,y>v){if(v=y-v,v>A&&C.sane){e.msg="invalid distance too far back",C.mode=lt;break e}if(x=0,B=c,0===h){if(x+=l-v,v2;)P[r++]=B[x++],P[r++]=B[x++],P[r++]=B[x++],b-=3;b&&(P[r++]=B[x++],b>1&&(P[r++]=B[x++]))}else{x=r-y;do{P[r++]=P[x++],P[r++]=P[x++],P[r++]=P[x++],b-=3}while(b>2);b&&(P[r++]=P[x++],b>1&&(P[r++]=P[x++]))}break}}break}}while(i>3,i-=b,d-=b<<3,u&=(1<{const l=a.bits;let A,h,c,u,d,p,f=0,g=0,m=0,_=0,v=0,b=0,y=0,x=0,B=0,w=0,P=null;const C=new Uint16Array(16),M=new Uint16Array(16);let E,F,I,D=null;for(f=0;f<=15;f++)C[f]=0;for(g=0;g=1&&0===C[_];_--);if(v>_&&(v=_),0===_)return r[o++]=20971520,r[o++]=20971520,a.bits=1,0;for(m=1;m<_&&0===C[m];m++);for(v0&&(0===e||1!==_))return-1;for(M[1]=0,f=1;f<15;f++)M[f+1]=M[f]+C[f];for(g=0;g852||2===e&&B>592)return 1;for(;;){E=f-y,n[g]+1=p?(F=D[n[g]-p],I=P[n[g]-p]):(F=96,I=0),A=1<>y)+h]=E<<24|F<<16|I|0}while(0!==h);for(A=1<>=1;if(0!==A?(w&=A-1,w+=A):w=0,g++,0==--C[f]){if(f===_)break;f=t[i+n[g]]}if(f>v&&(w&u)!==c){for(0===y&&(y=v),d+=m,b=f-y,x=1<852||2===e&&B>592)return 1;c=w&u,r[c]=v<<24|b<<16|d-o|0}}return 0!==w&&(r[d+w]=f-y<<24|64<<16|0),a.bits=v,0};const{Z_FINISH:ft,Z_BLOCK:gt,Z_TREES:mt,Z_OK:_t,Z_STREAM_END:vt,Z_NEED_DICT:bt,Z_STREAM_ERROR:yt,Z_DATA_ERROR:xt,Z_MEM_ERROR:Bt,Z_BUF_ERROR:wt,Z_DEFLATED:Pt}=O,Ct=16180,Mt=16190,Et=16191,Ft=16192,It=16194,Dt=16199,St=16200,Tt=16206,Rt=16209,Lt=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function Ut(){this.strm=null,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 Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const kt=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode16211?1:0},Ot=e=>{if(kt(e))return yt;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=Ct,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,_t},Nt=e=>{if(kt(e))return yt;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,Ot(e)},Qt=(e,t)=>{let i;if(kt(e))return yt;const s=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?yt:(null!==s.window&&s.wbits!==t&&(s.window=null),s.wrap=i,s.wbits=t,Nt(e))},Vt=(e,t)=>{if(!e)return yt;const i=new Ut;e.state=i,i.strm=e,i.window=null,i.mode=Ct;const s=Qt(e,t);return s!==_t&&(e.state=null),s};let Ht,jt,Gt=!0;const zt=e=>{if(Gt){Ht=new Int32Array(512),jt=new Int32Array(32);let t=0;for(;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(pt(1,e.lens,0,288,Ht,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;pt(2,e.lens,0,32,jt,0,e.work,{bits:5}),Gt=!1}e.lencode=Ht,e.lenbits=9,e.distcode=jt,e.distbits=5},Wt=(e,t,i,s)=>{let r;const o=e.state;return null===o.window&&(o.wsize=1<=o.wsize?(o.window.set(t.subarray(i-o.wsize,i),0),o.wnext=0,o.whave=o.wsize):(r=o.wsize-o.wnext,r>s&&(r=s),o.window.set(t.subarray(i-s,i-s+r),o.wnext),(s-=r)?(o.window.set(t.subarray(i-s,i),0),o.wnext=s,o.whave=o.wsize):(o.wnext+=r,o.wnext===o.wsize&&(o.wnext=0),o.whave{let i,s,r,o,n,a,l,A,h,c,u,d,p,f,g,m,_,v,b,y,x,B,w=0;const P=new Uint8Array(4);let C,M;const E=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(kt(e)||!e.output||!e.input&&0!==e.avail_in)return yt;i=e.state,i.mode===Et&&(i.mode=Ft),n=e.next_out,r=e.output,l=e.avail_out,o=e.next_in,s=e.input,a=e.avail_in,A=i.hold,h=i.bits,c=a,u=l,B=_t;e:for(;;)switch(i.mode){case Ct:if(0===i.wrap){i.mode=Ft;break}for(;h<16;){if(0===a)break e;a--,A+=s[o++]<>>8&255,i.check=U(i.check,P,2,0),A=0,h=0,i.mode=16181;break}if(i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&A)<<8)+(A>>8))%31){e.msg="incorrect header check",i.mode=Rt;break}if((15&A)!==Pt){e.msg="unknown compression method",i.mode=Rt;break}if(A>>>=4,h-=4,x=8+(15&A),0===i.wbits&&(i.wbits=x),x>15||x>i.wbits){e.msg="invalid window size",i.mode=Rt;break}i.dmax=1<>8&1),512&i.flags&&4&i.wrap&&(P[0]=255&A,P[1]=A>>>8&255,i.check=U(i.check,P,2,0)),A=0,h=0,i.mode=16182;case 16182:for(;h<32;){if(0===a)break e;a--,A+=s[o++]<>>8&255,P[2]=A>>>16&255,P[3]=A>>>24&255,i.check=U(i.check,P,4,0)),A=0,h=0,i.mode=16183;case 16183:for(;h<16;){if(0===a)break e;a--,A+=s[o++]<>8),512&i.flags&&4&i.wrap&&(P[0]=255&A,P[1]=A>>>8&255,i.check=U(i.check,P,2,0)),A=0,h=0,i.mode=16184;case 16184:if(1024&i.flags){for(;h<16;){if(0===a)break e;a--,A+=s[o++]<>>8&255,i.check=U(i.check,P,2,0)),A=0,h=0}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&i.flags&&(d=i.length,d>a&&(d=a),d&&(i.head&&(x=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(s.subarray(o,o+d),x)),512&i.flags&&4&i.wrap&&(i.check=U(i.check,s,d,o)),a-=d,o+=d,i.length-=d),i.length))break e;i.length=0,i.mode=16186;case 16186:if(2048&i.flags){if(0===a)break e;d=0;do{x=s[o+d++],i.head&&x&&i.length<65536&&(i.head.name+=String.fromCharCode(x))}while(x&&d>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=Et;break;case 16189:for(;h<32;){if(0===a)break e;a--,A+=s[o++]<>>=7&h,h-=7&h,i.mode=Tt;break}for(;h<3;){if(0===a)break e;a--,A+=s[o++]<>>=1,h-=1,3&A){case 0:i.mode=16193;break;case 1:if(zt(i),i.mode=Dt,t===mt){A>>>=2,h-=2;break e}break;case 2:i.mode=16196;break;case 3:e.msg="invalid block type",i.mode=Rt}A>>>=2,h-=2;break;case 16193:for(A>>>=7&h,h-=7&h;h<32;){if(0===a)break e;a--,A+=s[o++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=Rt;break}if(i.length=65535&A,A=0,h=0,i.mode=It,t===mt)break e;case It:i.mode=16195;case 16195:if(d=i.length,d){if(d>a&&(d=a),d>l&&(d=l),0===d)break e;r.set(s.subarray(o,o+d),n),a-=d,o+=d,l-=d,n+=d,i.length-=d;break}i.mode=Et;break;case 16196:for(;h<14;){if(0===a)break e;a--,A+=s[o++]<>>=5,h-=5,i.ndist=1+(31&A),A>>>=5,h-=5,i.ncode=4+(15&A),A>>>=4,h-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=Rt;break}i.have=0,i.mode=16197;case 16197:for(;i.have>>=3,h-=3}for(;i.have<19;)i.lens[E[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,C={bits:i.lenbits},B=pt(0,i.lens,0,19,i.lencode,0,i.work,C),i.lenbits=C.bits,B){e.msg="invalid code lengths set",i.mode=Rt;break}i.have=0,i.mode=16198;case 16198:for(;i.have>>24,m=w>>>16&255,_=65535&w,!(g<=h);){if(0===a)break e;a--,A+=s[o++]<>>=g,h-=g,i.lens[i.have++]=_;else{if(16===_){for(M=g+2;h>>=g,h-=g,0===i.have){e.msg="invalid bit length repeat",i.mode=Rt;break}x=i.lens[i.have-1],d=3+(3&A),A>>>=2,h-=2}else if(17===_){for(M=g+3;h>>=g,h-=g,x=0,d=3+(7&A),A>>>=3,h-=3}else{for(M=g+7;h>>=g,h-=g,x=0,d=11+(127&A),A>>>=7,h-=7}if(i.have+d>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=Rt;break}for(;d--;)i.lens[i.have++]=x}}if(i.mode===Rt)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=Rt;break}if(i.lenbits=9,C={bits:i.lenbits},B=pt(1,i.lens,0,i.nlen,i.lencode,0,i.work,C),i.lenbits=C.bits,B){e.msg="invalid literal/lengths set",i.mode=Rt;break}if(i.distbits=6,i.distcode=i.distdyn,C={bits:i.distbits},B=pt(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,C),i.distbits=C.bits,B){e.msg="invalid distances set",i.mode=Rt;break}if(i.mode=Dt,t===mt)break e;case Dt:i.mode=St;case St:if(a>=6&&l>=258){e.next_out=n,e.avail_out=l,e.next_in=o,e.avail_in=a,i.hold=A,i.bits=h,At(e,u),n=e.next_out,r=e.output,l=e.avail_out,o=e.next_in,s=e.input,a=e.avail_in,A=i.hold,h=i.bits,i.mode===Et&&(i.back=-1);break}for(i.back=0;w=i.lencode[A&(1<>>24,m=w>>>16&255,_=65535&w,!(g<=h);){if(0===a)break e;a--,A+=s[o++]<>v)],g=w>>>24,m=w>>>16&255,_=65535&w,!(v+g<=h);){if(0===a)break e;a--,A+=s[o++]<>>=v,h-=v,i.back+=v}if(A>>>=g,h-=g,i.back+=g,i.length=_,0===m){i.mode=16205;break}if(32&m){i.back=-1,i.mode=Et;break}if(64&m){e.msg="invalid literal/length code",i.mode=Rt;break}i.extra=15&m,i.mode=16201;case 16201:if(i.extra){for(M=i.extra;h>>=i.extra,h-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=16202;case 16202:for(;w=i.distcode[A&(1<>>24,m=w>>>16&255,_=65535&w,!(g<=h);){if(0===a)break e;a--,A+=s[o++]<>v)],g=w>>>24,m=w>>>16&255,_=65535&w,!(v+g<=h);){if(0===a)break e;a--,A+=s[o++]<>>=v,h-=v,i.back+=v}if(A>>>=g,h-=g,i.back+=g,64&m){e.msg="invalid distance code",i.mode=Rt;break}i.offset=_,i.extra=15&m,i.mode=16203;case 16203:if(i.extra){for(M=i.extra;h>>=i.extra,h-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=Rt;break}i.mode=16204;case 16204:if(0===l)break e;if(d=u-l,i.offset>d){if(d=i.offset-d,d>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=Rt;break}d>i.wnext?(d-=i.wnext,p=i.wsize-d):p=i.wnext-d,d>i.length&&(d=i.length),f=i.window}else f=r,p=n-i.offset,d=i.length;d>l&&(d=l),l-=d,i.length-=d;do{r[n++]=f[p++]}while(--d);0===i.length&&(i.mode=St);break;case 16205:if(0===l)break e;r[n++]=i.length,l--,i.mode=St;break;case Tt:if(i.wrap){for(;h<32;){if(0===a)break e;a--,A|=s[o++]<{if(kt(e))return yt;let t=e.state;return t.window&&(t.window=null),e.state=null,_t},Zt=(e,t)=>{if(kt(e))return yt;const i=e.state;return 0==(2&i.wrap)?yt:(i.head=t,t.done=!1,_t)},qt=(e,t)=>{const i=t.length;let s,r,o;return kt(e)?yt:(s=e.state,0!==s.wrap&&s.mode!==Mt?yt:s.mode===Mt&&(r=1,r=R(r,t,i,0),r!==s.check)?xt:(o=Wt(e,t,i,i),o?(s.mode=16210,Bt):(s.havedict=1,_t)))},$t=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};const ei=Object.prototype.toString,{Z_NO_FLUSH:ti,Z_FINISH:ii,Z_OK:si,Z_STREAM_END:ri,Z_NEED_DICT:oi,Z_STREAM_ERROR:ni,Z_DATA_ERROR:ai,Z_MEM_ERROR:li}=O;function Ai(e){this.options=Ve({chunkSize:65536,windowBits:15,to:""},e||{});const 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 Xe,this.strm.avail_out=0;let i=Xt(this.strm,t.windowBits);if(i!==si)throw new Error(k[i]);if(this.header=new $t,Zt(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=ze(t.dictionary):"[object ArrayBuffer]"===ei.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=qt(this.strm,t.dictionary),i!==si)))throw new Error(k[i])}function hi(e,t){const i=new Ai(t);if(i.push(e),i.err)throw i.msg||k[i.err];return i.result}Ai.prototype.push=function(e,t){const i=this.strm,s=this.options.chunkSize,r=this.options.dictionary;let o,n,a;if(this.ended)return!1;for(n=t===~~t?t:!0===t?ii:ti,"[object ArrayBuffer]"===ei.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(s),i.next_out=0,i.avail_out=s),o=Jt(i,n),o===oi&&r&&(o=qt(i,r),o===si?o=Jt(i,n):o===ai&&(o=oi));i.avail_in>0&&o===ri&&i.state.wrap>0&&0!==e[i.next_in];)Kt(i),o=Jt(i,n);switch(o){case ni:case ai:case oi:case li:return this.onEnd(o),this.ended=!0,!1}if(a=i.avail_out,i.next_out&&(0===i.avail_out||o===ri))if("string"===this.options.to){let e=Ke(i.output,i.next_out),t=i.next_out-e,r=We(i.output,e);i.next_out=t,i.avail_out=s-t,t&&i.output.set(i.output.subarray(e,e+t),0),this.onData(r)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(o!==si||0!==a){if(o===ri)return o=Yt(this.strm),this.onEnd(o),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},Ai.prototype.onData=function(e){this.chunks.push(e)},Ai.prototype.onEnd=function(e){e===si&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=He(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var ci={Inflate:Ai,inflate:hi,inflateRaw:function(e,t){return(t=t||{}).raw=!0,hi(e,t)},ungzip:hi,constants:O};const{Deflate:ui,deflate:di,deflateRaw:pi,gzip:fi}=at,{Inflate:gi,inflate:mi,inflateRaw:_i,ungzip:vi}=ci;var bi=ui,yi=di,xi=pi,Bi=fi,wi=gi,Pi=mi,Ci=_i,Mi=vi,Ei=O,Fi={Deflate:bi,deflate:yi,deflateRaw:xi,gzip:Bi,Inflate:wi,inflate:Pi,inflateRaw:Ci,ungzip:Mi,constants:Ei};e.Deflate=bi,e.Inflate=wi,e.constants=Ei,e.default=Fi,e.deflate=yi,e.deflateRaw=xi,e.gzip=Bi,e.inflate=Pi,e.inflateRaw=Ci,e.ungzip=Mi,Object.defineProperty(e,"__esModule",{value:!0})}));var kw=Object.freeze({__proto__:null});let Ow=window.pako||kw;Ow.inflate||(Ow=Ow.default);const Nw=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}}();const Qw={version:1,parse:function(e,t,i,s,r,o){const n=function(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]}}(i),a=function(e){return{positions:new Uint16Array(Ow.inflate(e.positions).buffer),normals:new Int8Array(Ow.inflate(e.normals).buffer),indices:new Uint32Array(Ow.inflate(e.indices).buffer),edgeIndices:new Uint32Array(Ow.inflate(e.edgeIndices).buffer),meshPositions:new Uint32Array(Ow.inflate(e.meshPositions).buffer),meshIndices:new Uint32Array(Ow.inflate(e.meshIndices).buffer),meshEdgesIndices:new Uint32Array(Ow.inflate(e.meshEdgesIndices).buffer),meshColors:new Uint8Array(Ow.inflate(e.meshColors).buffer),entityIDs:Ow.inflate(e.entityIDs,{to:"string"}),entityMeshes:new Uint32Array(Ow.inflate(e.entityMeshes).buffer),entityIsObjects:new Uint8Array(Ow.inflate(e.entityIsObjects).buffer),positionsDecodeMatrix:new Float32Array(Ow.inflate(e.positionsDecodeMatrix).buffer)}}(n);!function(e,t,i,s,r,o){o.getNextId(),s.positionsCompression="precompressed",s.normalsCompression="precompressed";const n=i.positions,a=i.normals,l=i.indices,A=i.edgeIndices,h=i.meshPositions,u=i.meshIndices,d=i.meshEdgesIndices,p=i.meshColors,f=JSON.parse(i.entityIDs),g=i.entityMeshes,m=i.entityIsObjects,v=h.length,b=g.length;for(let r=0;rg[e]g[t]?1:0));for(let e=0;e1||(E[i]=e)}}for(let e=0;e1,o=Xw(m.subarray(4*t,4*t+3)),u=m[4*t+3]/255,v=a.subarray(d[t],i?a.length:d[t+1]),y=l.subarray(d[t],i?l.length:d[t+1]),x=A.subarray(p[t],i?A.length:p[t+1]),w=h.subarray(f[t],i?h.length:f[t+1]),M=c.subarray(g[t],g[t]+16);if(r){const e=`${n}-geometry.${t}`;s.createGeometry({id:e,primitive:"triangles",positionsCompressed:v,normalsCompressed:y,indices:x,edgeIndices:w,positionsDecodeMatrix:M})}else{const e=`${n}-${t}`;b[E[t]];const i={};s.createMesh(_.apply(i,{id:e,primitive:"triangles",positionsCompressed:v,normalsCompressed:y,indices:x,edgeIndices:w,positionsDecodeMatrix:M,color:o,opacity:u}))}}let F=0;for(let e=0;e1){const t={},r=`${n}-instance.${F++}`,o=`${n}-geometry.${i}`,a=16*x[e],A=u.subarray(a,a+16);s.createMesh(_.apply(t,{id:r,geometryId:o,matrix:A})),l.push(r)}else l.push(i)}if(l.length>0){const e={};s.createEntity(_.apply(e,{id:r,isObject:!0,meshIds:l}))}}}(0,0,a,s,0,o)}};let Yw=window.pako||kw;Yw.inflate||(Yw=Yw.default);const Zw=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}}();const qw={version:5,parse:function(e,t,i,s,r,o){const n=function(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]}}(i),a=function(e){return{positions:new Float32Array(Yw.inflate(e.positions).buffer),normals:new Int8Array(Yw.inflate(e.normals).buffer),indices:new Uint32Array(Yw.inflate(e.indices).buffer),edgeIndices:new Uint32Array(Yw.inflate(e.edgeIndices).buffer),matrices:new Float32Array(Yw.inflate(e.matrices).buffer),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(Yw.inflate(e.eachPrimitivePositionsAndNormalsPortion).buffer),eachPrimitiveIndicesPortion:new Uint32Array(Yw.inflate(e.eachPrimitiveIndicesPortion).buffer),eachPrimitiveEdgeIndicesPortion:new Uint32Array(Yw.inflate(e.eachPrimitiveEdgeIndicesPortion).buffer),eachPrimitiveColor:new Uint8Array(Yw.inflate(e.eachPrimitiveColor).buffer),primitiveInstances:new Uint32Array(Yw.inflate(e.primitiveInstances).buffer),eachEntityId:Yw.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(Yw.inflate(e.eachEntityPrimitiveInstancesPortion).buffer),eachEntityMatricesPortion:new Uint32Array(Yw.inflate(e.eachEntityMatricesPortion).buffer)}}(n);!function(e,t,i,s,r,o){const n=o.getNextId();s.positionsCompression="disabled",s.normalsCompression="precompressed";const a=i.positions,l=i.normals,A=i.indices,h=i.edgeIndices,c=i.matrices,u=i.eachPrimitivePositionsAndNormalsPortion,d=i.eachPrimitiveIndicesPortion,p=i.eachPrimitiveEdgeIndicesPortion,f=i.eachPrimitiveColor,g=i.primitiveInstances,m=JSON.parse(i.eachEntityId),v=i.eachEntityPrimitiveInstancesPortion,b=i.eachEntityMatricesPortion,y=u.length,x=g.length,B=new Uint8Array(y),w=m.length;for(let e=0;e1||(P[i]=e)}}for(let e=0;e1,r=Zw(f.subarray(4*e,4*e+3)),o=f[4*e+3]/255,c=a.subarray(u[e],t?a.length:u[e+1]),g=l.subarray(u[e],t?l.length:u[e+1]),v=A.subarray(d[e],t?A.length:d[e+1]),b=h.subarray(p[e],t?h.length:p[e+1]);if(i){const t=`${n}-geometry.${e}`;s.createGeometry({id:t,primitive:"triangles",positionsCompressed:c,normalsCompressed:g,indices:v,edgeIndices:b})}else{const t=e;m[P[e]];const i={};s.createMesh(_.apply(i,{id:t,primitive:"triangles",positionsCompressed:c,normalsCompressed:g,indices:v,edgeIndices:b,color:r,opacity:o}))}}let C=0;for(let e=0;e1){const t={},r="instance."+C++,o="geometry"+i,n=16*b[e],l=c.subarray(n,n+16);s.createMesh(_.apply(t,{id:r,geometryId:o,matrix:l})),a.push(r)}else a.push(i)}if(a.length>0){const e={};s.createEntity(_.apply(e,{id:r,isObject:!0,meshIds:a}))}}}(0,0,a,s,0,o)}};let $w=window.pako||kw;$w.inflate||($w=$w.default);const eP=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}}();const tP={version:6,parse:function(e,t,i,s,r,o){const n=function(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],matrices:e[4],reusedPrimitivesDecodeMatrix:e[5],eachPrimitivePositionsAndNormalsPortion:e[6],eachPrimitiveIndicesPortion:e[7],eachPrimitiveEdgeIndicesPortion:e[8],eachPrimitiveColorAndOpacity:e[9],primitiveInstances:e[10],eachEntityId:e[11],eachEntityPrimitiveInstancesPortion:e[12],eachEntityMatricesPortion:e[13],eachTileAABB:e[14],eachTileEntitiesPortion:e[15]}}(i),a=function(e){function t(e,t){return 0===e.length?[]:$w.inflate(e,t).buffer}return{positions:new Uint16Array(t(e.positions)),normals:new Int8Array(t(e.normals)),indices:new Uint32Array(t(e.indices)),edgeIndices:new Uint32Array(t(e.edgeIndices)),matrices:new Float32Array(t(e.matrices)),reusedPrimitivesDecodeMatrix:new Float32Array(t(e.reusedPrimitivesDecodeMatrix)),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(t(e.eachPrimitivePositionsAndNormalsPortion)),eachPrimitiveIndicesPortion:new Uint32Array(t(e.eachPrimitiveIndicesPortion)),eachPrimitiveEdgeIndicesPortion:new Uint32Array(t(e.eachPrimitiveEdgeIndicesPortion)),eachPrimitiveColorAndOpacity:new Uint8Array(t(e.eachPrimitiveColorAndOpacity)),primitiveInstances:new Uint32Array(t(e.primitiveInstances)),eachEntityId:$w.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(t(e.eachEntityPrimitiveInstancesPortion)),eachEntityMatricesPortion:new Uint32Array(t(e.eachEntityMatricesPortion)),eachTileAABB:new Float64Array(t(e.eachTileAABB)),eachTileEntitiesPortion:new Uint32Array(t(e.eachTileEntitiesPortion))}}(n);!function(e,t,i,s,r,o){const n=o.getNextId(),a=i.positions,l=i.normals,A=i.indices,h=i.edgeIndices,u=i.matrices,d=i.reusedPrimitivesDecodeMatrix,p=i.eachPrimitivePositionsAndNormalsPortion,f=i.eachPrimitiveIndicesPortion,g=i.eachPrimitiveEdgeIndicesPortion,m=i.eachPrimitiveColorAndOpacity,v=i.primitiveInstances,b=JSON.parse(i.eachEntityId),y=i.eachEntityPrimitiveInstancesPortion,x=i.eachEntityMatricesPortion,B=i.eachTileAABB,w=i.eachTileEntitiesPortion,P=p.length,C=v.length,M=b.length,E=w.length,F=new Uint32Array(P);for(let e=0;e1,c=t===P-1,u=a.subarray(p[t],c?a.length:p[t+1]),b=l.subarray(p[t],c?l.length:p[t+1]),y=A.subarray(f[t],c?A.length:f[t+1]),x=h.subarray(g[t],c?h.length:g[t+1]),B=eP(m.subarray(4*t,4*t+3)),w=m[4*t+3]/255,C=o.getNextId();if(r){const e=`${n}-geometry.${i}.${t}`;U[e]||(s.createGeometry({id:e,primitive:"triangles",positionsCompressed:u,indices:y,edgeIndices:x,positionsDecodeMatrix:d}),U[e]=!0),s.createMesh(_.apply(N,{id:C,geometryId:e,origin:I,matrix:E,color:B,opacity:w})),R.push(C)}else s.createMesh(_.apply(N,{id:C,origin:I,primitive:"triangles",positionsCompressed:u,normalsCompressed:b,indices:y,edgeIndices:x,positionsDecodeMatrix:L,color:B,opacity:w})),R.push(C)}R.length>0&&s.createEntity(_.apply(O,{id:w,isObject:!0,meshIds:R}))}}}(e,t,a,s,0,o)}};let iP=window.pako||kw;iP.inflate||(iP=iP.default);const sP=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 rP(e){const t=[];for(let i=0,s=e.length;i1,c=t===F-1,P=sP(w.subarray(6*e,6*e+3)),C=w[6*e+3]/255,M=w[6*e+4]/255,E=w[6*e+5]/255,I=o.getNextId();if(r){const r=B[e],o=d.slice(r,r+16),x=`${n}-geometry.${i}.${t}`;if(!Q[x]){let e,i,r,o,n,d;switch(f[t]){case 0:e="solid",i=a.subarray(g[t],c?a.length:g[t+1]),r=l.subarray(m[t],c?l.length:m[t+1]),n=h.subarray(b[t],c?h.length:b[t+1]),d=u.subarray(y[t],c?u.length:y[t+1]);break;case 1:e="surface",i=a.subarray(g[t],c?a.length:g[t+1]),r=l.subarray(m[t],c?l.length:m[t+1]),n=h.subarray(b[t],c?h.length:b[t+1]),d=u.subarray(y[t],c?u.length:y[t+1]);break;case 2:e="points",i=a.subarray(g[t],c?a.length:g[t+1]),o=rP(A.subarray(v[t],c?A.length:v[t+1]));break;case 3:e="lines",i=a.subarray(g[t],c?a.length:g[t+1]),n=h.subarray(b[t],c?h.length:b[t+1]);break;default:continue}s.createGeometry({id:x,primitive:e,positionsCompressed:i,normalsCompressed:r,colors:o,indices:n,edgeIndices:d,positionsDecodeMatrix:p}),Q[x]=!0}s.createMesh(_.apply(V,{id:I,geometryId:x,origin:R,matrix:o,color:P,metallic:M,roughness:E,opacity:C})),U.push(I)}else{let e,i,r,o,n,d;switch(f[t]){case 0:e="solid",i=a.subarray(g[t],c?a.length:g[t+1]),r=l.subarray(m[t],c?l.length:m[t+1]),n=h.subarray(b[t],c?h.length:b[t+1]),d=u.subarray(y[t],c?u.length:y[t+1]);break;case 1:e="surface",i=a.subarray(g[t],c?a.length:g[t+1]),r=l.subarray(m[t],c?l.length:m[t+1]),n=h.subarray(b[t],c?h.length:b[t+1]),d=u.subarray(y[t],c?u.length:y[t+1]);break;case 2:e="points",i=a.subarray(g[t],c?a.length:g[t+1]),o=rP(A.subarray(v[t],c?A.length:v[t+1]));break;case 3:e="lines",i=a.subarray(g[t],c?a.length:g[t+1]),n=h.subarray(b[t],c?h.length:b[t+1]);break;default:continue}s.createMesh(_.apply(V,{id:I,origin:R,primitive:e,positionsCompressed:i,normalsCompressed:r,colors:o,indices:n,edgeIndices:d,positionsDecodeMatrix:N,color:P,metallic:M,roughness:E,opacity:C})),U.push(I)}}U.length>0&&s.createEntity(_.apply(O,{id:E,isObject:!0,meshIds:U}))}}}(e,t,a,s,0,o)}};let nP=window.pako||kw;nP.inflate||(nP=nP.default);const aP=c.vec4(),lP=c.vec4();const AP=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 hP(e){const t=[];for(let i=0,s=e.length;i1,l=r===L-1,A=AP(F.subarray(6*e,6*e+3)),h=F[6*e+3]/255,u=F[6*e+4]/255,I=F[6*e+5]/255,D=o.getNextId();if(a){const o=E[e],a=v.slice(o,o+16),M=`${n}-geometry.${i}.${r}`;let F=H[M];if(!F){F={batchThisMesh:!t.reuseGeometries};let e=!1;switch(y[r]){case 0:F.primitiveName="solid",F.geometryPositions=d.subarray(x[r],l?d.length:x[r+1]),F.geometryNormals=p.subarray(B[r],l?p.length:B[r+1]),F.geometryIndices=g.subarray(P[r],l?g.length:P[r+1]),F.geometryEdgeIndices=m.subarray(C[r],l?m.length:C[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 1:F.primitiveName="surface",F.geometryPositions=d.subarray(x[r],l?d.length:x[r+1]),F.geometryNormals=p.subarray(B[r],l?p.length:B[r+1]),F.geometryIndices=g.subarray(P[r],l?g.length:P[r+1]),F.geometryEdgeIndices=m.subarray(C[r],l?m.length:C[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 2:F.primitiveName="points",F.geometryPositions=d.subarray(x[r],l?d.length:x[r+1]),F.geometryColors=hP(f.subarray(w[r],l?f.length:w[r+1])),e=F.geometryPositions.length>0;break;case 3:F.primitiveName="lines",F.geometryPositions=d.subarray(x[r],l?d.length:x[r+1]),F.geometryIndices=g.subarray(P[r],l?g.length:P[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;default:continue}if(e||(F=null),F&&(F.geometryPositions.length,F.batchThisMesh)){F.decompressedPositions=new Float32Array(F.geometryPositions.length);const e=F.geometryPositions,t=F.decompressedPositions;for(let i=0,s=e.length;i0&&n.length>0;break;case 1:e="surface",t=d.subarray(x[r],l?d.length:x[r+1]),i=p.subarray(B[r],l?p.length:B[r+1]),n=g.subarray(P[r],l?g.length:P[r+1]),a=m.subarray(C[r],l?m.length:C[r+1]),c=t.length>0&&n.length>0;break;case 2:e="points",t=d.subarray(x[r],l?d.length:x[r+1]),o=hP(f.subarray(w[r],l?f.length:w[r+1])),c=t.length>0;break;case 3:e="lines",t=d.subarray(x[r],l?d.length:x[r+1]),n=g.subarray(P[r],l?g.length:P[r+1]),c=t.length>0&&n.length>0;break;default:continue}c&&(s.createMesh(_.apply(G,{id:D,origin:Q,primitive:e,positionsCompressed:t,normalsCompressed:i,colorsCompressed:o,indices:n,edgeIndices:a,positionsDecodeMatrix:R,color:A,metallic:u,roughness:I,opacity:h})),T.push(D))}}T.length>0&&s.createEntity(_.apply(j,{id:A,isObject:!0,meshIds:T}))}}}(e,t,a,s,r,o)}};let uP=window.pako||kw;uP.inflate||(uP=uP.default);const dP=c.vec4(),pP=c.vec4();const fP=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}}();const gP={version:9,parse:function(e,t,i,s,r,o){const n=function(e){return{metadata:e[0],positions:e[1],normals:e[2],colors:e[3],indices:e[4],edgeIndices:e[5],matrices:e[6],reusedGeometriesDecodeMatrix:e[7],eachGeometryPrimitiveType:e[8],eachGeometryPositionsPortion:e[9],eachGeometryNormalsPortion:e[10],eachGeometryColorsPortion:e[11],eachGeometryIndicesPortion:e[12],eachGeometryEdgeIndicesPortion:e[13],eachMeshGeometriesPortion:e[14],eachMeshMatricesPortion:e[15],eachMeshMaterial:e[16],eachEntityId:e[17],eachEntityMeshesPortion:e[18],eachTileAABB:e[19],eachTileEntitiesPortion:e[20]}}(i),a=function(e){function t(e,t){return 0===e.length?[]:uP.inflate(e,t).buffer}return{metadata:JSON.parse(uP.inflate(e.metadata,{to:"string"})),positions:new Uint16Array(t(e.positions)),normals:new Int8Array(t(e.normals)),colors:new Uint8Array(t(e.colors)),indices:new Uint32Array(t(e.indices)),edgeIndices:new Uint32Array(t(e.edgeIndices)),matrices:new Float32Array(t(e.matrices)),reusedGeometriesDecodeMatrix:new Float32Array(t(e.reusedGeometriesDecodeMatrix)),eachGeometryPrimitiveType:new Uint8Array(t(e.eachGeometryPrimitiveType)),eachGeometryPositionsPortion:new Uint32Array(t(e.eachGeometryPositionsPortion)),eachGeometryNormalsPortion:new Uint32Array(t(e.eachGeometryNormalsPortion)),eachGeometryColorsPortion:new Uint32Array(t(e.eachGeometryColorsPortion)),eachGeometryIndicesPortion:new Uint32Array(t(e.eachGeometryIndicesPortion)),eachGeometryEdgeIndicesPortion:new Uint32Array(t(e.eachGeometryEdgeIndicesPortion)),eachMeshGeometriesPortion:new Uint32Array(t(e.eachMeshGeometriesPortion)),eachMeshMatricesPortion:new Uint32Array(t(e.eachMeshMatricesPortion)),eachMeshMaterial:new Uint8Array(t(e.eachMeshMaterial)),eachEntityId:JSON.parse(uP.inflate(e.eachEntityId,{to:"string"})),eachEntityMeshesPortion:new Uint32Array(t(e.eachEntityMeshesPortion)),eachTileAABB:new Float64Array(t(e.eachTileAABB)),eachTileEntitiesPortion:new Uint32Array(t(e.eachTileEntitiesPortion))}}(n);!function(e,t,i,s,r,o){const n=o.getNextId(),a=i.metadata,l=i.positions,A=i.normals,h=i.colors,u=i.indices,d=i.edgeIndices,p=i.matrices,f=i.reusedGeometriesDecodeMatrix,g=i.eachGeometryPrimitiveType,m=i.eachGeometryPositionsPortion,v=i.eachGeometryNormalsPortion,b=i.eachGeometryColorsPortion,y=i.eachGeometryIndicesPortion,x=i.eachGeometryEdgeIndicesPortion,B=i.eachMeshGeometriesPortion,w=i.eachMeshMatricesPortion,P=i.eachMeshMaterial,C=i.eachEntityId,M=i.eachEntityMeshesPortion,E=i.eachTileAABB,F=i.eachTileEntitiesPortion,I=m.length,D=B.length,S=M.length,T=F.length;r&&r.loadData(a,{includeTypes:t.includeTypes,excludeTypes:t.excludeTypes,globalizeObjectIds:t.globalizeObjectIds});const R=new Uint32Array(I);for(let e=0;e1,C=r===I-1,M=fP(P.subarray(6*e,6*e+3)),E=P[6*e+3]/255,F=P[6*e+4]/255,D=P[6*e+5]/255,S=o.getNextId();if(a){const o=w[e],a=p.slice(o,o+16),B=`${n}-geometry.${i}.${r}`;let P=k[B];if(!P){P={batchThisMesh:!t.reuseGeometries};let e=!1;switch(g[r]){case 0:P.primitiveName="solid",P.geometryPositions=l.subarray(m[r],C?l.length:m[r+1]),P.geometryNormals=A.subarray(v[r],C?A.length:v[r+1]),P.geometryIndices=u.subarray(y[r],C?u.length:y[r+1]),P.geometryEdgeIndices=d.subarray(x[r],C?d.length:x[r+1]),e=P.geometryPositions.length>0&&P.geometryIndices.length>0;break;case 1:P.primitiveName="surface",P.geometryPositions=l.subarray(m[r],C?l.length:m[r+1]),P.geometryNormals=A.subarray(v[r],C?A.length:v[r+1]),P.geometryIndices=u.subarray(y[r],C?u.length:y[r+1]),P.geometryEdgeIndices=d.subarray(x[r],C?d.length:x[r+1]),e=P.geometryPositions.length>0&&P.geometryIndices.length>0;break;case 2:P.primitiveName="points",P.geometryPositions=l.subarray(m[r],C?l.length:m[r+1]),P.geometryColors=h.subarray(b[r],C?h.length:b[r+1]),e=P.geometryPositions.length>0;break;case 3:P.primitiveName="lines",P.geometryPositions=l.subarray(m[r],C?l.length:m[r+1]),P.geometryIndices=u.subarray(y[r],C?u.length:y[r+1]),e=P.geometryPositions.length>0&&P.geometryIndices.length>0;break;default:continue}if(e||(P=null),P&&(P.geometryPositions.length,P.batchThisMesh)){P.decompressedPositions=new Float32Array(P.geometryPositions.length),P.transformedAndRecompressedPositions=new Uint16Array(P.geometryPositions.length);const e=P.geometryPositions,t=P.decompressedPositions;for(let i=0,s=e.length;i0&&n.length>0;break;case 1:e="surface",t=l.subarray(m[r],C?l.length:m[r+1]),i=A.subarray(v[r],C?A.length:v[r+1]),n=u.subarray(y[r],C?u.length:y[r+1]),a=d.subarray(x[r],C?d.length:x[r+1]),c=t.length>0&&n.length>0;break;case 2:e="points",t=l.subarray(m[r],C?l.length:m[r+1]),o=h.subarray(b[r],C?h.length:b[r+1]),c=t.length>0;break;case 3:e="lines",t=l.subarray(m[r],C?l.length:m[r+1]),n=u.subarray(y[r],C?u.length:y[r+1]),c=t.length>0&&n.length>0;break;default:continue}c&&(s.createMesh(_.apply(j,{id:S,origin:L,primitive:e,positionsCompressed:t,normalsCompressed:i,colorsCompressed:o,indices:n,edgeIndices:a,positionsDecodeMatrix:Q,color:M,metallic:F,roughness:D,opacity:E})),O.push(S))}}O.length>0&&s.createEntity(_.apply(H,{id:E,isObject:!0,meshIds:O}))}}}(e,t,a,s,r,o)}};let mP=window.pako||kw;mP.inflate||(mP=mP.default);const _P=c.vec4(),vP=c.vec4();const bP=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 yP(e,t){const i=[];if(t.length>1)for(let e=0,s=t.length-1;e1)for(let t=0,s=e.length/3-1;t0,a=9*e,c=1===h[a+0],u=h[a+1];h[a+2],h[a+3];const d=h[a+4],p=h[a+5],f=h[a+6],g=h[a+7],m=h[a+8];if(o){const t=new Uint8Array(l.subarray(i,r)).buffer,o=`${n}-texture-${e}`;if(c)s.createTexture({id:o,buffers:[t],minFilter:d,magFilter:p,wrapS:f,wrapT:g,wrapR:m});else{const e=new Blob([t],{type:10001===u?"image/jpeg":10002===u?"image/png":"image/gif"}),i=(window.URL||window.webkitURL).createObjectURL(e),r=document.createElement("img");r.src=i,s.createTexture({id:o,image:r,minFilter:d,magFilter:p,wrapS:f,wrapT:g,wrapR:m})}}}for(let e=0;e=0?`${n}-texture-${r}`:null,normalsTextureId:a>=0?`${n}-texture-${a}`:null,metallicRoughnessTextureId:o>=0?`${n}-texture-${o}`:null,emissiveTextureId:l>=0?`${n}-texture-${l}`:null,occlusionTextureId:A>=0?`${n}-texture-${A}`:null})}const j=new Uint32Array(N);for(let e=0;e1,l=r===N-1,A=D[e],h=A>=0?`${n}-textureSet-${A}`:null,T=bP(S.subarray(6*e,6*e+3)),R=S[6*e+3]/255,L=S[6*e+4]/255,O=S[6*e+5]/255,Q=o.getNextId();if(a){const o=I[e],a=b.slice(o,o+16),A=`${n}-geometry.${i}.${r}`;let F=W[A];if(!F){F={batchThisMesh:!t.reuseGeometries};let e=!1;switch(x[r]){case 0:F.primitiveName="solid",F.geometryPositions=u.subarray(B[r],l?u.length:B[r+1]),F.geometryNormals=d.subarray(w[r],l?d.length:w[r+1]),F.geometryUVs=f.subarray(C[r],l?f.length:C[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),F.geometryEdgeIndices=m.subarray(E[r],l?m.length:E[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 1:F.primitiveName="surface",F.geometryPositions=u.subarray(B[r],l?u.length:B[r+1]),F.geometryNormals=d.subarray(w[r],l?d.length:w[r+1]),F.geometryUVs=f.subarray(C[r],l?f.length:C[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),F.geometryEdgeIndices=m.subarray(E[r],l?m.length:E[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 2:F.primitiveName="points",F.geometryPositions=u.subarray(B[r],l?u.length:B[r+1]),F.geometryColors=p.subarray(P[r],l?p.length:P[r+1]),e=F.geometryPositions.length>0;break;case 3:F.primitiveName="lines",F.geometryPositions=u.subarray(B[r],l?u.length:B[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 4:F.primitiveName="lines",F.geometryPositions=u.subarray(B[r],l?u.length:B[r+1]),F.geometryIndices=yP(F.geometryPositions,g.subarray(M[r],l?g.length:M[r+1])),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;default:continue}if(e||(F=null),F&&(F.geometryPositions.length,F.batchThisMesh)){F.decompressedPositions=new Float32Array(F.geometryPositions.length),F.transformedAndRecompressedPositions=new Uint16Array(F.geometryPositions.length);const e=F.geometryPositions,t=F.decompressedPositions;for(let i=0,s=e.length;i0&&a.length>0;break;case 1:e="surface",t=u.subarray(B[r],l?u.length:B[r+1]),i=d.subarray(w[r],l?d.length:w[r+1]),o=f.subarray(C[r],l?f.length:C[r+1]),a=g.subarray(M[r],l?g.length:M[r+1]),A=m.subarray(E[r],l?m.length:E[r+1]),c=t.length>0&&a.length>0;break;case 2:e="points",t=u.subarray(B[r],l?u.length:B[r+1]),n=p.subarray(P[r],l?p.length:P[r+1]),c=t.length>0;break;case 3:e="lines",t=u.subarray(B[r],l?u.length:B[r+1]),a=g.subarray(M[r],l?g.length:M[r+1]),c=t.length>0&&a.length>0;break;case 4:e="lines",t=u.subarray(B[r],l?u.length:B[r+1]),a=yP(t,g.subarray(M[r],l?g.length:M[r+1])),c=t.length>0&&a.length>0;break;default:continue}c&&(s.createMesh(_.apply(H,{id:Q,textureSetId:h,origin:G,primitive:e,positionsCompressed:t,normalsCompressed:i,uv:o&&o.length>0?o:null,colorsCompressed:n,indices:a,edgeIndices:A,positionsDecodeMatrix:v,color:T,metallic:L,roughness:O,opacity:R})),U.push(Q))}}U.length>0&&s.createEntity(_.apply(Q,{id:l,isObject:!0,meshIds:U}))}}}(e,t,a,s,r,o)}},BP=c.vec4(),wP=c.vec4();const PP=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 CP(e,t){const i=[];if(t.length>1)for(let e=0,s=t.length-1;e1)for(let t=0,s=e.length/3-1;t1){const t=new Uint8Array(e,n,a),i=l/2,s=t.length/l;for(let e=0;eJSON.parse(e.decode(i(Uint8Array)))}();return{metadata:s(),textureData:i(Uint8Array),eachTextureDataPortion:i(Uint32Array),eachTextureAttributes:i(Uint16Array),positions:i(Uint16Array),normals:i(Int8Array),colors:i(Uint8Array),uvs:i(Float32Array),indices:i(Uint32Array),edgeIndices:i(Uint32Array),eachTextureSetTextures:i(Int32Array),matrices:i(Float32Array),reusedGeometriesDecodeMatrix:i(Float32Array),eachGeometryPrimitiveType:i(Uint8Array),eachGeometryPositionsPortion:i(Uint32Array),eachGeometryNormalsPortion:i(Uint32Array),eachGeometryColorsPortion:i(Uint32Array),eachGeometryUVsPortion:i(Uint32Array),eachGeometryIndicesPortion:i(Uint32Array),eachGeometryEdgeIndicesPortion:i(Uint32Array),eachMeshGeometriesPortion:i(Uint32Array),eachMeshMatricesPortion:i(Uint32Array),eachMeshTextureSet:i(Int32Array),eachMeshMaterialAttributes:i(Uint8Array),eachEntityId:s(),eachEntityMeshesPortion:i(Uint32Array),eachTileAABB:i(Float64Array),eachTileEntitiesPortion:i(Uint32Array)}}(i);!function(e,t,i,s,r,o){const n=o.getNextId(),a=i.metadata,l=i.textureData,A=i.eachTextureDataPortion,h=i.eachTextureAttributes,u=i.positions,d=i.normals,p=i.colors,f=i.uvs,g=i.indices,m=i.edgeIndices,v=i.eachTextureSetTextures,b=i.matrices,y=i.reusedGeometriesDecodeMatrix,x=i.eachGeometryPrimitiveType,B=i.eachGeometryPositionsPortion,w=i.eachGeometryNormalsPortion,P=i.eachGeometryColorsPortion,C=i.eachGeometryUVsPortion,M=i.eachGeometryIndicesPortion,E=i.eachGeometryEdgeIndicesPortion,F=i.eachMeshGeometriesPortion,I=i.eachMeshMatricesPortion,D=i.eachMeshTextureSet,S=i.eachMeshMaterialAttributes,T=i.eachEntityId,R=i.eachEntityMeshesPortion,L=i.eachTileAABB,U=i.eachTileEntitiesPortion,k=A.length,O=v.length/5,N=B.length,Q=F.length,V=R.length,H=U.length;r&&r.loadData(a,{includeTypes:t.includeTypes,excludeTypes:t.excludeTypes,globalizeObjectIds:t.globalizeObjectIds});for(let e=0;e0,a=9*e,c=1===h[a+0],u=h[a+1];h[a+2],h[a+3];const d=h[a+4],p=h[a+5],f=h[a+6],g=h[a+7],m=h[a+8];if(o){const t=new Uint8Array(l.subarray(i,r)).buffer,o=`${n}-texture-${e}`;if(c)s.createTexture({id:o,buffers:[t],minFilter:d,magFilter:p,wrapS:f,wrapT:g,wrapR:m});else{const e=new Blob([t],{type:10001===u?"image/jpeg":10002===u?"image/png":"image/gif"}),i=(window.URL||window.webkitURL).createObjectURL(e),r=document.createElement("img");r.src=i,s.createTexture({id:o,image:r,minFilter:d,magFilter:p,wrapS:f,wrapT:g,wrapR:m})}}}for(let e=0;e=0?`${n}-texture-${r}`:null,normalsTextureId:a>=0?`${n}-texture-${a}`:null,metallicRoughnessTextureId:o>=0?`${n}-texture-${o}`:null,emissiveTextureId:l>=0?`${n}-texture-${l}`:null,occlusionTextureId:A>=0?`${n}-texture-${A}`:null})}const j=new Uint32Array(N);for(let e=0;e1,l=r===N-1,A=D[e],h=A>=0?`${n}-textureSet-${A}`:null,T=PP(S.subarray(6*e,6*e+3)),R=S[6*e+3]/255,L=S[6*e+4]/255,O=S[6*e+5]/255,Q=o.getNextId();if(a){const o=I[e],a=b.slice(o,o+16),A=`${n}-geometry.${i}.${r}`;let F=W[A];if(!F){F={batchThisMesh:!t.reuseGeometries};let e=!1;switch(x[r]){case 0:F.primitiveName="solid",F.geometryPositions=u.subarray(B[r],l?u.length:B[r+1]),F.geometryNormals=d.subarray(w[r],l?d.length:w[r+1]),F.geometryUVs=f.subarray(C[r],l?f.length:C[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),F.geometryEdgeIndices=m.subarray(E[r],l?m.length:E[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 1:F.primitiveName="surface",F.geometryPositions=u.subarray(B[r],l?u.length:B[r+1]),F.geometryNormals=d.subarray(w[r],l?d.length:w[r+1]),F.geometryUVs=f.subarray(C[r],l?f.length:C[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),F.geometryEdgeIndices=m.subarray(E[r],l?m.length:E[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 2:F.primitiveName="points",F.geometryPositions=u.subarray(B[r],l?u.length:B[r+1]),F.geometryColors=p.subarray(P[r],l?p.length:P[r+1]),e=F.geometryPositions.length>0;break;case 3:F.primitiveName="lines",F.geometryPositions=u.subarray(B[r],l?u.length:B[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 4:F.primitiveName="lines",F.geometryPositions=u.subarray(B[r],l?u.length:B[r+1]),F.geometryIndices=CP(F.geometryPositions,g.subarray(M[r],l?g.length:M[r+1])),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;default:continue}if(e||(F=null),F&&(F.geometryPositions.length,F.batchThisMesh)){F.decompressedPositions=new Float32Array(F.geometryPositions.length),F.transformedAndRecompressedPositions=new Uint16Array(F.geometryPositions.length);const e=F.geometryPositions,t=F.decompressedPositions;for(let i=0,s=e.length;i0&&a.length>0;break;case 1:e="surface",t=u.subarray(B[r],l?u.length:B[r+1]),i=d.subarray(w[r],l?d.length:w[r+1]),o=f.subarray(C[r],l?f.length:C[r+1]),a=g.subarray(M[r],l?g.length:M[r+1]),A=m.subarray(E[r],l?m.length:E[r+1]),c=t.length>0&&a.length>0;break;case 2:e="points",t=u.subarray(B[r],l?u.length:B[r+1]),n=p.subarray(P[r],l?p.length:P[r+1]),c=t.length>0;break;case 3:e="lines",t=u.subarray(B[r],l?u.length:B[r+1]),a=g.subarray(M[r],l?g.length:M[r+1]),c=t.length>0&&a.length>0;break;case 4:e="lines",t=u.subarray(B[r],l?u.length:B[r+1]),a=CP(t,g.subarray(M[r],l?g.length:M[r+1])),c=t.length>0&&a.length>0;break;default:continue}c&&(s.createMesh(_.apply(H,{id:Q,textureSetId:h,origin:G,primitive:e,positionsCompressed:t,normalsCompressed:i,uv:o&&o.length>0?o:null,colorsCompressed:n,indices:a,edgeIndices:A,positionsDecodeMatrix:v,color:T,metallic:L,roughness:O,opacity:R})),U.push(Q))}}U.length>0&&s.createEntity(_.apply(Q,{id:l,isObject:!0,meshIds:U}))}}}(e,t,n,s,r,o)}},EP={};EP[Qw.version]=Qw,EP[jw.version]=jw,EP[Ww.version]=Ww,EP[Jw.version]=Jw,EP[qw.version]=qw,EP[tP.version]=tP,EP[oP.version]=oP,EP[cP.version]=cP,EP[gP.version]=gP,EP[xP.version]=xP,EP[MP.version]=MP;var FP={};!function(e){var t,i="File format is not recognized.",s="Error while reading zip file.",r="Error while reading file data.",o=524288,n="text/plain";try{t=0===new Blob([new DataView(new ArrayBuffer(0))]).size}catch(e){}function a(){this.crc=-1}function l(){}function A(e,t){var i,s;return i=new ArrayBuffer(e),s=new Uint8Array(i),t&&s.set(t,0),{buffer:i,array:s,view:new DataView(i)}}function h(){}function c(e){var t,i=this;i.size=0,i.init=function(s,r){var o=new Blob([e],{type:n});(t=new d(o)).init((function(){i.size=t.size,s()}),r)},i.readUint8Array=function(e,i,s,r){t.readUint8Array(e,i,s,r)}}function u(t){var i,s=this;s.size=0,s.init=function(e){for(var r=t.length;"="==t.charAt(r-1);)r--;i=t.indexOf(",")+1,s.size=Math.floor(.75*(r-i)),e()},s.readUint8Array=function(s,r,o){var n,a=A(r),l=4*Math.floor(s/3),h=4*Math.ceil((s+r)/3),c=e.atob(t.substring(l+i,h+i)),u=s-3*Math.floor(l/4);for(n=u;ne.size)throw new RangeError("offset:"+t+", length:"+i+", size:"+e.size);return e.slice?e.slice(t,t+i):e.webkitSlice?e.webkitSlice(t,t+i):e.mozSlice?e.mozSlice(t,t+i):e.msSlice?e.msSlice(t,t+i):void 0}(e,t,i))}catch(e){r(e)}}}function p(){}function f(e){var i,s=this;s.init=function(e){i=new Blob([],{type:n}),e()},s.writeUint8Array=function(e,s){i=new Blob([i,t?e:e.buffer],{type:n}),s()},s.getData=function(t,s){var r=new FileReader;r.onload=function(e){t(e.target.result)},r.onerror=s,r.readAsText(i,e)}}function g(t){var i=this,s="",r="";i.init=function(e){s+="data:"+(t||"")+";base64,",e()},i.writeUint8Array=function(t,i){var o,n=r.length,a=r;for(r="",o=0;o<3*Math.floor((n+t.length)/3)-n;o++)a+=String.fromCharCode(t[o]);for(;o2?s+=e.btoa(a):r=a,i()},i.getData=function(t){t(s+e.btoa(r))}}function m(e){var i,s=this;s.init=function(t){i=new Blob([],{type:e}),t()},s.writeUint8Array=function(s,r){i=new Blob([i,t?s:s.buffer],{type:e}),r()},s.getData=function(e){e(i)}}function _(e,t,i,s,r,n,a,l,A,h){var c,u,d,p=0,f=t.sn;function g(){e.removeEventListener("message",m,!1),l(u,d)}function m(t){var i=t.data,r=i.data,o=i.error;if(o)return o.toString=function(){return"Error: "+this.message},void A(o);if(i.sn===f)switch("number"==typeof i.codecTime&&(e.codecTime+=i.codecTime),"number"==typeof i.crcTime&&(e.crcTime+=i.crcTime),i.type){case"append":r?(u+=r.length,s.writeUint8Array(r,(function(){_()}),h)):_();break;case"flush":d=i.crc,r?(u+=r.length,s.writeUint8Array(r,(function(){g()}),h)):g();break;case"progress":a&&a(c+i.loaded,n);break;case"importScripts":case"newTask":case"echo":break;default:console.warn("zip.js:launchWorkerProcess: unknown message: ",i)}}function _(){(c=p*o)<=n?i.readUint8Array(r+c,Math.min(o,n-c),(function(i){a&&a(c,n);var s=0===c?t:{sn:f};s.type="append",s.data=i;try{e.postMessage(s,[i.buffer])}catch(t){e.postMessage(s)}p++}),A):e.postMessage({sn:f,type:"flush"})}u=0,e.addEventListener("message",m,!1),_()}function v(e,t,i,s,r,n,l,A,h,c){var u,d=0,p=0,f="input"===n,g="output"===n,m=new a;!function n(){var a;if((u=d*o)127?r[i-128]:String.fromCharCode(i);return s}function x(e){return decodeURIComponent(escape(e))}function B(e){var t,i="";for(t=0;t>16,i=65535&e;try{return new Date(1980+((65024&t)>>9),((480&t)>>5)-1,31&t,(63488&i)>>11,(2016&i)>>5,2*(31&i),0)}catch(e){}}(e.lastModDateRaw),1!=(1&e.bitFlag)?((s||8!=(8&e.bitFlag))&&(e.crc32=t.view.getUint32(i+10,!0),e.compressedSize=t.view.getUint32(i+14,!0),e.uncompressedSize=t.view.getUint32(i+18,!0)),4294967295!==e.compressedSize&&4294967295!==e.uncompressedSize?(e.filenameLength=t.view.getUint16(i+22,!0),e.extraFieldLength=t.view.getUint16(i+24,!0)):r("File is using Zip64 (4gb+ file size).")):r("File contains encrypted entry.")}function P(t,o,n){var a=0;function l(){}l.prototype.getData=function(s,o,l,h){var c=this;function u(e,t){h&&!function(e){var t=A(4);return t.view.setUint32(0,e),c.crc32==t.view.getUint32(0)}(t)?n("CRC failed."):s.getData((function(e){o(e)}))}function d(e){n(e||r)}function p(e){n(e||"Error while writing file data.")}t.readUint8Array(c.offset,30,(function(r){var o,f=A(r.length,r);1347093252==f.view.getUint32(0)?(w(c,f,4,!1,n),o=c.offset+30+c.filenameLength+c.extraFieldLength,s.init((function(){0===c.compressionMethod?b(c._worker,a++,t,s,o,c.compressedSize,h,u,l,d,p):function(t,i,s,r,o,n,a,l,A,h,c){var u=a?"output":"none";e.zip.useWebWorkers?_(t,{sn:i,codecClass:"Inflater",crcType:u},s,r,o,n,A,l,h,c):v(new e.zip.Inflater,s,r,o,n,u,A,l,h,c)}(c._worker,a++,t,s,o,c.compressedSize,h,u,l,d,p)}),p)):n(i)}),d)};var h={getEntries:function(e){var r=this._worker;!function(e){t.size<22?n(i):r(22,(function(){r(Math.min(65558,t.size),(function(){n(i)}))}));function r(i,r){t.readUint8Array(t.size-i,i,(function(t){for(var i=t.length-22;i>=0;i--)if(80===t[i]&&75===t[i+1]&&5===t[i+2]&&6===t[i+3])return void e(new DataView(t.buffer,i,22));r()}),(function(){n(s)}))}}((function(o){var a,h;a=o.getUint32(16,!0),h=o.getUint16(8,!0),a<0||a>=t.size?n(i):t.readUint8Array(a,t.size-a,(function(t){var s,o,a,c,u=0,d=[],p=A(t.length,t);for(s=0;s>>8^i[255&(t^e[s])];this.crc=t},a.prototype.get=function(){return~this.crc},a.prototype.table=function(){var e,t,i,s=[];for(e=0;e<256;e++){for(i=e,t=0;t<8;t++)1&i?i=i>>>1^3988292384:i>>>=1;s[e]=i}return s}(),l.prototype.append=function(e,t){return e},l.prototype.flush=function(){},c.prototype=new h,c.prototype.constructor=c,u.prototype=new h,u.prototype.constructor=u,d.prototype=new h,d.prototype.constructor=d,p.prototype.getData=function(e){e(this.data)},f.prototype=new p,f.prototype.constructor=f,g.prototype=new p,g.prototype.constructor=g,m.prototype=new p,m.prototype.constructor=m;var F={deflater:["z-worker.js","deflate.js"],inflater:["z-worker.js","inflate.js"]};function I(t,i,s){if(null===e.zip.workerScripts||null===e.zip.workerScriptsPath){var r;if(e.zip.workerScripts){if(r=e.zip.workerScripts[t],!Array.isArray(r))return void s(new Error("zip.workerScripts."+t+" is not an array!"));r=function(e){var t=document.createElement("a");return e.map((function(e){return t.href=e,t.href}))}(r)}else(r=F[t].slice(0))[0]=(e.zip.workerScriptsPath||"")+r[0];var o=new Worker(r[0]);o.codecTime=o.crcTime=0,o.postMessage({type:"importScripts",scripts:r.slice(1)}),o.addEventListener("message",(function e(t){var r=t.data;if(r.error)return o.terminate(),void s(r.error);"importScripts"===r.type&&(o.removeEventListener("message",e),o.removeEventListener("error",n),i(o))})),o.addEventListener("error",n)}else s(new Error("Either zip.workerScripts or zip.workerScriptsPath may be set, not both."));function n(e){o.terminate(),s(e)}}function D(e){console.error(e)}e.zip={Reader:h,Writer:p,BlobReader:d,Data64URIReader:u,TextReader:c,BlobWriter:m,Data64URIWriter:g,TextWriter:f,createReader:function(e,t,i){i=i||D,e.init((function(){P(e,t,i)}),i)},createWriter:function(e,t,i,s){i=i||D,s=!!s,e.init((function(){E(e,t,i,s)}),i)},useWebWorkers:!0,workerScriptsPath:null,workerScripts:null}}(FP);const IP=FP.zip;!function(e){var t,i,s=e.Reader,r=e.Writer;try{i=0===new Blob([new DataView(new ArrayBuffer(0))]).size}catch(e){}function o(e){var t=this;function i(i,s){var r;t.data?i():((r=new XMLHttpRequest).addEventListener("load",(function(){t.size||(t.size=Number(r.getResponseHeader("Content-Length"))||Number(r.response.byteLength)),t.data=new Uint8Array(r.response),i()}),!1),r.addEventListener("error",s,!1),r.open("GET",e),r.responseType="arraybuffer",r.send())}t.size=0,t.init=function(s,r){if(function(e){var t=document.createElement("a");return t.href=e,"http:"===t.protocol||"https:"===t.protocol}(e)){var o=new XMLHttpRequest;o.addEventListener("load",(function(){t.size=Number(o.getResponseHeader("Content-Length")),t.size?s():i(s,r)}),!1),o.addEventListener("error",r,!1),o.open("HEAD",e),o.send()}else i(s,r)},t.readUint8Array=function(e,s,r,o){i((function(){r(new Uint8Array(t.data.subarray(e,e+s)))}),o)}}function n(e){var t=this;t.size=0,t.init=function(i,s){var r=new XMLHttpRequest;r.addEventListener("load",(function(){t.size=Number(r.getResponseHeader("Content-Length")),"bytes"==r.getResponseHeader("Accept-Ranges")?i():s("HTTP Range not supported.")}),!1),r.addEventListener("error",s,!1),r.open("HEAD",e),r.send()},t.readUint8Array=function(t,i,s,r){!function(t,i,s,r){var o=new XMLHttpRequest;o.open("GET",e),o.responseType="arraybuffer",o.setRequestHeader("Range","bytes="+t+"-"+(t+i-1)),o.addEventListener("load",(function(){s(o.response)}),!1),o.addEventListener("error",r,!1),o.send()}(t,i,(function(e){s(new Uint8Array(e))}),r)}}function a(e){var t=this;t.size=0,t.init=function(i,s){t.size=e.byteLength,i()},t.readUint8Array=function(t,i,s,r){s(new Uint8Array(e.slice(t,t+i)))}}function l(){var e,t=this;t.init=function(t,i){e=new Uint8Array,t()},t.writeUint8Array=function(t,i,s){var r=new Uint8Array(e.length+t.length);r.set(e),r.set(t,e.length),e=r,i()},t.getData=function(t){t(e.buffer)}}function A(e,t){var s,r=this;r.init=function(t,i){e.createWriter((function(e){s=e,t()}),i)},r.writeUint8Array=function(e,r,o){var n=new Blob([i?e:e.buffer],{type:t});s.onwrite=function(){s.onwrite=null,r()},s.onerror=o,s.write(n)},r.getData=function(t){e.file(t)}}o.prototype=new s,o.prototype.constructor=o,n.prototype=new s,n.prototype.constructor=n,a.prototype=new s,a.prototype.constructor=a,l.prototype=new r,l.prototype.constructor=l,A.prototype=new r,A.prototype.constructor=A,e.FileWriter=A,e.HttpReader=o,e.HttpRangeReader=n,e.ArrayBufferReader=a,e.ArrayBufferWriter=l,e.fs&&((t=e.fs.ZipDirectoryEntry).prototype.addHttpContent=function(i,s,r){return function(i,s,r,o){if(i.directory)return o?new t(i.fs,s,r,i):new e.fs.ZipFileEntry(i.fs,s,r,i);throw"Parent entry is not a directory."}(this,i,{data:s,Reader:r?n:o})},t.prototype.importHttpContent=function(e,t,i,s){this.importZip(t?new n(e):new o(e),i,s)},e.fs.FS.prototype.importHttpContent=function(e,i,s,r){this.entries=[],this.root=new t(this),this.root.importHttpContent(e,i,s,r)})}(IP);const DP=["4.2"];class SP{constructor(e,t={}){this.supportedSchemas=DP,this._xrayOpacity=.7,this._src=null,this._options=t,this.viewpoint=null,t.workerScriptsPath?(IP.workerScriptsPath=t.workerScriptsPath,this.src=t.src,this.xrayOpacity=.7,this.displayEffect=t.displayEffect,this.createMetaModel=t.createMetaModel):e.error("Config expected: workerScriptsPath")}load(e,t,i,s,r,o){switch(s.materialType){case"MetallicMaterial":t._defaultMaterial=new bs(t,{baseColor:[1,1,1],metallic:.6,roughness:.6});break;case"SpecularMaterial":t._defaultMaterial=new Bs(t,{diffuse:[1,1,1],specular:c.vec3([1,1,1]),glossiness:.5});break;default:t._defaultMaterial=new Jt(t,{reflectivity:.75,shiness:100,diffuse:[1,1,1]})}t._wireframeMaterial=new ms(t,{color:[0,0,0],lineWidth:2});var n=t.scene.canvas.spinner;n.processes++,TP(e,t,i,s,(function(){n.processes--,r&&r(),t.fire("loaded",!0,!1)}),(function(e){n.processes--,t.error(e),o&&o(e),t.fire("error",e)}),(function(e){console.log("Error, Will Robinson: "+e)}))}}var TP=function(e,t,i,s,r,o){!function(e,t,i){var s=new VP;s.load(e,(function(){t(s)}),(function(e){i("Error loading ZIP archive: "+e)}))}(i,(function(i){RP(e,i,s,t,r,o)}),o)},RP=function(){return function(t,i,s,r,o){var n={plugin:t,zip:i,edgeThreshold:30,materialType:s.materialType,scene:r.scene,modelNode:r,info:{references:{}},materials:{}};s.createMetaModel&&(n.metaModelData={modelId:r.id,metaObjects:[{name:r.id,type:"Default",id:r.id}]}),r.scene.loading++,function(t,i){t.zip.getFile("Manifest.xml",(function(s,r){for(var o=r.children,n=0,a=o.length;n0){for(var n=o.trim().split(" "),a=new Int16Array(n.length),l=0,A=0,h=n.length;A0){i.primitive="triangles";for(var o=[],n=0,a=r.length;n=t.length)i();else{var a=t[o].id,l=a.lastIndexOf(":");l>0&&(a=a.substring(l+1));var A=a.lastIndexOf("#");A>0&&(a=a.substring(0,A)),s[a]?r(o+1):function(e,t,i){e.zip.getFile(t,(function(t,s){!function(e,t,i){for(var s,r=t.children,o=0,n=r.length;o0)for(var s=0,r=t.length;s-1?e+"&_="+t:e+"?_="+t}getIFC(e,t,i){e=this._cacheBusterURL(e);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),i=new Uint8Array(e);for(var n=0;n-1?e+"&_="+t:e+"?_="+t}getLAS(e,t,i){e=this._cacheBusterURL(e);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),i=new Uint8Array(e);for(var n=0;n{let t=0,i=0,s=0;const r=new DataView(e),o=new Uint8Array(6e3),n=({item:s,format:o,size:n})=>{let a,l;switch(o){case"char":return l=new Uint8Array(e,t,n),t+=n,a=YP(l),[s,a];case"uShort":return a=r.getUint16(t,!0),t+=n,[s,a];case"uLong":return a=r.getUint32(t,!0),"NumberOfVariableLengthRecords"===s&&(i=a),t+=n,[s,a];case"uChar":return a=r.getUint8(t),t+=n,[s,a];case"double":return a=r.getFloat64(t,!0),t+=n,[s,a];default:t+=n}};return(()=>{const e={};WP.forEach((t=>{const i=n({...t});if(void 0!==i){if("FileSignature"===i[0]&&"LASF"!==i[1])throw new Error("Ivalid FileSignature. Is this a LAS/LAZ file");e[i[0]]=i[1]}}));const r=[];let a=i;for(;a--;){const e={};KP.forEach((i=>{const r=n({...i});e[r[0]]=r[1],"UserId"===r[0]&&"LASF_Projection"===r[1]&&(s=t-18+54)})),r.push(e)}const l=(e=>{if(void 0===e)return;const t=s+e.RecordLengthAfterHeader,i=o.slice(s,t),r=JP(i),n=new DataView(r);let a=6,l=Number(n.getUint16(a,!0));const A=[];for(;l--;){const e={};e.key=n.getUint16(a+=2,!0),e.tiffTagLocation=n.getUint16(a+=2,!0),e.count=n.getUint16(a+=2,!0),e.valueOffset=n.getUint16(a+=2,!0),A.push(e)}const h=A.find((e=>3072===e.key));if(h&&h.hasOwnProperty("valueOffset"))return h.valueOffset})(r.find((e=>"LASF_Projection"===e.UserId)));return l&&(e.epsg=l),e})()},JP=e=>{let t=new ArrayBuffer(e.length),i=new Uint8Array(t);for(let t=0;t{let t="";return e.forEach((e=>{let i=String.fromCharCode(e);"\0"!==i&&(t+=i)})),t.trim()};function ZP(e,t){if(t>=e.length)return[e];let i=[];for(let s=0;s-1?e+"&_="+t:e+"?_="+t}getCityJSON(e,t,i){_.loadJSON(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}}function $P(e,t,i){i=i||2;var s,r,o,n,a,l,A,h=t&&t.length,c=h?t[0]*i:e.length,u=eC(e,0,c,i,!0),d=[];if(!u||u.next===u.prev)return d;if(h&&(u=function(e,t,i,s){var r,o,n,a=[];for(r=0,o=t.length;r80*i){s=o=e[0],r=n=e[1];for(var p=i;po&&(o=a),l>n&&(n=l);A=0!==(A=Math.max(o-s,n-r))?1/A:0}return iC(u,d,i,s,r,A),d}function eC(e,t,i,s,r){var o,n;if(r===wC(e,t,i,s)>0)for(o=t;o=t;o-=s)n=yC(o,e[o],e[o+1],n);return n&&fC(n,n.next)&&(xC(n),n=n.next),n}function tC(e,t){if(!e)return e;t||(t=e);var i,s=e;do{if(i=!1,s.steiner||!fC(s,s.next)&&0!==pC(s.prev,s,s.next))s=s.next;else{if(xC(s),(s=t=s.prev)===s.next)break;i=!0}}while(i||s!==t);return t}function iC(e,t,i,s,r,o,n){if(e){!n&&o&&function(e,t,i,s){var r=e;do{null===r.z&&(r.z=hC(r.x,r.y,t,i,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==e);r.prevZ.nextZ=null,r.prevZ=null,function(e){var t,i,s,r,o,n,a,l,A=1;do{for(i=e,e=null,o=null,n=0;i;){for(n++,s=i,a=0,t=0;t0||l>0&&s;)0!==a&&(0===l||!s||i.z<=s.z)?(r=i,i=i.nextZ,a--):(r=s,s=s.nextZ,l--),o?o.nextZ=r:e=r,r.prevZ=o,o=r;i=s}o.nextZ=null,A*=2}while(n>1)}(r)}(e,s,r,o);for(var a,l,A=e;e.prev!==e.next;)if(a=e.prev,l=e.next,o?rC(e,s,r,o):sC(e))t.push(a.i/i),t.push(e.i/i),t.push(l.i/i),xC(e),e=l.next,A=l.next;else if((e=l)===A){n?1===n?iC(e=oC(tC(e),t,i),t,i,s,r,o,2):2===n&&nC(e,t,i,s,r,o):iC(tC(e),t,i,s,r,o,1);break}}}function sC(e){var t=e.prev,i=e,s=e.next;if(pC(t,i,s)>=0)return!1;for(var r=e.next.next;r!==e.prev;){if(uC(t.x,t.y,i.x,i.y,s.x,s.y,r.x,r.y)&&pC(r.prev,r,r.next)>=0)return!1;r=r.next}return!0}function rC(e,t,i,s){var r=e.prev,o=e,n=e.next;if(pC(r,o,n)>=0)return!1;for(var a=r.xo.x?r.x>n.x?r.x:n.x:o.x>n.x?o.x:n.x,h=r.y>o.y?r.y>n.y?r.y:n.y:o.y>n.y?o.y:n.y,c=hC(a,l,t,i,s),u=hC(A,h,t,i,s),d=e.prevZ,p=e.nextZ;d&&d.z>=c&&p&&p.z<=u;){if(d!==e.prev&&d!==e.next&&uC(r.x,r.y,o.x,o.y,n.x,n.y,d.x,d.y)&&pC(d.prev,d,d.next)>=0)return!1;if(d=d.prevZ,p!==e.prev&&p!==e.next&&uC(r.x,r.y,o.x,o.y,n.x,n.y,p.x,p.y)&&pC(p.prev,p,p.next)>=0)return!1;p=p.nextZ}for(;d&&d.z>=c;){if(d!==e.prev&&d!==e.next&&uC(r.x,r.y,o.x,o.y,n.x,n.y,d.x,d.y)&&pC(d.prev,d,d.next)>=0)return!1;d=d.prevZ}for(;p&&p.z<=u;){if(p!==e.prev&&p!==e.next&&uC(r.x,r.y,o.x,o.y,n.x,n.y,p.x,p.y)&&pC(p.prev,p,p.next)>=0)return!1;p=p.nextZ}return!0}function oC(e,t,i){var s=e;do{var r=s.prev,o=s.next.next;!fC(r,o)&&gC(r,s,s.next,o)&&vC(r,o)&&vC(o,r)&&(t.push(r.i/i),t.push(s.i/i),t.push(o.i/i),xC(s),xC(s.next),s=e=o),s=s.next}while(s!==e);return tC(s)}function nC(e,t,i,s,r,o){var n=e;do{for(var a=n.next.next;a!==n.prev;){if(n.i!==a.i&&dC(n,a)){var l=bC(n,a);return n=tC(n,n.next),l=tC(l,l.next),iC(n,t,i,s,r,o),void iC(l,t,i,s,r,o)}a=a.next}n=n.next}while(n!==e)}function aC(e,t){return e.x-t.x}function lC(e,t){if(t=function(e,t){var i,s=t,r=e.x,o=e.y,n=-1/0;do{if(o<=s.y&&o>=s.next.y&&s.next.y!==s.y){var a=s.x+(o-s.y)*(s.next.x-s.x)/(s.next.y-s.y);if(a<=r&&a>n){if(n=a,a===r){if(o===s.y)return s;if(o===s.next.y)return s.next}i=s.x=s.x&&s.x>=h&&r!==s.x&&uC(oi.x||s.x===i.x&&AC(i,s)))&&(i=s,u=l)),s=s.next}while(s!==A);return i}(e,t),t){var i=bC(t,e);tC(t,t.next),tC(i,i.next)}}function AC(e,t){return pC(e.prev,e,t.prev)<0&&pC(t.next,e,e.next)<0}function hC(e,t,i,s,r){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-i)*r)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-s)*r)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function cC(e){var t=e,i=e;do{(t.x=0&&(e-n)*(s-a)-(i-n)*(t-a)>=0&&(i-n)*(o-a)-(r-n)*(s-a)>=0}function dC(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){var i=e;do{if(i.i!==e.i&&i.next.i!==e.i&&i.i!==t.i&&i.next.i!==t.i&&gC(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}(e,t)&&(vC(e,t)&&vC(t,e)&&function(e,t){var i=e,s=!1,r=(e.x+t.x)/2,o=(e.y+t.y)/2;do{i.y>o!=i.next.y>o&&i.next.y!==i.y&&r<(i.next.x-i.x)*(o-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==e);return s}(e,t)&&(pC(e.prev,e,t.prev)||pC(e,t.prev,t))||fC(e,t)&&pC(e.prev,e,e.next)>0&&pC(t.prev,t,t.next)>0)}function pC(e,t,i){return(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y)}function fC(e,t){return e.x===t.x&&e.y===t.y}function gC(e,t,i,s){var r=_C(pC(e,t,i)),o=_C(pC(e,t,s)),n=_C(pC(i,s,e)),a=_C(pC(i,s,t));return r!==o&&n!==a||(!(0!==r||!mC(e,i,t))||(!(0!==o||!mC(e,s,t))||(!(0!==n||!mC(i,e,s))||!(0!==a||!mC(i,t,s)))))}function mC(e,t,i){return t.x<=Math.max(e.x,i.x)&&t.x>=Math.min(e.x,i.x)&&t.y<=Math.max(e.y,i.y)&&t.y>=Math.min(e.y,i.y)}function _C(e){return e>0?1:e<0?-1:0}function vC(e,t){return pC(e.prev,e,e.next)<0?pC(e,t,e.next)>=0&&pC(e,e.prev,t)>=0:pC(e,t,e.prev)<0||pC(e,e.next,t)<0}function bC(e,t){var i=new BC(e.i,e.x,e.y),s=new BC(t.i,t.x,t.y),r=e.next,o=t.prev;return e.next=t,t.prev=e,i.next=r,r.prev=i,s.next=i,i.prev=s,o.next=s,s.prev=o,s}function yC(e,t,i,s){var r=new BC(e,t,i);return s?(r.next=s.next,r.prev=s,s.next.prev=r,s.next=r):(r.prev=r,r.next=r),r}function xC(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function BC(e,t,i){this.i=e,this.x=t,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function wC(e,t,i,s){for(var r=0,o=t,n=i-s;o0&&(s+=e[r-1].length,i.holes.push(s))}return i};const PC=c.vec2(),CC=c.vec3(),MC=c.vec3(),EC=c.vec3();class FC{constructor(e={}){this.cacheBuster=!1!==e.cacheBuster}_cacheBusterURL(e){if(!this.cacheBuster)return e;const t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}getDotBIM(e,t,i){_.loadJSON(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}}const IC=function(e){const t=t=>parseInt(e.substr(t+1,2),16)/255;return[t(0),t(2),t(4)]},DC=function(e){const t=[];for(let i=0;i=0?h:2*Math.PI-h}return r(e[0]-i[0])*(t[1]-i[1])-(t[0]-i[0])*(e[1]-i[1]);return(t,i,s,r)=>{const o=e(t,i,s),n=e(t,s,r),a=e(t,r,i);return!((o<0||n<0||a<0)&&(o>0||n>0||a>0))}}(),r=[],o=(i?t:t.slice(0).reverse()).map((e=>({idx:e})));o.forEach(((e,t)=>{e.prev=o[(t-1+o.length)%o.length],e.next=o[(t+1)%o.length]}));const n=c.vec2(),a=c.vec2();for(;o.length>2;){let t=0;for(;;){if(t>=o.length)throw`isCCW = ${i}; earIdx = ${t}; len = ${o.length}`;const r=o[t],l=e[r.prev.idx],A=e[r.idx],h=e[r.next.idx];if(c.subVec2(l,A,n),c.subVec2(h,A,a),n[0]*a[1]-n[1]*a[0]>=0&&o.every((t=>t===r||t===r.prev||t===r.next||!s(e[t.idx],l,A,h))))break;++t}const l=o[t];o.splice(t,1),r.push([l.idx,l.next.idx,l.prev.idx]);l.prev.next=l.next;l.next.prev=l.prev}return[e,r,i]},SC=function(e,t){const i=e.canvas.canvas,s=i.parentNode,r=document.createElement("div");s.insertBefore(r,i);let o=5;r.style.background=t,r.style.border="2px solid white",r.style.margin="0 0",r.style.zIndex="100",r.style.position="absolute",r.style.pointerEvents="none",r.style.display="none";const n=new Ae(e,{}),a=e=>e+"px",l=function(){const e=n.canvasPos.slice();ce(i,s,e),r.style.left=a(e[0]-3-o/2),r.style.top=a(e[1]-3-o/2),r.style.borderRadius=a(2*o),r.style.width=a(o),r.style.height=a(o)},A=e.camera.on("viewMatrix",l),h=e.camera.on("projMatrix",l);return{update:function(e){e&&(n.worldPos=e,l()),r.style.display=e?"":"none"},setHighlighted:function(e){o=e?10:5,l()},getCanvasPos:()=>n.canvasPos,getWorldPos:()=>n.worldPos,destroy:function(){r.parentNode.removeChild(r),e.camera.off(A),e.camera.off(h),n.destroy()}}},TC=function(e,t,i){let s=null;const r=r=>{if(r){s&&s.destroy();try{const[o,n]=DC(r.map((e=>[e[0],e[2]]))),a=[].concat(...o.map((e=>[e[0],r[0][1],e[1]]))),l=[].concat(...n);s=new es(e,{pickable:!1,geometry:new Gt(e,{positions:a,indices:l,normals:c.buildNormals(a,l)}),material:new Jt(e,{alpha:void 0!==i?i:.5,backfaces:!0,diffuse:IC(t)})})}catch(e){s=null}}s&&(s.visible=!!r)};return r(null),{updateBase:r,destroy:()=>s&&s.destroy()}},RC=function(e,t){return function(i,s,r){const o=e.scene,n=o.canvas.canvas,a=(e,t)=>(t[0]=e.clientX,t[1]=e.clientY,ce(n.ownerDocument.documentElement,n,t),t),l=e=>{const i=c.vec3(),s=c.vec3();return c.canvasPosToWorldRay(n,o.camera.viewMatrix,o.camera.projMatrix,o.camera.projection,e,i,s),t(i,s)};let A=!1;const h=function(){A=!1},u=function(){h(),n.removeEventListener("mousedown",p),n.removeEventListener("mousemove",f),e.cameraControl.off(g),n.removeEventListener("mouseup",m)},d=c.vec2(),p=function(e){1===e.which&&(a(e,d),A=!0)};n.addEventListener("mousedown",p);const f=function(e){const t=a(e,c.vec2());A&&c.distVec2(d,t)>20&&(h(),i())};n.addEventListener("mousemove",f);const g=e.cameraControl.on("rayMove",(e=>{const t=e.canvasPos;s(t,l(t))})),m=function(e){if(1===e.which&&A){u();const t=a(e,c.vec2());r(t,l(t))}};return n.addEventListener("mouseup",m),u}},LC=function(e,t,i,s){const r=-(c.dotVec3(i,t)-e)/c.dotVec3(s,t);{const e=c.vec3();return c.mulVec3Scalar(s,r,e),c.addVec3(i,e,e),e}};class UC extends D{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={},this.plugin.viewer.scene,this._geometry=t.geometry,t.onMouseOver,t.onMouseLeave,t.onContextMenu,this._alpha="alpha"in t&&void 0!==t.alpha?t.alpha:.5,this.color=t.color,this._visible=!0,this._rebuildMesh()}_rebuildMesh(){const e=this.plugin.viewer.scene,t=this._geometry.planeCoordinates.slice(),i=this._geometry.height<0,s=this._geometry.altitude+(i?this._geometry.height:0),r=this._geometry.height*(i?-1:1),[o,n,a]=DC(t),l=[],A=[],h=e=>{const t=l.length;for(let t of o)l.push([t[0],s+(e?r:0),t[1]]);for(let i of n)A.push(...(e?i:i.slice(0).reverse()).map((e=>e+t)))};h(!1),h(!0);for(let e=0;ee+c)))}this._zoneMesh&&this._zoneMesh.destroy();const u=[].concat(...l);this._zoneMesh=new es(e,{edges:this._edges,geometry:new Gt(e,{positions:u,indices:A,normals:c.buildNormals(u,A)}),material:new Jt(e,{alpha:this._alpha,backfaces:!0,diffuse:IC(this._color)}),visible:this._visible}),this._zoneMesh.highlighted=this._highlighted,this._zoneMesh.zone=this;{const e=c.vec2(),t=c.vec2();let i=0;for(let s of n){const r=o[s[0]],n=o[s[1]],a=o[s[2]];c.subVec2(n,r,e),c.subVec2(a,r,t),i+=Math.abs(e[0]*t[1]-e[1]*t[0])}this._baseArea=i/2}this._metrics=null;const d=e=>Math.min(...l.map((t=>t[e]))),p=e=>Math.max(...l.map((t=>t[e]))),f=d(0),g=d(1),m=d(2),_=p(0),v=p(1),b=p(2);this._center=c.vec3([(f+_)/2,(g+v)/2,(m+b)/2])}get baseArea(){return this._baseArea}get area(){return this._getMetrics().area}get volume(){return this._getMetrics().volume}_getMetrics(){if(null===this._metrics){let e=0,t=0;const i=this._zoneMesh.geometry,s=[c.vec3(),c.vec3(),c.vec3()],r=c.vec3();for(let o=0;o{const s=t.map((t=>[t[0],e?r:o,t[1]]));i.push(e?s:s.slice(0).reverse())};n(!0),n(!1);const a=(e,i)=>[t[e][0],i,t[e][1]];for(let e=0;ei?a:n;h|=A,u.push(A)}switch(h){case n:case a:o.push(t);break;case l:break;case A:const i=[];for(let o=0;o=3&&o.push(i)}}i=o}if(0===i.length)return null;{const e=c.vec3([0,0,0]),t=new Set;for(const s of i)for(const i of s){const s=i.map((e=>e.toFixed(3))).join(":");t.has(s)||(t.add(s),c.addVec3(e,i,e))}return c.mulVec3Scalar(e,1/t.size,e),e}}get center(){return this._center}get altitude(){return this._geometry.altitude}set altitude(e){this._geometry.altitude=e,this._rebuildMesh()}get height(){return this._geometry.height}set height(e){this._geometry.height=e,this._rebuildMesh()}get highlighted(){return this._highlighted}set highlighted(e){this._highlighted=e,this._zoneMesh&&(this._zoneMesh.highlighted=e)}set color(e){this._color=e,this._zoneMesh&&(this._zoneMesh.material.diffuse=IC(this._color))}get color(){return this._color}set alpha(e){this._alpha=e,this._zoneMesh&&(this._zoneMesh.material.alpha=this._alpha)}get alpha(){return this._alpha}get edges(){return this._edges}set edges(e){this._edges=e,this._zoneMesh&&(this._zoneMesh.edges=this._edges)}set visible(e){this._visible=!!e,this._zoneMesh.visible=this._visible,this._needUpdate()}get visible(){return this._visible}getJSON(){return{id:this.id,geometry:this._geometry,alpha:this._alpha,color:this._color}}duplicate(){return this.plugin.createZone({id:c.createUUID(),geometry:{planeCoordinates:this._geometry.planeCoordinates.map((e=>e.slice())),altitude:this._geometry.altitude,height:this._geometry.height},alpha:this._alpha,color:this._color})}destroy(){this._zoneMesh.destroy(),super.destroy()}}class kC extends D{constructor(e,t,i){super(e.viewer.scene),this.zonesPlugin=e,this.pointerLens=t.pointerLens,this.createSelect3dPoint=i,this._deactivate=null}get active(){return!!this._deactivate}activate(e,t,i,s){if(this._deactivate)return;if("object"==typeof e&&null!==e){const r=e,o=(e,t)=>{if(e in r)return r[e];if(void 0!==t)return t;throw"config missing: "+e};e=o("altitude"),t=o("height"),i=o("color","#008000"),s=o("alpha",.5)}const r=this.zonesPlugin,o=r.viewer,n=o.scene,a=this,l=this.createSelect3dPoint(o,((t,i)=>LC(e,c.vec3([0,1,0]),t,i)));!function o(){const A=TC(n,i,s),h=function(e,t,i,s,r,o){const n=SC(e,t),a=SC(e,t),l=i?function(e){i.visible=!!e,e&&(i.canvasPos=e)}:()=>{};let A=s((()=>{l(null),n.update(null)}),((e,t)=>{l(e),n.update(t)}),(function(e,t){n.update(t),A=s((function(){l(null),a.update(null),r(null)}),(function(e,i){l(e),a.update(i),r(c.distVec3(t,i)>.01&&[t,i])}),(function(e,i){a.update(i),n.destroy(),a.destroy(),l(null),o([t,i])}))}));return{deactivate:function(){A(),n.destroy(),a.destroy(),l(null)}}}(n,i,a.pointerLens,l,(e=>{if(e){const t=e[0],i=e[1],s=e=>Math.min(t[e],i[e]),r=e=>Math.max(t[e],i[e]),o=s(0),n=s(1),a=s(2),l=r(0);r(1);const h=r(2);A.updateBase([[o,n,h],[l,n,h],[l,n,a],[o,n,a]])}else A.updateBase(null)}),(n=>{A.destroy();const l=function(e,t,i,s,r,o,n){const a=i=>Math.min(e[i],t[i]),l=i=>Math.max(e[i],t[i]),A=a(0),h=a(2),u=l(0),d=l(2);return n.createZone({id:c.createUUID(),geometry:{planeCoordinates:[[A,d],[u,d],[u,h],[A,h]],altitude:i,height:s},alpha:o,color:r})}(n[0],n[1],e,t,i,s,r);let h=!0;a._deactivate=()=>{h=!1},a.fire("zoneEnd",l),h&&o()})).deactivate;a._deactivate=()=>{h(),A.destroy()}}()}deactivate(){this._deactivate&&(this._deactivate(),this._deactivate=null)}destroy(){this.deactivate(),super.destroy()}}const OC=function(e,t,i,s,r,o,n,a,l){const A=o?function(e){o.visible=!!e,e&&(o.canvasPos=e)}:()=>{};let h;const u=[()=>A(null)],d=TC(e,s,r);return u.push((()=>d.destroy())),function o(p){const f=SC(e,s),g=p.length>0&&function(e,t,i){const s=e.canvas.canvas,r=new Ae(e,{});r.worldPos=i;const o=new Ae(e,{}),n=s.ownerDocument.body,a=new ge(n,{color:t,thickness:1,thicknessClickable:6});a.setVisible(!1);const l=function(){const e=r.canvasPos.slice(),t=o.canvasPos.slice();ce(s,n,e),ce(s,n,t),a.setStartAndEnd(e[0],e[1],t[0],t[1])},A=e.camera.on("viewMatrix",l),h=e.camera.on("projMatrix",l);return{update:function(e){e&&(o.worldPos=e,l()),a.setVisible(!!e)},destroy:function(){e.camera.off(A),e.camera.off(h),r.destroy(),o.destroy(),a.destroy()}}}(e,s,p[p.length-1].getWorldPos());u.push((()=>{f.destroy(),g&&g.destroy()}));const m=p.length>0&&p[0],_=function(e){const t=m&&m.getCanvasPos();return t&&c.distVec2(t,e)<10&&{canvasPos:t,worldPos:m.getWorldPos()}},v=function(){const e=(e,t,i)=>t[0]<=Math.max(e[0],i[0])&&t[0]>=Math.min(e[0],i[0])&&t[1]<=Math.max(e[1],i[1])&&t[1]>=Math.min(e[1],i[1]),t=(e,t,i)=>{const s=(t[1]-e[1])*(i[0]-t[0])-(t[0]-e[0])*(i[1]-t[1]);return 0===s?0:s>0?1:2};return function(i,s){const r=i[i.length-2],o=i[i.length-1];for(let n=s?1:0;n{A(null),f.update(null),g&&g.update(null),d.updateBase(p.length>2?p.map((e=>e.getWorldPos())):null)}),((e,t)=>{const i=p.length>2&&_(e);if(m&&m.setHighlighted(!!i),A(i?i.canvasPos:e),f.update(!i&&t),g&&g.update(i?i.worldPos:t),p.length>=2){const e=p.map((e=>e.getWorldPos())).concat(i?[]:[t]),s=v(e.map((e=>[e[0],e[2]])),i);d.updateBase(s?null:e)}else d.updateBase(null)}),(function(e,a){const A=p.length>2&&_(e),h=p.map((e=>e.getWorldPos())).concat(A?[]:[a]);d.updateBase(h);const m=h.map((e=>[e[0],e[2]]));p.length>2&&v(m,A)?(u.pop()(),o(p)):A?(f.update(a),u.forEach((e=>e())),l(n.createZone({id:c.createUUID(),geometry:{planeCoordinates:m,altitude:t,height:i},alpha:r,color:s}))):(f.update(a),g&&g.update(a),o(p.concat(f)))}))}([]),{closeSurface:function(){throw"TODO"},deactivate:function(){h(),u.forEach((e=>e()))}}};class NC extends D{constructor(e,t,i,s){const r=e.plugin.viewer,o=r.scene;super(o);const n=e._geometry.altitude,a=e._geometry.planeCoordinates.map((t=>{const i=o.canvas.canvas.ownerDocument.body,s=new ue(o,{},i,{fillColor:e._color});return s.worldPos=c.vec3([t[0],n,t[1]]),s.on("worldPos",(function(){t[0]=s.worldPos[0],t[1]=s.worldPos[2];try{e._rebuildMesh()}catch(t){e._zoneMesh&&(e._zoneMesh.destroy(),e._zoneMesh=null)}})),s})),l=pe({viewer:r,handleMouseEvents:i,handleTouchEvents:s,pointerLens:t&&t.pointerLens,dots:a,ray2WorldPos:(e,t)=>LC(n,c.vec3([0,1,0]),e,t),onEnd:(t,i)=>(e._zoneMesh&&this.fire("edited"),!!e._zoneMesh)}),A=function(){l(),a.forEach((e=>e.destroy()))},h=e.on("destroyed",A);this._deactivate=function(){e.off("destroyed",h),A()}}deactivate(){this._deactivate(),super.destroy()}}class QC extends D{constructor(e,t,i,s){const r=e.plugin.viewer,o=r.scene,n=o.canvas.canvas;super(o);const a=this,l=e._geometry.altitude,A=t&&t.pointerLens,h=A?function(e){A.visible=!!e,e&&(A.canvasPos=e)}:()=>{},u=e=>{const t=c.vec3(),i=c.vec3();return c.canvasPosToWorldRay(n,o.camera.viewMatrix,o.camera.projMatrix,o.camera.projection,e,t,i),s=t,r=i,LC(l,c.vec3([0,1,0]),s,r);var s,r},d=(e,t)=>(t[0]=e.clientX,t[1]=e.clientY,ce(n.ownerDocument.documentElement,n,t),t),p=function(e,t){const i=e=>{e.preventDefault(),t(e)};return n.addEventListener(e,i),()=>n.removeEventListener(e,i)};let f=()=>{};const g=function(t,i,s,o){const l=o(t),A=d(l,c.vec2()),g=r.scene.pick({canvasPos:A,includeEntities:[e._zoneMesh.id]});if((g&&g.entity&&g.entity.zone)===e){f(),n.style.cursor="move",r.cameraControl.active=!1;const t=function(){const t=e._geometry.planeCoordinates.map((e=>e.slice())),i=u(A),s=c.vec2([i[0],i[2]]),r=c.vec2();return function(i){const o=u(i);r[0]=o[0],r[1]=o[2],c.subVec2(s,r,r),e._geometry.planeCoordinates.forEach(((e,i)=>{c.subVec2(t[i],r,e)}));try{e._rebuildMesh()}catch(t){e._zoneMesh&&(e._zoneMesh.destroy(),e._zoneMesh=null)}}}(),l=p(i,(function(e){const i=o(e);if(i){const e=d(i,c.vec2());t(e),h(e)}})),g=p(s,(function(e){const i=o(e);if(i){const e=d(i,c.vec2());t(e),h(null),f(),a.fire("translated")}}));f=function(){f=()=>{},n.style.cursor="default",r.cameraControl.active=!0,l(),g()}}},m=[];i&&m.push(p("mousedown",(e=>{1===e.which&&g(e,"mousemove","mouseup",(e=>1===e.which&&e))}))),s&&m.push(p("touchstart",(e=>{if(1===e.touches.length){const t=e.touches[0].identifier;g(e,"touchmove","touchend",(e=>[...e.changedTouches].find((e=>e.identifier===t))))}})));const _=function(){f(),m.forEach((e=>e())),h(null)},v=e.on("destroyed",_);this._deactivate=function(){e.off("destroyed",v),_()}}deactivate(){this._deactivate(),super.destroy()}}exports.AlphaFormat=1021,exports.AmbientLight=St,exports.AngleMeasurementEditMouseControl=class extends Be{constructor(e,t){super(e,t,!0,!1)}},exports.AngleMeasurementEditTouchControl=class extends Be{constructor(e,t){super(e,t,!1,!0)}},exports.AngleMeasurementsControl=ye,exports.AngleMeasurementsMouseControl=xe,exports.AngleMeasurementsPlugin=class extends V{constructor(e,t={}){super("AngleMeasurements",e),this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.zIndex=t.zIndex||1e4,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,angleMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get control(){return this._defaultControl||(this._defaultControl=new xe(this,{})),this._defaultControl}get measurements(){return this._measurements}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,i=e.corner,s=e.target,r=new be(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},corner:{entity:i.entity,worldPos:i.worldPos},target:{entity:s.entity,worldPos:s.worldPos},visible:e.visible,originVisible:!0,originWireVisible:!0,cornerVisible:!0,targetWireVisible:!0,targetVisible:!0,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[r.id]=r,r.on("destroyed",(()=>{delete this._measurements[r.id]})),r.clickable=!0,this.fire("measurementCreated",r),r}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("AngleMeasurement not found: "+e)}setLabelsShown(e){for(const[t,i]of Object.entries(this.measurements))i.labelShown=e}clear(){const e=Object.keys(this._measurements);for(var t=0,i=e.length;t{this.plugin.viewer.cameraControl.active=!1},u=()=>{this.plugin.viewer.cameraControl.active=!0},d=()=>{o&&(clearTimeout(o),o=null),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),u(),this._touchState=0};i.addEventListener("touchstart",this._onCanvasTouchStart=i=>{const l=i.touches.length;if(1!==l)return void(o&&(clearTimeout(o),o=null));const u=i.touches[0],p=u.clientX,f=u.clientY;switch(n.set([p,f]),a.set([p,f]),this._touchState){case 0:if(1!==l&&null!==o)return void d();const i=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping});if(i&&i.snapped)s.set(i.worldPos),this.pointerCircle.start(i.snappedCanvasPos);else{const e=t.pick({canvasPos:a,pickSurface:!0});if(!e||!e.worldPos)return;s.set(e.worldPos),this.pointerCircle.start(e.canvasPos)}o=setTimeout((()=>{1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{if(o=null,1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{if(o=null,1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{this.pointerCircle.stop();const i=e.touches.length;if(1!==i||1!==e.changedTouches.length)return void(o&&(clearTimeout(o),o=null));const r=e.touches[0],n=r.clientX,l=r.clientY;if(r.identifier!==A)return;let h,c;switch(a.set([n,l]),this._touchState){case 2:this.pointerLens&&(this.pointerLens.canvasPos=a),h=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),h&&h.snapped?(this.pointerLens&&(this.pointerLens.snappedCanvasPos=h.snappedCanvasPos,this.pointerLens.snapped=!0),s.set(h.worldPos),this._currentAngleMeasurement.origin.worldPos=h.worldPos):(c=t.pick({canvasPos:a,pickSurface:!0}),c&&c.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=c.canvasPos,this.pointerLens.snapped=!1),s.set(c.worldPos),this._currentAngleMeasurement.origin.worldPos=c.worldPos):this.pointerLens&&(this.pointerLens.cursorPos=null,this.pointerLens.snapped=!1)),this._touchState=2;break;case 5:if(1!==i&&null!==o)return clearTimeout(o),o=null,this.pointerLens&&(this.pointerLens.visible=!1),void(this._touchState=7);this.pointerLens&&(this.pointerLens.canvasPos=a),h=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),h&&h.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=h.snappedCanvasPos,this.pointerLens.snapped=!0),this._currentAngleMeasurement.corner.worldPos=h.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1):(c=t.pick({canvasPos:a,pickSurface:!0}),c&&c.worldPos&&(this.pointerLens&&(this.pointerLens.cursorPos=c.canvasPos,this.pointerLens.snapped=!1),this._currentAngleMeasurement.corner.worldPos=c.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1)),this._touchState=5;break;case 8:if(1!==i&&null!==o)return clearTimeout(o),o=null,this.pointerLens&&(this.pointerLens.visible=!1),void(this._touchState=7);this.pointerLens&&(this.pointerLens.canvasPos=a),h=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),h&&h.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=h.snappedCanvasPos,this.pointerLens.snapped=!0),this._currentAngleMeasurement.target.worldPos=h.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.angleVisible=!0):(c=t.pick({canvasPos:a,pickSurface:!0}),c&&c.worldPos&&(this.pointerLens&&(this.pointerLens.cursorPos=c.canvasPos,this.pointerLens.snapped=!1),this._currentAngleMeasurement.target.worldPos=c.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.angleVisible=!0)),this._touchState=8}}),{passive:!0}),i.addEventListener("touchend",this._onCanvasTouchEnd=i=>{this.pointerCircle.stop();const s=i.changedTouches.length;if(1!==s)return;const h=i.changedTouches[0],d=h.clientX,p=h.clientY;if(h.identifier===A)switch(o&&(clearTimeout(o),o=null),l.set([d,p]),this._touchState){case 1:{if(1!==s||d>n[0]+r||dn[1]+r||pn[0]+r||dn[1]+r||pn[0]+r||dn[1]+r||p",this._markerHTML=t.markerHTML||"
",this._container=t.container||document.body,this._values=t.values||{},this.annotations={},this.surfaceOffset=t.surfaceOffset}getContainerElement(){return this._container}send(e,t){if("clearAnnotations"===e)this.clear()}set surfaceOffset(e){null==e&&(e=.3),this._surfaceOffset=e}get surfaceOffset(){return this._surfaceOffset}createAnnotation(e){this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id);var t=null;e.markerElementId&&((t=document.getElementById(e.markerElementId))||this.error("Can't find DOM element for 'markerElementId' value '"+e.markerElementId+"' - defaulting to internally-generated empty DIV"));var i=null;e.labelElementId&&((i=document.getElementById(e.labelElementId))||this.error("Can't find DOM element for 'labelElementId' value '"+e.labelElementId+"' - defaulting to internally-generated empty DIV"));const s=new Me(this.viewer.scene,{id:e.id,plugin:this,container:this._container,markerElement:t,labelElement:i,markerHTML:e.markerHTML||this._markerHTML,labelHTML:e.labelHTML||this._labelHTML,occludable:e.occludable,values:_.apply(e.values,_.apply(this._values,{})),markerShown:e.markerShown,labelShown:e.labelShown,eye:e.eye,look:e.look,up:e.up,projection:e.projection,visible:!1!==e.visible});return e.pickResult=e.pickResult||e.pickRecord,e.pickResult?s.setFromPickResult(e.pickResult):(s.entity=e.entity,s.worldPos=e.worldPos),this.annotations[s.id]=s,s.on("destroyed",(()=>{delete this.annotations[s.id],this.fire("annotationDestroyed",s.id)})),this.fire("annotationCreated",s.id),s}destroyAnnotation(e){var t=this.annotations[e];t?t.destroy():this.log("Annotation not found: "+e)}clear(){const e=Object.keys(this.annotations);for(var t=0,i=e.length;tp.has(e.id)||g.has(e.id)||f.has(e.id))).reduce(((e,i)=>{let s,r=function(e){let t="";return t+=Math.round(255*e[0]).toString(16).padStart(2,"0"),t+=Math.round(255*e[1]).toString(16).padStart(2,"0"),t+=Math.round(255*e[2]).toString(16).padStart(2,"0"),t}(i.colorize);i.xrayed?(s=0===t.xrayMaterial.fillAlpha&&0!==t.xrayMaterial.edgeAlpha?.1:t.xrayMaterial.fillAlpha,s=Math.round(255*s).toString(16).padStart(2,"0"),r=s+r):p.has(i.id)&&(s=Math.round(255*i.opacity).toString(16).padStart(2,"0"),r=s+r),e[r]||(e[r]=[]);const o=i.id,n=i.originalSystemId,a={ifc_guid:n,originating_system:this.originatingSystem};return n!==o&&(a.authoring_tool_id=o),e[r].push(a),e}),{}),_=Object.entries(m).map((([e,t])=>({color:e,components:t})));o.components.coloring=_;const v=t.objectIds,b=t.visibleObjects,y=t.visibleObjectIds,x=v.filter((e=>!b[e])),B=t.selectedObjectIds;return e.defaultInvisible||y.length0&&e.clipping_planes.forEach((function(e){let t=yh(e.location,gh),i=yh(e.direction,gh);A&&c.negateVec3(i),c.subVec3(t,l),r.yUp&&(t=Bh(t),i=Bh(i)),new ns(s,{pos:t,dir:i})})),s.clearLines(),e.lines&&e.lines.length>0){const t=[],i=[];let r=0;e.lines.forEach((e=>{e.start_point&&e.end_point&&(t.push(e.start_point.x),t.push(e.start_point.y),t.push(e.start_point.z),t.push(e.end_point.x),t.push(e.end_point.y),t.push(e.end_point.z),i.push(r++),i.push(r++))})),new fh(s,{positions:t,indices:i,clippable:!1,collidable:!0})}if(s.clearBitmaps(),e.bitmaps&&e.bitmaps.length>0&&e.bitmaps.forEach((function(e){const t=e.bitmap_type||"jpg",i=e.bitmap_data;let o=yh(e.location,mh),n=yh(e.normal,_h),a=yh(e.up,vh),l=e.height||1;t&&i&&o&&n&&a&&(r.yUp&&(o=Bh(o),n=Bh(n),a=Bh(a)),new Hs(s,{src:i,type:t,pos:o,normal:n,up:a,clippable:!1,collidable:!0,height:l}))})),a&&(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=>this._withBCFComponent(t,e,(e=>e.visible=!1))))):(s.setObjectsVisible(s.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!0)))));const r=e.components.visibility.view_setup_hints;r&&(!1===r.spaces_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcSpace"),!1),void 0!==r.spaces_translucent&&s.setObjectsXRayed(i.metaScene.getObjectIDsByType("IfcSpace"),!0),r.space_boundaries_visible,!1===r.openings_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcOpening"),!0),r.space_boundaries_translucent,void 0!==r.openings_translucent&&s.setObjectsXRayed(i.metaScene.getObjectIDsByType("IfcOpening"),!0))}e.components.selection&&(s.setObjectsSelected(s.selectedObjectIds,!1),e.components.selection.forEach((e=>this._withBCFComponent(t,e,(e=>e.selected=!0))))),e.components.translucency&&(s.setObjectsXRayed(s.xrayedObjectIds,!1),e.components.translucency.forEach((e=>this._withBCFComponent(t,e,(e=>e.xrayed=!0))))),e.components.coloring&&e.components.coloring.forEach((e=>{let i=e.color,s=0,r=!1;8===i.length&&(s=parseInt(i.substring(0,2),16)/256,s<=1&&s>=.95&&(s=1),i=i.substring(2),r=!0);const o=[parseInt(i.substring(0,2),16)/256,parseInt(i.substring(2,4),16)/256,parseInt(i.substring(4,6),16)/256];e.components.map((e=>this._withBCFComponent(t,e,(e=>{e.colorize=o,r&&(e.opacity=s)}))))}))}if(e.perspective_camera||e.orthogonal_camera){let a,A,h,u;if(e.perspective_camera?(a=yh(e.perspective_camera.camera_view_point,gh),A=yh(e.perspective_camera.camera_direction,gh),h=yh(e.perspective_camera.camera_up_vector,gh),r.perspective.fov=e.perspective_camera.field_of_view,u="perspective"):(a=yh(e.orthogonal_camera.camera_view_point,gh),A=yh(e.orthogonal_camera.camera_direction,gh),h=yh(e.orthogonal_camera.camera_up_vector,gh),r.ortho.scale=e.orthogonal_camera.view_to_world_scale,u="ortho"),c.subVec3(a,l),r.yUp&&(a=Bh(a),A=Bh(A),h=Bh(h)),o){const e=s.pick({pickSurface:!0,origin:a,direction:A});A=e?e.worldPos:c.addVec3(a,A,gh)}else A=c.addVec3(a,A,gh);n?(r.eye=a,r.look=A,r.up=h,r.projection=u):i.cameraFlight.flyTo({eye:a,look:A,up:h,duration:t.duration,projection:u})}}_withBCFComponent(e,t,i){const s=this.viewer,r=s.scene;if(t.authoring_tool_id&&t.originating_system===this.originatingSystem){const o=t.authoring_tool_id,n=r.objects[o];if(n)return void i(n);if(e.updateCompositeObjects){if(s.metaScene.metaObjects[o])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(o),i)}}if(t.ifc_guid){const o=t.ifc_guid,n=r.objects[o];if(n)return void i(n);if(e.updateCompositeObjects){if(s.metaScene.metaObjects[o])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(o),i)}Object.keys(r.models).forEach((t=>{const n=c.globalizeObjectId(t,o),a=r.objects[n];if(a)i(a);else if(e.updateCompositeObjects){s.metaScene.metaObjects[n]&&r.withObjects(s.metaScene.getObjectIDsInSubtree(n),i)}}))}}destroy(){super.destroy()}},exports.Bitmap=Hs,exports.ByteType=1010,exports.CameraMemento=$h,exports.CameraPath=class extends D{get type(){return"CameraPath"}constructor(e,t={}){super(e,t),this._frames=[],this._eyeCurve=new Uh(this),this._lookCurve=new Uh(this),this._upCurve=new Uh(this),t.frames&&(this.addFrames(t.frames),this.smoothFrameTimes(1))}get frames(){return this._frames}get eyeCurve(){return this._eyeCurve}get lookCurve(){return this._lookCurve}get upCurve(){return this._upCurve}saveFrame(e){const t=this.scene.camera;this.addFrame(e,t.eye,t.look,t.up)}addFrame(e,t,i,s){const r={t:e,eye:t.slice(0),look:i.slice(0),up:s.slice(0)};this._frames.push(r),this._eyeCurve.points.push(r.eye),this._lookCurve.points.push(r.look),this._upCurve.points.push(r.up)}addFrames(e){let t;for(let i=0,s=e.length;i1?1:e,t.eye=this._eyeCurve.getPoint(e,kh),t.look=this._lookCurve.getPoint(e,kh),t.up=this._upCurve.getPoint(e,kh)}sampleFrame(e,t,i,s){e=e<0?0:e>1?1:e,this._eyeCurve.getPoint(e,t),this._lookCurve.getPoint(e,i),this._upCurve.getPoint(e,s)}smoothFrameTimes(e){if(0===this._frames.length)return;const t=c.vec3();var i=0;this._frames[0].t=0;const s=[];for(let e=1,o=this._frames.length;e{this._parseModel(e,t,i,s),r.processes--}),(e=>{r.processes--,this.error(e),s.fire("error",e)}))}_parseModel(e,t,i,s){if(s.destroyed)return;const r=e.transform?this._transformVertices(e.vertices,e.transform,i.rotateX):e.vertices,o=t.stats||{};o.sourceFormat=e.type||"CityJSON",o.schemaVersion=e.version||"",o.title="",o.author="",o.created="",o.numMetaObjects=0,o.numPropertySets=0,o.numObjects=0,o.numGeometries=0,o.numTriangles=0,o.numVertices=0;const n=!1!==t.loadMetadata,a=n?{id:c.createUUID(),name:"Model",type:"Model"}:null,l=n?{id:"",projectId:"",author:"",createdAt:"",schema:e.version||"",creatingApplication:"",metaObjects:[a],propertySets:[]}:null,A={data:e,vertices:r,sceneModel:s,loadMetadata:n,metadata:l,rootMetaObject:a,nextId:0,stats:o};if(this._parseCityJSON(A),s.finalize(),n){const e=s.id;this.viewer.metaScene.createMetaModel(e,A.metadata,i)}s.scene.once("tick",(()=>{s.destroyed||(s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1))}))}_transformVertices(e,t,i){const s=[],r=t.scale||c.vec3([1,1,1]),o=t.translate||c.vec3([0,0,0]);for(let t=0,n=0;t0))return;const o=[];for(let i=0,s=t.geometry.length;i0){const r=t[s[0]];if(void 0!==r.value)n=e[r.value];else{const t=r.values;if(t){a=[];for(let s=0,r=t.length;s0&&(s.createEntity({id:i,meshIds:o,isObject:!0}),e.stats.numObjects++)}_parseGeometrySurfacesWithOwnMaterials(e,t,i,s){switch(t.type){case"MultiPoint":case"MultiLineString":break;case"MultiSurface":case"CompositeSurface":const r=t.boundaries;this._parseSurfacesWithOwnMaterials(e,i,r,s);break;case"Solid":const o=t.boundaries;for(let t=0;t0&&h.push(A.length);const i=this._extractLocalIndices(e,a[t],u,d);A.push(...i)}if(3===A.length)d.indices.push(A[0]),d.indices.push(A[1]),d.indices.push(A[2]);else if(A.length>3){const e=[];for(let t=0;t0&&n.indices.length>0){const t=""+e.nextId++;r.createMesh({id:t,primitive:"triangles",positions:n.positions,indices:n.indices,color:i&&i.diffuseColor?i.diffuseColor:[.8,.8,.8],opacity:1}),s.push(t),e.stats.numGeometries++,e.stats.numVertices+=n.positions.length/3,e.stats.numTriangles+=n.indices.length/3}}_parseSurfacesWithSharedMaterial(e,t,i,s){const r=e.vertices;for(let o=0;o0&&a.push(n.length);const l=this._extractLocalIndices(e,t[o][r],i,s);n.push(...l)}if(3===n.length)s.indices.push(n[0]),s.indices.push(n[1]),s.indices.push(n[2]);else if(n.length>3){let e=[];for(let t=0;t{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),document.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),e.items&&(this.items=e.items),this._hideOnAction=!1!==e.hideOnAction,this.context=e.context,this.enabled=!1!==e.enabled,this.hide()}on(e,t){let 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{const o=this._getNextId(),n=new i(o);for(let i=0,o=e.length;i0,A=this._getNextId(),h=i.getTitle||(()=>i.title||""),c=i.doAction||i.callback||(()=>{}),u=i.getEnabled||(()=>!0),d=i.getShown||(()=>!0),p=new r(A,h,c,u,d);if(p.parentMenu=n,a.items.push(p),l){const e=t(s);p.subMenu=e,e.parentItem=p}this._itemList.push(p),this._itemMap[p.id]=p}}return this._menuList.push(n),this._menuMap[n.id]=n,n};this._rootMenu=t(e)}_getNextId(){return"ContextMenu_"+this._id+"_"+this._nextId++}_createUI(){const e=t=>{this._createMenuUI(t);const i=t.groups;for(let t=0,s=i.length;t'),i.push("
    "),t)for(let e=0,s=t.length;e'+l+""),r===o-1||e')):(i.push('
  • '+l+"
  • "),r===o-1||e'))}}i.push("
"),i.push("");const s=i.join("");document.body.insertAdjacentHTML("beforeend",s);const r=document.querySelector("."+e.id);e.menuElement=r,r.style["border-radius"]="4px",r.style.display="none",r.style["z-index"]=3e5,r.style.background="white",r.style.border="1px solid black",r.style["box-shadow"]="0 4px 5px 0 gray",r.oncontextmenu=e=>{e.preventDefault()};const o=this;let n=null;if(t)for(let e=0,i=t.length;e{e.preventDefault();const i=t.subMenu;if(!i)return void(n&&(o._hideMenu(n.id),n=null));if(n&&n.id!==i.id&&(o._hideMenu(n.id),n=null),!1===t.enabled)return;const s=t.itemElement,r=i.menuElement,a=s.getBoundingClientRect();r.getBoundingClientRect();a.right+200>window.innerWidth?o._showMenu(i.id,a.left-200,a.top-1):o._showMenu(i.id,a.right-5,a.top-1),n=i})),s||(t.itemElement.addEventListener("click",(e=>{e.preventDefault(),o._context&&!1!==t.enabled&&(t.doAction&&t.doAction(o._context),this._hideOnAction?o.hide():(o._updateItemsTitles(),o._updateItemsEnabledStatus()))})),t.itemElement.addEventListener("mouseup",(e=>{3===e.which&&(e.preventDefault(),o._context&&!1!==t.enabled&&(t.doAction&&t.doAction(o._context),this._hideOnAction?o.hide():(o._updateItemsTitles(),o._updateItemsEnabledStatus())))})),t.itemElement.addEventListener("mouseenter",(e=>{e.preventDefault(),!1!==t.enabled&&t.doHover&&t.doHover(o._context)})))):console.error("ContextMenu item element not found: "+t.id)}}}_updateItemsTitles(){if(this._context)for(let e=0,t=this._itemList.length;e{n.subMenu&&(e=n.itemElement,t=e.getBoundingClientRect(),i=n.subMenu.menuElement,s={visibility:i.style.visibility,display:i.style.display},i.style.display="block",i.style.visibility="hidden",o=n.subMenu.menuElement.getBoundingClientRect().width,i.style.visibility=s.visibility,i.style.display=s.display,r=t.right+o>window.innerWidth,e.setAttribute("data-submenuposition",r?"left":"right"))}))}_showMenu(e,t,i){const s=this._menuMap[e];if(!s)return void console.error("Menu not found: "+e);if(s.shown)return;const r=s.menuElement;r&&(this._showMenuElement(r,t,i),s.shown=!0)}_hideMenu(e){const t=this._menuMap[e];if(!t)return void console.error("Menu not found: "+e);if(!t.shown)return;const i=t.menuElement;i&&(this._hideMenuElement(i),t.shown=!1)}_hideAllMenus(){for(let e=0,t=this._menuList.length;ewindow.innerHeight&&(i=window.innerHeight-s),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=i+"px"}_hideMenuElement(e){e.style.display="none"}},exports.CubicBezierCurve=class extends Lh{constructor(e,t={}){super(e,t),this.v0=t.v0,this.v1=t.v1,this.v2=t.v2,this.v3=t.v3,this.t=t.t}set v0(e){this._v0=e||c.vec3([0,0,0])}get v0(){return this._v0}set v1(e){this._v1=e||c.vec3([0,0,0])}get v1(){return this._v1}set v2(e){this._v2=e||c.vec3([0,0,0])}get v2(){return this._v2}set v3(e){this.fire("v3",this._v3=e||c.vec3([0,0,0]))}get v3(){return this._v3}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=c.vec3();return t[0]=c.b3(e,this._v0[0],this._v1[0],this._v2[0],this._v3[0]),t[1]=c.b3(e,this._v0[1],this._v1[1],this._v2[1],this._v3[1]),t[2]=c.b3(e,this._v0[2],this._v1[2],this._v2[2],this._v3[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,v3:this._v3,t:this._t}}},exports.Curve=Lh,exports.DefaultLoadingManager=TA,exports.DepthFormat=1026,exports.DepthStencilFormat=1027,exports.DirLight=Dt,exports.DistanceMeasurementEditControl=Ih,exports.DistanceMeasurementEditMouseControl=class extends Ih{constructor(e,t){super(e,t,!0,!1)}},exports.DistanceMeasurementEditTouchControl=class extends Ih{constructor(e,t){super(e,t,!1,!0)}},exports.DistanceMeasurementsControl=Eh,exports.DistanceMeasurementsMouseControl=Fh,exports.DistanceMeasurementsPlugin=class extends V{constructor(e,t={}){super("DistanceMeasurements",e),this._pointerLens=t.pointerLens,this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.labelMinAxisLength=t.labelMinAxisLength,this.defaultVisible=!1!==t.defaultVisible,this.defaultOriginVisible=!1!==t.defaultOriginVisible,this.defaultTargetVisible=!1!==t.defaultTargetVisible,this.defaultWireVisible=!1!==t.defaultWireVisible,this.defaultXLabelEnabled=!1!==t.defaultXLabelEnabled,this.defaultYLabelEnabled=!1!==t.defaultYLabelEnabled,this.defaultZLabelEnabled=!1!==t.defaultZLabelEnabled,this.defaultLengthLabelEnabled=!1!==t.defaultLengthLabelEnabled,this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.defaultAxisVisible=!1!==t.defaultAxisVisible,this.defaultXAxisVisible=!1!==t.defaultXAxisVisible,this.defaultYAxisVisible=!1!==t.defaultYAxisVisible,this.defaultZAxisVisible=!1!==t.defaultZAxisVisible,this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.zIndex=t.zIndex||1e4,this.defaultLabelsOnWires=!1!==t.defaultLabelsOnWires,this.useRotationAdjustment=void 0!==t.useRotationAdjustment&&!1!==t.useRotationAdjustment,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,distanceMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get pointerLens(){return this._pointerLens}get control(){return this._defaultControl||(this._defaultControl=new Fh(this,{})),this._defaultControl}get measurements(){return this._measurements}set labelMinAxisLength(e){e<1&&(this.error("labelMinAxisLength must be >= 1; defaulting to 25"),e=25),this._labelMinAxisLength=e||25}get labelMinAxisLength(){return this._labelMinAxisLength}set useRotationAdjustment(e){e=void 0!==e&&Boolean(e),this._useRotationAdjustment=e}get useRotationAdjustment(){return this._useRotationAdjustment}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,i=e.target,s=new Mh(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},target:{entity:i.entity,worldPos:i.worldPos},visible:e.visible,wireVisible:e.wireVisible,axisVisible:!1!==e.axisVisible&&!1!==this.defaultAxisVisible,xAxisVisible:!1!==e.xAxisVisible&&!1!==this.defaultXAxisVisible,yAxisVisible:!1!==e.yAxisVisible&&!1!==this.defaultYAxisVisible,zAxisVisible:!1!==e.zAxisVisible&&!1!==this.defaultZAxisVisible,xLabelEnabled:!1!==e.xLabelEnabled&&!1!==this.defaultXLabelEnabled,yLabelEnabled:!1!==e.yLabelEnabled&&!1!==this.defaultYLabelEnabled,zLabelEnabled:!1!==e.zLabelEnabled&&!1!==this.defaultZLabelEnabled,lengthLabelEnabled:!1!==e.lengthLabelEnabled&&!1!==this.defaultLengthLabelEnabled,labelsVisible:!1!==e.labelsVisible&&!1!==this.defaultLabelsVisible,useRotationAdjustment:this.useRotationAdjustment,originVisible:e.originVisible,targetVisible:e.targetVisible,color:e.color,labelsOnWires:!1!==e.labelsOnWires&&!1!==this.defaultLabelsOnWires,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[s.id]=s,s.clickable=!0,s.on("destroyed",(()=>{delete this._measurements[s.id]})),this.fire("measurementCreated",s),s}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("DistanceMeasurement not found: "+e)}setLabelsShown(e){for(const[t,i]of Object.entries(this.measurements))i.labelShown=e}setAxisVisible(e){for(const[t,i]of Object.entries(this.measurements))i.axisVisible=e;this.defaultAxisVisible=e}getAxisVisible(){return this.defaultAxisVisible}clear(){const e=Object.keys(this._measurements);for(var t=0,i=e.length;t{this.plugin.viewer.cameraControl.active=!1},u=()=>{this.plugin.viewer.cameraControl.active=!0},d=()=>{o&&(clearTimeout(o),o=null),this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),u(),this._touchState=0};i.addEventListener("touchstart",this._onCanvasTouchStart=l=>{const u=l.touches.length;if(1!==u)return void(o&&(clearTimeout(o),o=null));const p=l.touches[0],f=i.getBoundingClientRect(),g=p.clientX-f.left,m=p.clientY-f.top;switch(n.set([g,m]),a.set([g,m]),this._touchState){case 0:if(1!==u&&null!==o)return void d();const i=t.pick({canvasPos:a,snapping:this._snapping,snapToEdge:this._snapping});if(i&&i.snapped)s.set(i.worldPos),this.pointerCircle.start(i.snappedCanvasPos);else{const e=t.pick({canvasPos:a,pickSurface:!0});if(!e||!e.worldPos)return;s.set(e.worldPos),this.pointerCircle.start(e.canvasPos)}o=setTimeout((()=>{1!==u||a[0]>n[0]+r||a[0]n[1]+r||a[1]{if(o=null,1!==u||a[0]>n[0]+r||a[0]n[1]+r||a[1]{this.pointerCircle.stop();const n=r.touches.length;if(1!==n||1!==r.changedTouches.length)return void(o&&(clearTimeout(o),o=null));const l=r.touches[0],h=i.getBoundingClientRect(),u=l.clientX-h.left,d=l.clientY-h.top;if(l.identifier!==A)return;let p,f;switch(a.set([u,d]),this._touchState){case 2:this.pointerLens&&(this.pointerLens.canvasPos=a),p=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),p&&p.snapped?(this.pointerLens&&(this.pointerLens.snappedCanvasPos=p.snappedCanvasPos,this.pointerLens.snapped=!0),s.set(p.worldPos),this._currentDistanceMeasurement?this._currentDistanceMeasurement.origin.worldPos=p.worldPos:(this._currentDistanceMeasurement=e.createMeasurement({id:c.createUUID(),origin:{worldPos:p.worldPos,entity:p.entity},target:{worldPos:p.worldPos,entity:p.entity}}),this._currentDistanceMeasurement.labelsVisible=!1,this._currentDistanceMeasurement.xAxisVisible=!1,this._currentDistanceMeasurement.yAxisVisible=!1,this._currentDistanceMeasurement.zAxisVisible=!1,this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.originVisible=!0,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.clickable=!1),this.distanceMeasurementsPlugin.fire("measurementStart",this._currentDistanceMeasurement)):(f=t.pick({canvasPos:a,pickSurface:!0}),f&&f.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=f.canvasPos,this.pointerLens.snapped=!1),s.set(f.worldPos),this._currentDistanceMeasurement?this._currentDistanceMeasurement.origin.worldPos=f.worldPos:(this._currentDistanceMeasurement=e.createMeasurement({id:c.createUUID(),origin:{worldPos:f.worldPos,entity:f.entity},target:{worldPos:f.worldPos,entity:f.entity}}),this._currentDistanceMeasurement.labelsVisible=!1,this._currentDistanceMeasurement.xAxisVisible=!1,this._currentDistanceMeasurement.yAxisVisible=!1,this._currentDistanceMeasurement.zAxisVisible=!1,this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.originVisible=!0,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.clickable=!1),this.distanceMeasurementsPlugin.fire("measurementStart",this._currentDistanceMeasurement)):this.pointerLens&&(this.pointerLens.cursorPos=null,this.pointerLens.snapped=!1)),this._touchState=2;break;case 5:if(1!==n&&null!==o)return clearTimeout(o),o=null,this.pointerLens&&(this.pointerLens.visible=!1),void(this._touchState=7);this.pointerLens&&(this.pointerLens.canvasPos=a),p=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),p&&p.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=p.snappedCanvasPos,this.pointerLens.snapped=!0),this._currentDistanceMeasurement.target.worldPos=p.worldPos,this._currentDistanceMeasurement.target.entity=p.entity,this._currentDistanceMeasurement.targetVisible=!0,this._currentDistanceMeasurement.wireVisible=!0,this._currentDistanceMeasurement.labelsVisible=!0):(f=t.pick({canvasPos:a,pickSurface:!0}),f&&f.worldPos&&(this.pointerLens&&(this.pointerLens.cursorPos=f.canvasPos,this.pointerLens.snapped=!1),this._currentDistanceMeasurement.target.worldPos=f.worldPos,this._currentDistanceMeasurement.target.entity=f.entity,this._currentDistanceMeasurement.targetVisible=!0,this._currentDistanceMeasurement.wireVisible=!0,this._currentDistanceMeasurement.labelsVisible=!0)),this._touchState=5}}),{passive:!0}),i.addEventListener("touchend",this._onCanvasTouchEnd=s=>{this.pointerCircle.stop();const h=s.changedTouches.length;if(1!==h)return;const d=s.changedTouches[0],p=i.getBoundingClientRect(),f=d.clientX-p.left,g=d.clientY-p.top;if(d.identifier===A)switch(o&&(clearTimeout(o),o=null),l.set([f,g]),this._touchState){case 1:{if(1!==h||f>n[0]+r||fn[1]+r||gn[0]+r||fn[1]+r||g{const t=e.fileData,n=e.sceneModel,a={},l=c.createUUID(),A=c.createUUID(),h=c.createUUID(),u=c.createUUID(),d={metaObjects:[{id:l,name:"Project",type:"Project",parent:null},{id:A,name:"Site",type:"Site",parent:l},{id:h,name:"Building",type:"Building",parent:A},{id:u,name:"BuildingStorey",type:"BuildingStorey",parent:h}],propertySets:[]},p=(e,i)=>{if(a[e])return;const s=t.meshes.find((e=>e.mesh_id===i.mesh_id));n.createGeometry({id:e,primitive:"triangles",positions:s.coordinates,indices:s.indices}),a[e]=!0},f=t.elements;for(let e=0,i=f.length;ee.mesh_id===i.mesh_id));for(let t=0,i=e.length;t{n.destroyed||(n.scene.fire("modelLoaded",n.id),n.fire("loaded",!0,!1))}))};if(e.src){const i=e.src;this.viewer.scene.canvas.spinner.processes++,this._dataSource.getDotBIM(i,(e=>{n({fileData:e,sceneModel:t,nextId:0,error:function(e){}}),this.viewer.scene.canvas.spinner.processes--}),(e=>{this.viewer.scene.canvas.spinner.processes--,this.error(e)}))}else if(e.dotBIM){const i={fileData:e.dotBIM,sceneModel:t,nextId:0,error:function(e){}};n(i)}return t.once("destroyed",(()=>{this.viewer.metaScene.destroyMetaModel(i)})),t}destroy(){super.destroy()}},exports.EdgeMaterial=$t,exports.EmphasisMaterial=Zt,exports.FaceAlignedSectionPlanesPlugin=class extends V{constructor(e,t={}){if(super("FaceAlignedSectionPlanesPlugin",e),this._freeControls=[],this._sectionPlanes=e.scene.sectionPlanes,this._controls={},this._shownControlId=null,this._dragSensitivity=t.dragSensitivity||1,null!==t.overviewCanvasId&&void 0!==t.overviewCanvasId){const e=document.getElementById(t.overviewCanvasId);e?this._overview=new vw(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;bw.set(this.viewer.scene.aabb),c.getAABB3Center(bw,yw),bw[0]+=t[0]-yw[0],bw[1]+=t[1]-yw[1],bw[2]+=t[2]-yw[2],bw[3]+=t[0]-yw[0],bw[4]+=t[1]-yw[1],bw[5]+=t[2]-yw[2],this.viewer.cameraFlight.flyTo({aabb:bw,fitFOV:65})},onClickedNothing:()=>{this.hideControl()}}):this.warn("Can't find overview canvas: '"+t.overviewCanvasId+"' - will create plugin without overview")}null===t.controlElementId||void 0===t.controlElementId?this.error("Parameter expected: controlElementId"):(this._controlElement=document.getElementById(t.controlElementId),this._controlElement||this.warn("Can't find control element: '"+t.controlElementId+"' - will create plugin without control element")),this._onSceneSectionPlaneCreated=e.scene.on("sectionPlaneCreated",(e=>{this._sectionPlaneCreated(e)}))}setDragSensitivity(e){this._dragSensitivity=e||1}getDragSensitivity(){return this._dragSensitivity}setOverviewVisible(e){this._overview&&this._overview.setVisible(e)}getOverviewVisible(){if(this._overview)return this._overview.getVisible()}get sectionPlanes(){return this._sectionPlanes}createSectionPlane(e={}){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);return new ns(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 mw(this);t._setSectionPlane(e),t.setVisible(!1),this._controls[e.id]=t,this._overview&&this._overview.addSectionPlane(e),e.once("destroyed",(()=>{this._sectionPlaneDestroyed(e)}))}flipSectionPlanes(){const e=this.viewer.scene.sectionPlanes;for(let t in e){e[t].flipDir()}}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(let 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){let 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(let t=0,i=e.length;t{i=1e3*this._delayBeforeRestoreSeconds,s||(e.scene._renderer.setColorTextureEnabled(!this._hideColorTexture),e.scene._renderer.setPBREnabled(!this._hidePBR),e.scene._renderer.setSAOEnabled(!this._hideSAO),e.scene._renderer.setTransparentEnabled(!this._hideTransparentObjects),e.scene._renderer.setEdgesEnabled(!this._hideEdges),this._scaleCanvasResolution?e.scene.canvas.resolutionScale=this._scaleCanvasResolutionFactor:e.scene.canvas.resolutionScale=this._defaultScaleCanvasResolutionFactor,s=!0)},o=()=>{e.scene.canvas.resolutionScale=this._defaultScaleCanvasResolutionFactor,e.scene._renderer.setEdgesEnabled(!0),e.scene._renderer.setColorTextureEnabled(!0),e.scene._renderer.setPBREnabled(!0),e.scene._renderer.setSAOEnabled(!0),e.scene._renderer.setTransparentEnabled(!0),s=!1};this._onCanvasBoundary=e.scene.canvas.on("boundary",r),this._onCameraMatrix=e.scene.camera.on("matrix",r),this._onSceneTick=e.scene.on("tick",(e=>{s&&(i-=e.deltaTime,(!this._delayBeforeRestore||i<=0)&&o())}));let n=!1;this._onSceneMouseDown=e.scene.input.on("mousedown",(()=>{n=!0})),this._onSceneMouseUp=e.scene.input.on("mouseup",(()=>{n=!1})),this._onSceneMouseMove=e.scene.input.on("mousemove",(()=>{n&&r()}))}get hideColorTexture(){return this._hideColorTexture}set hideColorTexture(e){this._hideColorTexture=e}get hidePBR(){return this._hidePBR}set hidePBR(e){this._hidePBR=e}get hideSAO(){return this._hideSAO}set hideSAO(e){this._hideSAO=e}get hideEdges(){return this._hideEdges}set hideEdges(e){this._hideEdges=e}get hideTransparentObjects(){return this._hideTransparentObjects}set hideTransparentObjects(e){this._hideTransparentObjects=!1!==e}get scaleCanvasResolution(){return this._scaleCanvasResolution}set scaleCanvasResolution(e){this._scaleCanvasResolution=e}get defaultScaleCanvasResolutionFactor(){return this._defaultScaleCanvasResolutionFactor}set defaultScaleCanvasResolutionFactor(e){this._defaultScaleCanvasResolutionFactor=e||1}get scaleCanvasResolutionFactor(){return this._scaleCanvasResolutionFactor}set scaleCanvasResolutionFactor(e){this._scaleCanvasResolutionFactor=e||.6}get delayBeforeRestore(){return this._delayBeforeRestore}set delayBeforeRestore(e){this._delayBeforeRestore=e}get delayBeforeRestoreSeconds(){return this._delayBeforeRestoreSeconds}set delayBeforeRestoreSeconds(e){this._delayBeforeRestoreSeconds=null!=e?e:.5}send(e,t){}destroy(){this.viewer.scene.camera.off(this._onCameraMatrix),this.viewer.scene.canvas.off(this._onCanvasBoundary),this.viewer.scene.input.off(this._onSceneMouseDown),this.viewer.scene.input.off(this._onSceneMouseUp),this.viewer.scene.input.off(this._onSceneMouseMove),this.viewer.scene.off(this._onSceneTick),super.destroy()}},exports.FloatType=1015,exports.Fresnel=class extends D{get type(){return"Fresnel"}constructor(e,t={}){super(e,t),this._state=new lt({edgeColor:c.vec3([0,0,0]),centerColor:c.vec3([1,1,1]),edgeBias:0,centerBias:1,power:1}),this.edgeColor=t.edgeColor,this.centerColor=t.centerColor,this.edgeBias=t.edgeBias,this.centerBias=t.centerBias,this.power=t.power}set edgeColor(e){this._state.edgeColor.set(e||[0,0,0]),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set centerColor(e){this._state.centerColor.set(e||[1,1,1]),this.glRedraw()}get centerColor(){return this._state.centerColor}set edgeBias(e){this._state.edgeBias=e||0,this.glRedraw()}get edgeBias(){return this._state.edgeBias}set centerBias(e){this._state.centerBias=null!=e?e:1,this.glRedraw()}get centerBias(){return this._state.centerBias}set power(e){this._state.power=null!=e?e:1,this.glRedraw()}get power(){return this._state.power}destroy(){super.destroy(),this._state.destroy()}},exports.Frustum=U,exports.FrustumPlane=L,exports.GIFMediaType=1e4,exports.GLTFDefaultDataSource=Dh,exports.GLTFLoaderPlugin=class extends V{constructor(e,t={}){super("GLTFLoader",e,t),this._sceneModelLoader=new QB(this,t),this.dataSource=t.dataSource,this.objectDefaults=t.objectDefaults}set dataSource(e){this._dataSource=e||new Dh}get dataSource(){return this._dataSource}set objectDefaults(e){this._objectDefaults=e||WB}get objectDefaults(){return this._objectDefaults}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 dh(this.viewer.scene,_.apply(e,{isModel:!0,dtxEnabled:e.dtxEnabled})),i=t.id;if(!e.src&&!e.gltf)return this.error("load() param expected: src or gltf"),t;if(e.metaModelSrc||e.metaModelJSON){const s=s=>{this.viewer.metaScene.createMetaModel(i,s,{}),this.viewer.scene.canvas.spinner.processes--,e.src?this._sceneModelLoader.load(this,e.src,s,e,t):this._sceneModelLoader.parse(this,e.gltf,s,e,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--,s(e)}),(e=>{this.error(`load(): Failed to load model metadata for model '${i} from '${t}' - ${e}`),this.viewer.scene.canvas.spinner.processes--}))}else e.metaModelJSON&&s(e.metaModelJSON)}else e.src?this._sceneModelLoader.load(this,e.src,null,e,t):this._sceneModelLoader.parse(this,e.gltf,null,e,t);return t.once("destroyed",(()=>{this.viewer.metaScene.destroyMetaModel(i)})),t}destroy(){super.destroy()}},exports.HalfFloatType=1016,exports.ImagePlane=class extends D{constructor(e,t={}){super(e,t),this._src=null,this._image=null,this._pos=c.vec3(),this._origin=c.vec3(),this._rtcPos=c.vec3(),this._dir=c.vec3(),this._size=1,this._imageSize=c.vec2(),this._texture=new Ss(this),this._plane=new es(this,{geometry:new Gt(this,Ns({center:[0,0,0],xSize:1,zSize:1,xSegments:10,zSegments:10})),material:new Jt(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0}),clippable:t.clippable}),this._grid=new es(this,{geometry:new Gt(this,Os({size:1,divisions:10})),material:new Jt(this,{diffuse:[0,0,0],ambient:[0,0,0],emissive:[.2,.8,.2]}),position:[0,.001,0],clippable:t.clippable}),this._node=new gs(this,{rotation:[0,0,0],position:[0,0,0],scale:[1,1,1],clippable:!1,children:[this._plane,this._grid]}),this._gridVisible=!1,this.visible=!0,this.gridVisible=t.gridVisible,this.position=t.position,this.rotation=t.rotation,this.dir=t.dir,this.size=t.size,this.collidable=t.collidable,this.clippable=t.clippable,this.pickable=t.pickable,this.opacity=t.opacity,t.image?this.image=t.image:this.src=t.src}set visible(e){this._plane.visible=e,this._grid.visible=this._gridVisible&&e}get visible(){return this._plane.visible}set gridVisible(e){e=!1!==e,this._gridVisible=e,this._grid.visible=this._gridVisible&&this.visible}get gridVisible(){return this._gridVisible}set image(e){this._image=e,this._image&&(this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}get image(){return this._image}set src(e){if(this._src=e,this._src){this._image=null;const e=new Image;e.onload=()=>{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set position(e){this._pos.set(e||[0,0,0]),W(this._pos,this._origin,this._rtcPos),this._node.origin=this._origin,this._node.position=this._rtcPos}get position(){return this._pos}set rotation(e){this._node.rotation=e}get rotation(){return this._node.rotation}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set dir(e){if(this._dir.set(e||[0,0,-1]),e){const t=this.scene.center,i=[-this._dir[0],-this._dir[1],-this._dir[2]];c.subVec3(t,this.position,zh);const s=-c.dotVec3(i,zh);c.normalizeVec3(i),c.mulVec3Scalar(i,s,Wh),c.vec3PairToQuaternion(Kh,e,Xh),this._node.quaternion=Xh}}get dir(){return this._dir}set collidable(e){this._node.collidable=!1!==e}get collidable(){return this._node.collidable}set clippable(e){this._node.clippable=!1!==e}get clippable(){return this._node.clippable}set pickable(e){this._node.pickable=!1!==e}get pickable(){return this._node.pickable}set opacity(e){this._node.opacity=e}get opacity(){return this._node.opacity}destroy(){super.destroy()}_updatePlaneSizeFromImage(){const e=this._size,t=this._imageSize[0],i=this._imageSize[1];if(t>i){const s=i/t;this._node.scale=[e,1,e*s]}else{const s=t/i;this._node.scale=[e*s,1,e]}}},exports.IntType=1013,exports.JPEGMediaType=10001,exports.KTX2TextureTranscoder=NA,exports.LASLoaderPlugin=class extends V{constructor(e,t={}){super("lasLoader",e,t),this.dataSource=t.dataSource,this.skip=t.skip,this.fp64=t.fp64,this.colorDepth=t.colorDepth}get dataSource(){return this._dataSource}set dataSource(e){this._dataSource=e||new GP}get skip(){return this._skip}set skip(e){this._skip=e||1}get fp64(){return this._fp64}set fp64(e){this._fp64=!!e}get colorDepth(){return this._colorDepth}set colorDepth(e){this._colorDepth=e||"auto"}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 dh(this.viewer.scene,_.apply(e,{maxGeometryBatchSize:5e5,isModel:!0}));if(!e.src&&!e.las)return this.error("load() param expected: src or las"),t;const i={las:{skip:this._skip,fp64:this._fp64,colorDepth:this._colorDepth}};if(e.src)this._loadModel(e.src,e,i,t);else{const s=this.viewer.scene.canvas.spinner;s.processes++,this._parseModel(e.las,e,i,t).then((()=>{s.processes--}),(e=>{s.processes--,this.error(e),t.fire("error",e)}))}return t}_loadModel(e,t,i,s){const r=this.viewer.scene.canvas.spinner;r.processes++,this._dataSource.getLAS(t.src,(e=>{this._parseModel(e,t,i,s).then((()=>{r.processes--}),(e=>{r.processes--,this.error(e),s.fire("error",e)}))}),(e=>{r.processes--,this.error(e),s.fire("error",e)}))}_parseModel(e,t,i,s){function r(e){const i=e.value;if(t.rotateX&&i)for(let e=0,t=i.length;e{if(s.destroyed)return void l();const A=t.stats||{};A.sourceFormat="LAS",A.schemaVersion="",A.title="",A.author="",A.created="",A.numMetaObjects=0,A.numPropertySets=0,A.numObjects=0,A.numGeometries=0,A.numTriangles=0,A.numVertices=0;try{const A=XP(e);ry(e,zP,i).then((e=>{const h=e.attributes,u=e.loaderData,d=void 0!==u.pointsFormatId?u.pointsFormatId:-1;if(!h.POSITION)return s.finalize(),void l("No positions found in file");let p,f;switch(d){case 0:p=r(h.POSITION),f=n(h.intensity);break;case 1:if(!h.intensity)return s.finalize(),void l("No positions found in file");p=r(h.POSITION),f=n(h.intensity);break;case 2:case 3:if(!h.intensity)return s.finalize(),void l("No positions found in file");p=r(h.POSITION),f=o(h.COLOR_0,h.intensity)}const g=ZP(p,15e5),m=ZP(f,2e6),_=[];for(let e=0,t=g.length;e{s.destroyed||(s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1))})),a()}))}catch(e){s.finalize(),l(e)}}))}},exports.LambertMaterial=ms,exports.LightMap=class extends qh{get type(){return"LightMap"}constructor(e,t={}){super(e,t),this.scene._lightMapCreated(this)}destroy(){super.destroy(),this.scene._lightMapDestroyed(this)}},exports.LineSet=fh,exports.LinearEncoding=3e3,exports.LinearFilter=1006,exports.LinearMipMapLinearFilter=1008,exports.LinearMipMapNearestFilter=1007,exports.LinearMipmapLinearFilter=1008,exports.LinearMipmapNearestFilter=1007,exports.Loader=RA,exports.LoadingManager=SA,exports.LocaleService=Sh,exports.LuminanceAlphaFormat=1025,exports.LuminanceFormat=1024,exports.Map=e,exports.Marker=Ae,exports.MarqueePicker=N,exports.MarqueePickerMouseControl=class extends D{constructor(e){super(e.marqueePicker,e);const t=e.marqueePicker,i=t.viewer.scene.canvas.canvas;let s,r,o,n,a,l,A,h=!1,c=!1,u=!1;i.addEventListener("mousedown",(e=>{this.getActive()&&0===e.button&&(A=setTimeout((function(){const o=t.viewer.scene.input;o.keyDown[o.KEY_CTRL]||t.clear(),s=e.pageX,r=e.pageY,a=e.offsetX,t.setMarqueeCorner1([s,r]),h=!0,t.viewer.cameraControl.pointerEnabled=!1,t.setMarqueeVisible(!0),i.style.cursor="crosshair"}),400),c=!0)})),i.addEventListener("mouseup",(e=>{if(!this.getActive())return;if(!h&&!u)return;if(0!==e.button)return;clearTimeout(A),o=e.pageX,n=e.pageY;const i=Math.abs(o-s),a=Math.abs(n-r);h=!1,t.viewer.cameraControl.pointerEnabled=!0,u&&(u=!1),(i>3||a>3)&&t.pick()})),document.addEventListener("mouseup",(e=>{this.getActive()&&0===e.button&&(clearTimeout(A),h&&(t.setMarqueeVisible(!1),h=!1,c=!1,u=!0,t.viewer.cameraControl.pointerEnabled=!0))}),!0),i.addEventListener("mousemove",(e=>{this.getActive()&&0===e.button&&c&&(clearTimeout(A),h&&(o=e.pageX,n=e.pageY,l=e.offsetX,t.setMarqueeVisible(!0),t.setMarqueeCorner2([o,n]),t.setPickMode(a{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="ortho"===e||"perspective"===e?e:"perspective")}));var o=-1;function n(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 a,l,A=null,h=null,u=!1,d=!1,p=.5;s._navCubeCanvas.addEventListener("mouseenter",s._onMouseEnter=function(e){d=!0}),s._navCubeCanvas.addEventListener("mouseleave",s._onMouseLeave=function(e){d=!1}),s._navCubeCanvas.addEventListener("mousedown",s._onMouseDown=function(e){if(1===e.which){A=e.x,h=e.y,a=e.clientX,l=e.clientY;var t=n(e),s=i.pick({canvasPos:t});u=!!s}}),document.addEventListener("mouseup",s._onMouseUp=function(e){if(1===e.which&&(u=!1,null!==A)){var t=n(e),a=i.pick({canvasPos:t,pickSurface:!0});if(a&&a.uv){var l=s._cubeTextureCanvas.getArea(a.uv);if(l>=0&&(document.body.style.cursor="pointer",o>=0&&(s._cubeTextureCanvas.setAreaHighlighted(o,!1),s._repaint(),o=-1),l>=0)){if(s._cubeTextureCanvas.setAreaHighlighted(l,!0),o=l,s._repaint(),e.xA+3||e.yh+3)return;var c=s._cubeTextureCanvas.getAreaDir(l);if(c){var d=s._cubeTextureCanvas.getAreaUp(l);s._isProjectNorth&&s._projectNorthOffsetAngle&&(c=r(1,c,XB),d=r(1,d,JB)),f(c,d,(function(){o>=0&&(s._cubeTextureCanvas.setAreaHighlighted(o,!1),s._repaint(),o=-1),document.body.style.cursor="pointer",o>=0&&(s._cubeTextureCanvas.setAreaHighlighted(o,!1),s._repaint(),o=-1),l>=0&&(s._cubeTextureCanvas.setAreaHighlighted(l,!1),o=-1,s._repaint())}))}}}}}),document.addEventListener("mousemove",s._onMouseMove=function(t){if(o>=0&&(s._cubeTextureCanvas.setAreaHighlighted(o,!1),s._repaint(),o=-1),1!==t.buttons||u){if(u){var r=t.clientX,A=t.clientY;return document.body.style.cursor="move",void function(t,i){var s=(t-a)*-p,r=(i-l)*-p;e.camera.orbitYaw(s),e.camera.orbitPitch(-r),a=t,l=i}(r,A)}if(d){var h=n(t),c=i.pick({canvasPos:h,pickSurface:!0});if(c){if(c.uv){document.body.style.cursor="pointer";var f=s._cubeTextureCanvas.getArea(c.uv);if(f===o)return;o>=0&&s._cubeTextureCanvas.setAreaHighlighted(o,!1),f>=0&&(s._cubeTextureCanvas.setAreaHighlighted(f,!0),s._repaint(),o=f)}}else document.body.style.cursor="default",o>=0&&(s._cubeTextureCanvas.setAreaHighlighted(o,!1),s._repaint(),o=-1)}}});var f=function(){var t=c.vec3();return function(i,r,o){var n=s._fitVisible?e.scene.getAABB(e.scene.visibleObjectIds):e.scene.aabb,a=c.getAABB3Diag(n);c.getAABB3Center(n,t);var l=Math.abs(a/Math.tan(s._cameraFitFOV*c.DEGTORAD));e.cameraControl.pivotPos=t,s._cameraFly?e.cameraFlight.flyTo({look:t,eye:[t[0]-l*i[0],t[1]-l*i[1],t[2]-l*i[2]],up:r||[0,1,0],orthoScale:1.1*a,fitFOV:s._cameraFitFOV,duration:s._cameraFlyDuration},o):e.cameraFlight.jumpTo({look:t,eye:[t[0]-l*i[0],t[1]-l*i[1],t[2]-l*i[2]],up:r||[0,1,0],orthoScale:1.1*a,fitFOV:s._cameraFitFOV},o)}}();this._onUpdated=e.localeService.on("updated",(()=>{this._cubeTextureCanvas.clear(),this._repaint()})),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){if("language"===e)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&&(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}setIsProjectNorth(e=!1){this._isProjectNorth=e}getIsProjectNorth(){return this._isProjectNorth}setProjectNorthOffsetAngle(e){this._projectNorthOffsetAngle=e}getProjectNorthOffsetAngle(){return this._projectNorthOffsetAngle}destroy(){this._navCubeCanvas&&(this.viewer.localeService.off(this._onUpdated),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()}},exports.NearestFilter=1003,exports.NearestMipMapLinearFilter=1005,exports.NearestMipMapNearestFilter=1004,exports.NearestMipmapLinearFilter=1005,exports.NearestMipmapNearestFilter=1004,exports.Node=gs,exports.OBJLoaderPlugin=class extends V{constructor(e,t){super("OBJLoader",e,t),this._sceneGraphLoader=new ZB}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);var t=new gs(this.viewer.scene,_.apply(e,{isModel:!0}));const i=t.id,s=e.src;if(!s)return this.error("load() param expected: src"),t;if(e.metaModelSrc){const r=e.metaModelSrc;_.loadJSON(r,(r=>{this.viewer.metaScene.createMetaModel(i,r),this._sceneGraphLoader.load(t,s,e)}),(e=>{this.error(`load(): Failed to load model modelMetadata for model '${i} from '${r}' - ${e}`)}))}else this._sceneGraphLoader.load(t,s,e);return t.once("destroyed",(()=>{this.viewer.metaScene.destroyMetaModel(i)})),t}destroy(){super.destroy()}},exports.ObjectsKdTree3=class{constructor(e){if(!e)throw"Parameter expected: cfg";if(!e.viewer)throw"Parameter expected: cfg.viewer";this.viewer=e.viewer,this._maxTreeDepth=e.maxTreeDepth||15,this._root=null,this._needsRebuild=!0,this._onModelLoaded=this.viewer.scene.on("modelLoaded",(e=>{this._needsRebuild=!0})),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",(e=>{this._needsRebuild=!0}))}get root(){return this._needsRebuild&&this._rebuild(),this._root}_rebuild(){const e=this.viewer.scene;this._root={aabb:e.getAABB()};for(let t in e.objects){const i=e.objects[t];this._insertEntity(this._root,i,1)}this._needsRebuild=!1}_insertEntity(e,t,i){const s=t.aabb;if(i>=this._maxTreeDepth)return e.entities=e.entities||[],void e.entities.push(t);if(e.left&&c.containsAABB3(e.left.aabb,s))return void this._insertEntity(e.left,t,i+1);if(e.right&&c.containsAABB3(e.right.aabb,s))return void this._insertEntity(e.right,t,i+1);const r=e.aabb;u[0]=r[3]-r[0],u[1]=r[4]-r[1],u[2]=r[5]-r[2];let o=0;if(u[1]>u[o]&&(o=1),u[2]>u[o]&&(o=2),!e.left){const n=r.slice();if(n[o+3]=(r[o]+r[o+3])/2,e.left={aabb:n},c.containsAABB3(n,s))return void this._insertEntity(e.left,t,i+1)}if(!e.right){const n=r.slice();if(n[o]=(r[o]+r[o+3])/2,e.right={aabb:n},c.containsAABB3(n,s))return void this._insertEntity(e.right,t,i+1)}e.entities=e.entities||[],e.entities.push(t)}destroy(){const e=this.viewer.scene;e.off(this._onModelLoaded),e.off(this._onModelUnloaded),this._root=null,this._needsRebuild=!0}},exports.ObjectsMemento=ic,exports.PNGMediaType=10002,exports.Path=class extends Lh{constructor(e,t={}){super(e,t),this._cachedLengths=[],this._dirty=!0,this._curves=[],this._t=0,this._dirtySubs=[],this._destroyedSubs=[],this.curves=t.curves||[],this.t=t.t}addCurve(e){this._curves.push(e),this._dirty=!0}set curves(e){var t,i,s;for(e=e||[],i=0,s=this._curves.length;i1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}get length(){var e=this._getCurveLengths();return e[e.length-1]}getPoint(e){for(var t,i=e*this.length,s=this._getCurveLengths(),r=0;r=i){var o=1-(s[r]-i)/(t=this._curves[r]).length;return t.getPointAt(o)}r++}return null}_getCurveLengths(){if(!this._dirty)return this._cachedLengths;var e,t=[],i=0,s=this._curves.length;for(e=0;e{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=s.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=r.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new lt({type:"point",pos:c.vec3([1,1,1]),color:c.vec3([.7,.7,.8]),intensity:1,attenuation:[0,0,0],space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(i._shadowViewMatrixDirty){i._shadowViewMatrix||(i._shadowViewMatrix=c.identityMat4());const e=i._state.pos,t=s.look,r=s.up;c.lookAtMat4v(e,t,r,i._shadowViewMatrix),i._shadowViewMatrixDirty=!1}return i._shadowViewMatrix},getShadowProjMatrix:()=>{if(i._shadowProjMatrixDirty){i._shadowProjMatrix||(i._shadowProjMatrix=c.identityMat4());const e=i.scene.canvas.canvas;c.perspectiveMat4(Math.PI/180*70,e.clientWidth/e.clientHeight,.1,500,i._shadowProjMatrix),i._shadowProjMatrixDirty=!1}return i._shadowProjMatrix},getShadowRenderBuf:()=>(i._shadowRenderBuf||(i._shadowRenderBuf=new it(i.scene.canvas.canvas,i.scene.canvas.gl,{size:[1024,1024]})),i._shadowRenderBuf)}),this.pos=t.pos,this.color=t.color,this.intensity=t.intensity,this.constantAttenuation=t.constantAttenuation,this.linearAttenuation=t.linearAttenuation,this.quadraticAttenuation=t.quadraticAttenuation,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set pos(e){this._state.pos.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get pos(){return this._state.pos}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set constantAttenuation(e){this._state.attenuation[0]=e||0,this.glRedraw()}get constantAttenuation(){return this._state.attenuation[0]}set linearAttenuation(e){this._state.attenuation[1]=e||0,this.glRedraw()}get linearAttenuation(){return this._state.attenuation[1]}set quadraticAttenuation(e){this._state.attenuation[2]=e||0,this.glRedraw()}get quadraticAttenuation(){return this._state.attenuation[2]}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}},exports.PointerCircle=Q,exports.PointerLens=class{constructor(e,t={}){this.viewer=e,this.scene=this.viewer.scene,this._lensCursorDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._lensCursorDiv,this.viewer.scene.canvas.canvas),this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red",this._lensCursorDiv.style.borderRadius="20px",this._lensCursorDiv.style.width="10px",this._lensCursorDiv.style.height="10px",this._lensCursorDiv.style.margin="-200px -200px",this._lensCursorDiv.style.zIndex="100000",this._lensCursorDiv.style.position="absolute",this._lensCursorDiv.style.pointerEvents="none",this._lensContainer=document.createElement("div"),this._lensContainerId=t.containerId||"xeokit-lens",this._lensContainer.setAttribute("id",this._lensContainerId),this._lensContainer.style.border="1px solid black",this._lensContainer.style.background="white",this._lensContainer.style.borderRadius="50%",this._lensContainer.style.width="300px",this._lensContainer.style.height="300px",this._lensContainer.style.zIndex="15000",this._lensContainer.style.position="absolute",this._lensContainer.style.pointerEvents="none",this._lensContainer.style.visibility="hidden",this._lensCanvas=document.createElement("canvas"),this._lensCanvas.id=`${this._lensContainerId}-canvas`,this._lensCanvas.style.borderRadius="50%",this._lensCanvas.style.width="300px",this._lensCanvas.style.height="300px",this._lensCanvas.style.zIndex="15000",this._lensCanvas.style.pointerEvents="none",document.body.appendChild(this._lensContainer),this._lensContainer.appendChild(this._lensCanvas),this._lensCanvasContext=this._lensCanvas.getContext("2d"),this._canvasElement=this.viewer.scene.canvas.canvas,this._canvasPos=null,this._snappedCanvasPos=null,this._lensPosToggle=t.lensPosToggle||!0,this._lensPosToggleAmount=t.lensPosToggleAmount||85,this._lensPosMarginLeft=t.lensPosMarginLeft||85,this._lensPosMarginTop=t.lensPosMarginTop||25,this._lensContainer.style.marginTop=`${this._lensPosMarginTop}px`,this._lensContainer.style.marginLeft=`${this._lensPosMarginLeft}px`,this._zoomLevel=t.zoomLevel||2,this._active=!1!==t.active,this._visible=!1,this._snapped=!1,this._onViewerRendering=this.viewer.scene.on("rendering",(()=>{this._active&&this._visible&&this.update()}))}update(){if(!this._active||!this._visible)return;if(!this._canvasPos)return;const e=this._lensContainer.getBoundingClientRect(),t=this._canvasElement.getBoundingClientRect(),i=this._canvasPos[0]e.left&&this._canvasPos[1]e.top;this._lensContainer.style.marginLeft=`${this._lensPosMarginLeft}px`,i&&(this._lensPosToggle?this._lensContainer.style.marginTop=t.bottom-t.top-this._lensCanvas.height-this._lensPosToggleAmount+"px":this._lensContainer.style.marginTop=`${this._lensPosMarginTop}px`,this._lensPosToggle=!this._lensPosToggle),this._lensCanvasContext.clearRect(0,0,this._lensCanvas.width,this._lensCanvas.height);const s=Math.max(this._lensCanvas.width,this._lensCanvas.height)/this._zoomLevel;this._lensCanvasContext.drawImage(this._canvasElement,this._canvasPos[0]-s/2,this._canvasPos[1]-s/2,s,s,0,0,this._lensCanvas.width,this._lensCanvas.height);const r=[(e.left+e.right)/2-t.left,(e.top+e.bottom)/2-t.top];if(this._snappedCanvasPos){const e=this._snappedCanvasPos[0]-this._canvasPos[0],t=this._snappedCanvasPos[1]-this._canvasPos[1];this._lensCursorDiv.style.marginLeft=r[0]+e*this._zoomLevel-10+"px",this._lensCursorDiv.style.marginTop=r[1]+t*this._zoomLevel-10+"px"}else this._lensCursorDiv.style.marginLeft=r[0]-10+"px",this._lensCursorDiv.style.marginTop=r[1]-10+"px"}set zoomFactor(e){this._zoomFactor=e,this.update()}get zoomFactor(){return this._zoomFactor}set canvasPos(e){this._canvasPos=e,this.update()}get canvasPos(){return this._canvasPos}set snappedCanvasPos(e){this._snappedCanvasPos=e,this.update()}get snappedCanvasPos(){return this._snappedCanvasPos}set snapped(e){this._snapped=e,e?(this._lensCursorDiv.style.background="greenyellow",this._lensCursorDiv.style.border="2px solid green"):(this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red")}get snapped(){return this._snapped}set active(e){this._active=e,this._lensContainer.style.visibility=e&&this._visible?"visible":"hidden",e&&this._visible||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}get active(){return this._active}set visible(e){this._visible=e,this._lensContainer.style.visibility=e&&this._active?"visible":"hidden",e&&this._active||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}get visible(){return this._visible}destroy(){this._destroyed||(this.viewer.scene.off(this._onViewerRendering),this._lensContainer.removeChild(this._lensCanvas),document.body.removeChild(this._lensContainer),this._destroyed=!0)}},exports.QuadraticBezierCurve=class extends Lh{constructor(e,t={}){super(e,t),this.v0=t.v0,this.v1=t.v1,this.v2=t.v2,this.t=t.t}set v0(e){this._v0=e||c.vec3([0,0,0])}get v0(){return this._v0}set v1(e){this._v1=e||c.vec3([0,0,0])}get v1(){return this._v1}set v2(e){this._v2=e||c.vec3([0,0,0])}get v2(){return this._v2}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=c.vec3();return t[0]=c.b2(e,this._v0[0],this._v1[0],this._v2[0]),t[1]=c.b2(e,this._v0[1],this._v1[1],this._v2[1]),t[2]=c.b2(e,this._v0[2],this._v1[2],this._v2[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,t:this._t}}},exports.Queue=d,exports.RGBAFormat=1023,exports.RGBAIntegerFormat=1033,exports.RGBA_ASTC_10x10_Format=37819,exports.RGBA_ASTC_10x5_Format=37816,exports.RGBA_ASTC_10x6_Format=37817,exports.RGBA_ASTC_10x8_Format=37818,exports.RGBA_ASTC_12x10_Format=37820,exports.RGBA_ASTC_12x12_Format=37821,exports.RGBA_ASTC_4x4_Format=37808,exports.RGBA_ASTC_5x4_Format=37809,exports.RGBA_ASTC_5x5_Format=37810,exports.RGBA_ASTC_6x5_Format=37811,exports.RGBA_ASTC_6x6_Format=37812,exports.RGBA_ASTC_8x5_Format=37813,exports.RGBA_ASTC_8x6_Format=37814,exports.RGBA_ASTC_8x8_Format=37815,exports.RGBA_BPTC_Format=36492,exports.RGBA_ETC2_EAC_Format=37496,exports.RGBA_PVRTC_2BPPV1_Format=35843,exports.RGBA_PVRTC_4BPPV1_Format=35842,exports.RGBA_S3TC_DXT1_Format=33777,exports.RGBA_S3TC_DXT3_Format=33778,exports.RGBA_S3TC_DXT5_Format=33779,exports.RGBFormat=1022,exports.RGB_ETC1_Format=36196,exports.RGB_ETC2_Format=37492,exports.RGB_PVRTC_2BPPV1_Format=35841,exports.RGB_PVRTC_4BPPV1_Format=35840,exports.RGB_S3TC_DXT1_Format=33776,exports.RGFormat=1030,exports.RGIntegerFormat=1031,exports.ReadableGeometry=Gt,exports.RedFormat=1028,exports.RedIntegerFormat=1029,exports.ReflectionMap=class extends qh{get type(){return"ReflectionMap"}constructor(e,t={}){super(e,t),this.scene._lightsState.addReflectionMap(this._state),this.scene._reflectionMapCreated(this)}destroy(){super.destroy(),this.scene._reflectionMapDestroyed(this)}},exports.RepeatWrapping=1e3,exports.STLDefaultDataSource=xw,exports.STLLoaderPlugin=class extends V{constructor(e,t={}){super("STLLoader",e,t),this._sceneGraphLoader=new ww,this.dataSource=t.dataSource}set dataSource(e){this._dataSource=e||new xw}get dataSource(){return this._dataSource}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 gs(this.viewer.scene,_.apply(e,{isModel:!0})),i=e.src,s=e.stl;return i||s?(i?this._sceneGraphLoader.load(this,t,i,e):this._sceneGraphLoader.parse(this,t,s,e),t):(this.error("load() param expected: either 'src' or 'stl'"),t)}},exports.SceneModel=dh,exports.SceneModelMesh=nr,exports.SceneModelTransform=rh,exports.SectionPlane=ns,exports.SectionPlanesPlugin=class extends V{constructor(e,t={}){if(super("SectionPlanes",e),this._freeControls=[],this._sectionPlanes=e.scene.sectionPlanes,this._controls={},this._shownControlId=null,null!==t.overviewCanvasId&&void 0!==t.overviewCanvasId){const e=document.getElementById(t.overviewCanvasId);e?this._overview=new lw(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;Aw.set(this.viewer.scene.aabb),c.getAABB3Center(Aw,hw),Aw[0]+=t[0]-hw[0],Aw[1]+=t[1]-hw[1],Aw[2]+=t[2]-hw[2],Aw[3]+=t[0]-hw[0],Aw[4]+=t[1]-hw[1],Aw[5]+=t[2]-hw[2],this.viewer.cameraFlight.flyTo({aabb:Aw,fitFOV:65})},onClickedNothing:()=>{this.hideControl()}}):this.warn("Can't find overview canvas: '"+t.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={}){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);return new ns(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 nw(this);t._setSectionPlane(e),t.setVisible(!1),this._controls[e.id]=t,this._overview&&this._overview.addSectionPlane(e),e.once("destroyed",(()=>{this._sectionPlaneDestroyed(e)}))}flipSectionPlanes(){const e=this.viewer.scene.sectionPlanes;for(let t in e){e[t].flipDir()}}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{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set collidable(e){this._mesh.collidable=!1!==e}get collidable(){return this._mesh.collidable}set clippable(e){this._mesh.clippable=!1!==e}get clippable(){return this._mesh.clippable}set pickable(e){this._mesh.pickable=!1!==e}get pickable(){return this._mesh.pickable}set opacity(e){this._mesh.opacity=e}get opacity(){return this._mesh.opacity}_updatePlaneSizeFromImage(){const e=.5*this._size,t=this._imageSize[0],i=this._imageSize[1],s=i/t;this._geometry.positions=t>i?[e,e*s,0,-e,e*s,0,-e,-e*s,0,e,-e*s,0]:[e/s,e,0,-e/s,e,0,-e/s,-e,0,e/s,-e,0]}},exports.StoreyViewsPlugin=class extends V{constructor(e,t={}){super("StoreyViews",e),this._objectsMemento=new ic,this._cameraMemento=new $h,this.storeys={},this.modelStoreys={},this._fitStoreyMaps=!!t.fitStoreyMaps,this._onModelLoaded=this.viewer.scene.on("modelLoaded",(e=>{this._registerModelStoreys(e),this.fire("storeys",this.storeys)}))}_registerModelStoreys(e){const t=this.viewer,i=t.scene,s=t.metaScene,r=s.metaModels[e],o=i.models[e];if(!r||!r.rootMetaObjects)return;const n=r.rootMetaObjects;for(let t=0,r=n.length;t.5?a.length:0,h=new cw(this,o.aabb,l,e,n,A);h._onModelDestroyed=o.once("destroyed",(()=>{this._deregisterModelStoreys(e),this.fire("storeys",this.storeys)})),this.storeys[n]=h,this.modelStoreys[e]||(this.modelStoreys[e]={}),this.modelStoreys[e][n]=h}}}_deregisterModelStoreys(e){const t=this.modelStoreys[e];if(t){const i=this.viewer.scene;for(let e in t)if(t.hasOwnProperty(e)){const s=t[e],r=i.models[s.modelId];r&&r.off(s._onModelDestroyed),delete this.storeys[e]}delete this.modelStoreys[e]}}get fitStoreyMaps(){return this._fitStoreyMaps}gotoStoreyCamera(e,t={}){const i=this.storeys[e];if(!i)return this.error("IfcBuildingStorey not found with this ID: "+e),void(t.done&&t.done());const s=this.viewer,r=s.scene.camera,o=i.storeyAABB;if(o[3]{t.done()})):(s.cameraFlight.jumpTo(_.apply(t,{eye:h,look:n,up:u,orthoScale:A})),s.camera.ortho.scale=A)}showStoreyObjects(e,t={}){if(!this.storeys[e])return void this.error("IfcBuildingStorey not found with this ID: "+e);const i=this.viewer,s=i.scene;i.metaScene.metaObjects[e]&&(t.hideOthers&&s.setObjectsVisible(i.scene.visibleObjectIds,!1),this.withStoreyObjects(e,((e,t)=>{e&&(e.visible=!0)})))}withStoreyObjects(e,t){const i=this.viewer,s=i.scene,r=i.metaScene,o=r.metaObjects[e];if(!o)return;const n=o.getObjectIDsInSubtree();for(var a=0,l=n.length;athis.storeys[i[1]].storeyAABB[4]?i[1]:null}worldPosToStoreyMap(e,t,i){const s=e.storeyId,r=this.storeys[s];if(!r)return this.error("IfcBuildingStorey not found with this ID: "+s),!1;const o=this._fitStoreyMaps?r.storeyAABB:r.modelAABB,n=o[0],a=o[1],l=o[2],A=o[3]-n,h=o[4]-a,c=o[5]-l,u=this.viewer.camera.worldUp,d=u[0]>u[1]&&u[0]>u[2],p=!d&&u[1]>u[0]&&u[1]>u[2];!d&&!p&&u[2]>u[0]&&(u[2],u[1]);const f=e.width/A,g=p?e.height/c:e.height/h;return i[0]=Math.floor(e.width-(t[0]-n)*f),i[1]=Math.floor(e.height-(t[2]-l)*g),i[0]>=0&&i[0]=0&&i[1]<=e.height}worldDirToStoreyMap(e,t,i){const s=this.viewer.camera,r=s.eye,o=s.look,n=c.subVec3(o,r,dw),a=s.worldUp,l=a[0]>a[1]&&a[0]>a[2],A=!l&&a[1]>a[0]&&a[1]>a[2];!l&&!A&&a[2]>a[0]&&(a[2],a[1]),l?(i[0]=n[1],i[1]=n[2]):A?(i[0]=n[0],i[1]=n[2]):(i[0]=n[0],i[1]=n[1]),c.normalizeVec2(i)}destroy(){this.viewer.scene.off(this._onModelLoaded),super.destroy()}},exports.Texture=Ss,exports.TextureTranscoder=class{transcode(e,t,i={}){}destroy(){}},exports.TreeViewPlugin=class extends V{constructor(e,t={}){super("TreeViewPlugin",e),this.errors=[],this.valid=!0;const i=t.containerElement||document.getElementById(t.containerElementId);if(i instanceof HTMLElement){for(let e=0;;e++)if(!Sw[e]){Sw[e]=this,this._index=e,this._id=`tree-${e}`;break}if(this._containerElement=i,this._metaModels={},this._autoAddModels=!1!==t.autoAddModels,this._autoExpandDepth=t.autoExpandDepth||0,this._sortNodes=!1!==t.sortNodes,this._viewer=e,this._rootElement=null,this._muteSceneEvents=!1,this._muteTreeEvents=!1,this._rootNodes=[],this._objectNodes={},this._nodeNodes={},this._rootNames={},this._sortNodes=t.sortNodes,this._pruneEmptyNodes=t.pruneEmptyNodes,this._showListItemElementId=null,this._renderService=t.renderService||new Dw,this._showIndeterminate=t.showIndeterminate??!1,!this._renderService)throw new Error("TreeViewPlugin: no render service set");if(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--,this._renderService.setCheckbox(i.nodeId,s);let r=i.parent;for(;r;){r.checked=s,s?r.numVisibleEntities++:r.numVisibleEntities--;const e=this._showIndeterminate&&r.numVisibleEntities>0&&r.numVisibleEntities0,e),r=r.parent}this._muteTreeEvents=!1})),this._onObjectXrayed=this._viewer.scene.on("objectXRayed",(e=>{if(this._muteSceneEvents)return;const t=e.id,i=this._objectNodes[t];if(!i)return;this._muteTreeEvents=!0;const s=e.xrayed;s!==i.xrayed&&(i.xrayed=s,this._renderService.setXRayed(i.nodeId,s),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=this._renderService.isChecked(t),s=this._renderService.getIdFromCheckbox(t),r=this._nodeNodes[s],o=this._viewer.scene.objects;let n=0;this._withNodeTree(r,(e=>{const t=e.objectId,s=o[t],r=0===e.children.length;e.numVisibleEntities=i?e.numEntities:0,r&&i!==e.checked&&n++,e.checked=i,this._renderService.setCheckbox(e.nodeId,i),s&&(s.visible=i)}));let a=r.parent;for(;a;){a.checked=i,i?a.numVisibleEntities+=n:a.numVisibleEntities-=n;const e=this._showIndeterminate&&a.numVisibleEntities>0&&a.numVisibleEntities0,e),a=a.parent}this._muteSceneEvents=!1},this._hierarchy=t.hierarchy||"containment",this._autoExpandDepth=t.autoExpandDepth||0,this._autoAddModels){const e=Object.keys(this.viewer.metaScene.metaModels);for(let t=0,i=e.length;t{this.viewer.metaScene.metaModels[e]&&this.addModel(e)}))}this.hierarchy=t.hierarchy}else this.error("Mandatory config expected: valid containerElementId or 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&&(this._hierarchy=e,this._createNodes())}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._metaModels[e]?this.warn("Model already added: "+e):(this._metaModels[e]=s,t&&t.rootName&&(this._rootNames[e]=t.rootName),i.on("destroyed",(()=>{this.removeModel(i.id)})),this._createNodes()):this.error("MetaModel not found: "+e)}removeModel(e){if(!this._containerElement)return;this._metaModels[e]&&(this._rootNames[e]&&delete this._rootNames[e],delete this._metaModels[e],this._createNodes())}showNode(e){this.unShowNode();const t=this._objectNodes[e];if(!t)return;this.collapse();const i=t.nodeId,s=this._renderService.getSwitchElement(i);if(s)return this._expandSwitchElement(s),s.scrollIntoView(),!0;const r=[];r.unshift(t);let o=t.parent;for(;o;)r.unshift(o),o=o.parent;for(let e=0,t=r.length;e{if(s===e)return;const r=this._renderService.getSwitchElement(i.nodeId);if(r){this._expandSwitchElement(r);const e=i.children;for(var o=0,n=e.length;o0;return this.valid}_validateMetaModelForStoreysHierarchy(e=0,t,i){return!0}_createEnabledNodes(){switch(this._pruneEmptyNodes&&this._findEmptyNodes(),this._hierarchy){case"storeys":this._createStoreysNodes(),0===this._rootNodes.length&&this.error("Failed to build storeys hierarchy");break;case"types":this._createTypesNodes();break;default:this._createContainmentNodes()}this._sortNodes&&this._doSortNodes(),this._synchNodesToEntities(),this._createTrees(),this.expandToDepth(this._autoExpandDepth)}_createDisabledNodes(){const e=this._renderService.createRootNode();this._rootElement=e,this._containerElement.appendChild(e);const t=this._viewer.metaScene.rootMetaObjects;for(let i in t){const s=t[i],r=s.type,o=s.name,n=o&&""!==o&&"Undefined"!==o&&"Default"!==o?o:r,a=this._renderService.createDisabledNodeElement(n);e.appendChild(a)}}_findEmptyNodes(){const e=this._viewer.metaScene.rootMetaObjects;for(let t in e)this._findEmptyNodes2(e[t])}_findEmptyNodes2(e,t=0){const i=this.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{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]s?1:0}_synchNodesToEntities(){const e=Object.keys(this.viewer.metaScene.metaObjects),t=this._viewer.metaScene.metaObjects,i=this._viewer.scene.objects;for(let s=0,r=e.length;sthis._createNodeElement(e))),t=this._renderService.createRootNode();e.forEach((e=>{t.appendChild(e)})),this._containerElement.appendChild(t),this._rootElement=t}_createNodeElement(e){return this._renderService.createNodeElement(e,this._switchExpandHandler,this._checkboxChangeHandler,(t=>{this.fire("contextmenu",{event:t,viewer:this._viewer,treeViewPlugin:this,treeViewNode:e}),t.preventDefault()}),(t=>{this.fire("nodeTitleClicked",{event:t,viewer:this._viewer,treeViewPlugin:this,treeViewNode:e}),t.preventDefault()}))}_expandSwitchElement(e){if(this._renderService.isExpanded(e))return;const t=this._renderService.getId(e),i=this._nodeNodes[t].children.map((e=>this._createNodeElement(e)));this._renderService.addChildren(e,i),this._renderService.expand(e,this._switchExpandHandler,this._switchCollapseHandler)}_collapseNode(e){const t=this._renderService.getSwitchElement(e);this._collapseSwitchElement(t)}_collapseSwitchElement(e){this._renderService.collapse(e,this._switchExpandHandler,this._switchCollapseHandler)}},exports.UnsignedByteType=1009,exports.UnsignedInt248Type=1020,exports.UnsignedIntType=1014,exports.UnsignedShort4444Type=1017,exports.UnsignedShort5551Type=1018,exports.UnsignedShortType=1012,exports.VBOGeometry=Ls,exports.ViewCullPlugin=class extends V{constructor(e,t={}){super("ViewCull",e),this._objectCullStates=function(e){const t=e.id;let i=Rw[t];return i||(i=new Tw(e),Rw[t]=i,e.on("destroyed",(()=>{delete Rw[t],i._destroy()}))),i}(e.scene),this._maxTreeDepth=t.maxTreeDepth||8,this._modelInfos={},this._frustum=new U,this._kdRoot=null,this._frustumDirty=!1,this._kdTreeDirty=!1,this._onViewMatrix=e.scene.camera.on("viewMatrix",(()=>{this._frustumDirty=!0})),this._onProjMatrix=e.scene.camera.on("projMatMatrix",(()=>{this._frustumDirty=!0})),this._onModelLoaded=e.scene.on("modelLoaded",(e=>{const t=this.viewer.scene.models[e];t&&this._addModel(t)})),this._onSceneTick=e.scene.on("tick",(()=>{this._doCull()}))}set enabled(e){this._enabled=e}get enabled(){return this._enabled}_addModel(e){const t={model:e,onDestroyed:e.on("destroyed",(()=>{this._removeModel(e)}))};this._modelInfos[e.id]=t,this._kdTreeDirty=!0}_removeModel(e){const t=this._modelInfos[e.id];t&&(t.model.off(t.onDestroyed),delete this._modelInfos[e.id],this._kdTreeDirty=!0)}_doCull(){const e=this._frustumDirty||this._kdTreeDirty;if(this._frustumDirty&&this._buildFrustum(),this._kdTreeDirty&&this._buildKDTree(),e){const e=this._kdRoot;e&&this._visitKDNode(e)}}_buildFrustum(){const e=this.viewer.scene.camera;k(this._frustum,e.viewMatrix,e.projMatrix),this._frustumDirty=!1}_buildKDTree(){const e=this.viewer.scene;this._kdRoot,this._kdRoot={aabb:e.getAABB(),intersection:U.INTERSECT};for(let e=0,t=this._objectCullStates.numObjects;e=this._maxTreeDepth)return e.objects=e.objects||[],e.objects.push(i),void c.expandAABB3(e.aabb,r);if(e.left&&c.containsAABB3(e.left.aabb,r))return void this._insertEntityIntoKDTree(e.left,t,i,s+1);if(e.right&&c.containsAABB3(e.right.aabb,r))return void this._insertEntityIntoKDTree(e.right,t,i,s+1);const o=e.aabb;Lw[0]=o[3]-o[0],Lw[1]=o[4]-o[1],Lw[2]=o[5]-o[2];let n=0;if(Lw[1]>Lw[n]&&(n=1),Lw[2]>Lw[n]&&(n=2),!e.left){const a=o.slice();if(a[n+3]=(o[n]+o[n+3])/2,e.left={aabb:a,intersection:U.INTERSECT},c.containsAABB3(a,r))return void this._insertEntityIntoKDTree(e.left,t,i,s+1)}if(!e.right){const a=o.slice();if(a[n]=(o[n]+o[n+3])/2,e.right={aabb:a,intersection:U.INTERSECT},c.containsAABB3(a,r))return void this._insertEntityIntoKDTree(e.right,t,i,s+1)}e.objects=e.objects||[],e.objects.push(i),c.expandAABB3(e.aabb,r)}_visitKDNode(e,t=U.INTERSECT){if(t!==U.INTERSECT&&e.intersects===t)return;t===U.INTERSECT&&(t=O(this._frustum,e.aabb),e.intersects=t);const i=t===U.OUTSIDE,s=e.objects;if(s&&s.length>0)for(let e=0,t=s.length;e{this._parseModel(e,t,i,s),r.processes--}),(e=>{r.processes--,this.error(e),s.fire("error",e)}))}_parseModel(e,t,i,s){if(s.destroyed)return;const r=t.stats||{};if(r.sourceFormat="IFC",r.schemaVersion="",r.title="",r.author="",r.created="",r.numMetaObjects=0,r.numPropertySets=0,r.numObjects=0,r.numGeometries=0,r.numTriangles=0,r.numVertices=0,!this._ifcAPI)throw"WebIFCLoaderPlugin has no WebIFC instance configured - please inject via WebIFCLoaderPlugin constructor";const o=new Uint8Array(e),n=this._ifcAPI.OpenModel(o),a=this._ifcAPI.GetModelSchema(n),l=this._ifcAPI.GetLineIDsWithType(n,this._webIFC.IFCPROJECT).get(0),A=!1!==t.loadMetadata,h={modelID:n,modelSchema:a,sceneModel:s,loadMetadata:A,metadata:A?{id:"",projectId:""+l,author:"",createdAt:"",schema:"",creatingApplication:"",metaObjects:[],propertySets:[]}:null,metaObjects:{},options:i,log:function(e){},nextId:0,stats:r};if(A){if(i.includeTypes){h.includeTypes={};for(let e=0,t=i.includeTypes.length;e{s.destroyed||(s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1))}))}_parseMetaObjects(e){const t=this._ifcAPI.GetLineIDsWithType(e.modelID,this._webIFC.IFCPROJECT).get(0),i=this._ifcAPI.GetLine(e.modelID,t);this._parseSpatialChildren(e,i)}_parseSpatialChildren(e,t,i){const s=this._ifcAPI.GetNameFromTypeCode(t.type);if(e.includeTypes&&!e.includeTypes[s])return;if(e.excludeTypes&&e.excludeTypes[s])return;this._createMetaObject(e,t,i);const r=t.GlobalId.value;this._parseRelatedItemsOfType(e,t.expressID,"RelatingObject","RelatedObjects",this._webIFC.IFCRELAGGREGATES,r),this._parseRelatedItemsOfType(e,t.expressID,"RelatingStructure","RelatedElements",this._webIFC.IFCRELCONTAINEDINSPATIALSTRUCTURE,r)}_createMetaObject(e,t,i){const s=t.GlobalId.value,r=this._ifcAPI.GetNameFromTypeCode(t.type),o={id:s,name:t.Name&&""!==t.Name.value?t.Name.value:r,type:r,parent:i};e.metadata.metaObjects.push(o),e.metaObjects[s]=o,e.stats.numMetaObjects++}_parseRelatedItemsOfType(e,t,i,s,r,o){const n=this._ifcAPI.GetLineIDsWithType(e.modelID,r);for(let r=0;re.value)).includes(t)}else h=A.value===t;if(h){const t=l[s];if(Array.isArray(t))t.forEach((t=>{const i=this._ifcAPI.GetLine(e.modelID,t.value);this._parseSpatialChildren(e,i,o)}));else{const i=this._ifcAPI.GetLine(e.modelID,t.value);this._parseSpatialChildren(e,i,o)}}}}_parsePropertySets(e){const t=this._ifcAPI.GetLineIDsWithType(e.modelID,this._webIFC.IFCRELDEFINESBYPROPERTIES);for(let i=0;i0){const o="Default",n=t.Name.value,a=[];for(let e=0,t=s.length;e{const i=t.expressID,s=t.geometries,r=[],o=this._ifcAPI.GetLine(e.modelID,i).GlobalId.value;if(e.loadMetadata){const t=o,i=e.metaObjects[t];if(e.includeTypes&&(!i||!e.includeTypes[i.type]))return;if(e.excludeTypes&&(!i||e.excludeTypes[i.type]))return}const n=c.mat4(),a=c.vec3();for(let t=0,i=s.size();t{o.destroyed||(o.finalize(),a.finalize(),this.viewer.scene.canvas.spinner.processes--,o.once("destroyed",(()=>{this.viewer.metaScene.destroyMetaModel(a.id)})),this.scheduleTask((()=>{o.destroyed||(o.scene.fire("modelLoaded",o.id),o.fire("loaded",!0,!1))})))},A=e=>{this.viewer.scene.canvas.spinner.processes--,this.error(e),o.fire("error",e)};let h=0;const c={getNextId:()=>`${n}.${h++}`};if(e.metaModelSrc||e.metaModelData)if(e.metaModelSrc){const r=e.metaModelSrc;this._dataSource.getMetaModel(r,(r=>{o.destroyed||(a.loadData(r,{includeTypes:i,excludeTypes:s,globalizeObjectIds:t.globalizeObjectIds}),e.src?this._loadModel(e.src,e,t,o,null,c,l,A):(this._parseModel(e.xkt,e,t,o,null,c),l()))}),(e=>{A(`load(): Failed to load model metadata for model '${n} from '${r}' - ${e}`)}))}else e.metaModelData&&(a.loadData(e.metaModelData,{includeTypes:i,excludeTypes:s,globalizeObjectIds:t.globalizeObjectIds}),e.src?this._loadModel(e.src,e,t,o,null,c,l,A):(this._parseModel(e.xkt,e,t,o,null,c),l()));else if(e.src)this._loadModel(e.src,e,t,o,a,c,l,A);else if(e.xkt)this._parseModel(e.xkt,e,t,o,a,c),l();else if(e.manifestSrc||e.manifest){const r=e.manifestSrc?function(e){const t=e.split("/");return t.pop(),t.join("/")+"/"}(e.manifestSrc):"",n=(e,n,l)=>{let A=0;const h=()=>{o.destroyed||A>=e.length?n():this._dataSource.getMetaModel(`${r}${e[A]}`,(e=>{a.loadData(e,{includeTypes:i,excludeTypes:s,globalizeObjectIds:t.globalizeObjectIds}),A++,this.scheduleTask(h,200)}),l)};h()},h=(i,s,n)=>{let a=0;const l=()=>{o.destroyed||a>=i.length?s():this._dataSource.getXKT(`${r}${i[a]}`,(i=>{this._parseModel(i,e,t,o,null,c),o.preFinalize(),a++,this.scheduleTask(l,200)}),n)};l()},u=(i,s,n)=>{let l=0;const A=()=>{o.destroyed||l>=i.length?s():this._dataSource.getXKT(`${r}${i[l]}`,(i=>{this._parseModel(i,e,t,o,a,c),o.preFinalize(),l++,this.scheduleTask(A,200)}),n)};A()};if(e.manifest){const t=e.manifest,i=t.xktFiles;if(!i||0===i.length)return void A("load(): Failed to load model manifest - manifest not valid");const s=t.metaModelFiles;s?n(s,(()=>{h(i,l,A)}),A):u(i,l,A)}else this._dataSource.getManifest(e.manifestSrc,(e=>{if(o.destroyed)return;const t=e.xktFiles;if(!t||0===t.length)return void A("load(): Failed to load model manifest - manifest not valid");const i=e.metaModelFiles;i?n(i,(()=>{h(t,l,A)}),A):u(t,l,A)}),A)}return o}_loadModel(e,t,i,s,r,o,n,a){this._dataSource.getXKT(t.src,(e=>{this._parseModel(e,t,i,s,r,o),s.preFinalize(),n()}),a)}async _parseModel(e,t,i,s,r,o){if(s.destroyed)return;const n=new DataView(e),a=new Uint8Array(e),l=n.getUint32(0,!0),A=EP[l];if(!A)return void this.error("Unsupported .XKT file version: "+l+" - this XKTLoaderPlugin supports versions "+Object.keys(EP));if(A.parseArrayBuffer)return void A.parseArrayBuffer(this.viewer,i,e,s,r,o);const h=n.getUint32(4,!0),c=[];let u=4*(h+2);for(let e=0;eRC(e,t)))}},exports.ZonesPlugin=class extends V{constructor(e,t={}){super("Zones",e),this._pointerLens=t.pointerLens,this._container=t.container||document.body,this._zones=[],this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.zIndex=t.zIndex||1e4,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,zone:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,zone:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,zone:t,event:e})}}createZone(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=new UC(this,{id:e.id,plugin:this,container:this._container,geometry:e.geometry,alpha:e.alpha,color:e.color,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._zones.push(t),t.on("destroyed",(()=>{const e=this._zones.indexOf(t);e>=0&&this._zones.splice(e,1)})),this.fire("zoneCreated",t),t}get zones(){return this._zones}destroy(){super.destroy()}},exports.ZonesPolysurfaceMouseControl=class extends D{constructor(e,t={}){super(e.viewer.scene),this.zonesPlugin=e,this.pointerLens=t.pointerLens,this._action=null}get active(){return!!this._action}activate(e,t,i,s){if("object"==typeof e&&null!==e){const r=e,o=(e,t)=>{if(e in r)return r[e];if(void 0!==t)return t;throw"config missing: "+e};e=o("altitude"),t=o("height"),i=o("color","#008000"),s=o("alpha",.5)}if(this._action)return;const r=this.zonesPlugin,o=r.viewer,n=o.scene,a=this,l=RC(o,(function(t,i){return LC(e,c.vec3([0,1,0]),t,i)}));!function o(){a._action=OC(n,e,t,i,s,a.pointerLens,r,l,(e=>{let t=!0;a._action={deactivate:()=>{t=!1}},a.fire("zoneEnd",e),t&&o()}))}()}deactivate(){this._action&&(this._action.deactivate(),this._action=null)}destroy(){this.deactivate(),super.destroy()}},exports.ZonesPolysurfaceTouchControl=class extends D{constructor(e,t={}){super(e.viewer.scene),this.zonesPlugin=e,this.pointerLens=t.pointerLens,this.pointerCircle=new Q(e.viewer),this._action=null}get active(){return!!this._action}activate(e,t,i,s){if("object"==typeof e&&null!==e){const r=e,o=(e,t)=>{if(e in r)return r[e];if(void 0!==t)return t;throw"config missing: "+e};e=o("altitude"),t=o("height"),i=o("color","#008000"),s=o("alpha",.5)}if(this._action)return;const r=this.zonesPlugin,o=r.viewer,n=o.scene,a=this,l=fe(o,this.pointerCircle,(function(t,i){return LC(e,c.vec3([0,1,0]),t,i)}));!function o(){a._action=OC(n,e,t,i,s,a.pointerLens,r,l,(e=>{let t=!0;a._action={deactivate:()=>{t=!1}},a.fire("zoneEnd",e),t&&o()}))}()}deactivate(){this._action&&(this._action.deactivate(),this._action=null)}destroy(){this.deactivate(),super.destroy()}},exports.ZonesTouchControl=class extends kC{constructor(e,t={}){const i=new Q(e.viewer);super(e,t,((e,t)=>fe(e,i,t))),this.pointerCircle=i}destroy(){this.pointerCircle.destroy(),super.destroy()}},exports.activateDraggableDot=de,exports.activateDraggableDots=pe,exports.buildBoxGeometry=zt,exports.buildBoxLinesGeometry=ks,exports.buildBoxLinesGeometryFromAABB=function(e={}){return ks({id:e.id,center:[(e.aabb[0]+e.aabb[3])/2,(e.aabb[1]+e.aabb[4])/2,(e.aabb[2]+e.aabb[5])/2],xSize:Math.abs(e.aabb[3]-e.aabb[0])/2,ySize:Math.abs(e.aabb[4]-e.aabb[1])/2,zSize:Math.abs(e.aabb[5]-e.aabb[2])/2})},exports.buildCylinderGeometry=is,exports.buildGridGeometry=Os,exports.buildLineGeometry=function(e={}){if(3!==e.startPoint.length)throw"Start point should contain 3 elements in array: x, y and z";if(3!==e.endPoint.length)throw"End point should contain 3 elements in array: x, y and z";let t=[],i=[],s=e.startPoint[0],r=e.startPoint[1],o=e.startPoint[2],n=e.endPoint[0],a=e.endPoint[1],l=e.endPoint[2],A=Math.sqrt((n-s)**2+(a-r)**2+(l-o)**2),h=[(n-s)/A,(a-r)/A,(l-o)/A];if(e.pattern){let c=e.pattern.length,u=!1,d=0,p=0,f=0,g=[s,r,o],m=e.pattern[p];for(i.push(g[0],g[1],g[2]);m<=A-d;){let s=[h[0]*m,h[1]*m,h[2]*m],r=[g[0]+s[0],g[1]+s[1],g[2]+s[2]];i.push(r[0],r[1],r[2]),u||(t.push(f),t.push(f+1)),u=!u,f+=1,g=r,p+=1,p>=c&&(p=0),d+=m,m=e.pattern[p]}e.extendToEnd&&(i.push(n,a,l),t.push(t.length-2),t.push(t.length-1))}else t.push(0),t.push(1),i.push(s,r,o,n,a,l);return _.apply(e,{primitive:"lines",positions:i,indices:t})},exports.buildPlaneGeometry=Ns,exports.buildPolylineGeometry=Vs,exports.buildPolylineGeometryFromCurve=function(e={}){let t=e.curve.getPoints(e.divisions).map((e=>[...e])).flat();return Vs({id:e.id,points:t})},exports.buildSphereGeometry=ss,exports.buildTorusGeometry=Qs,exports.buildVectorTextGeometry=os,exports.createRTCViewMat=z,exports.frustumIntersectsAABB3=O,exports.getKTX2TextureTranscoder=VA,exports.getPlaneRTCPos=X,exports.isTriangleMeshSolid=js,exports.load3DSGeometry=function(e,t={}){return new Promise((function(i,s){t.src||(console.error("load3DSGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,_.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("load3DSGeometry: no data loaded"),r.processes--,s());var o=Us.parse.from3DS(e).edit.objects[0].mesh,n=o.vertices,a=o.uvt,l=o.indices;r.processes--,i(_.apply(t,{primitive:"triangles",positions:n,normals:null,uv:a,indices:l}))}),(function(e){console.error("load3DSGeometry: "+e),r.processes--,s()}))}))},exports.loadOBJGeometry=function(e,t={}){return new Promise((function(i,s){t.src||(console.error("loadOBJGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,_.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("loadOBJGeometry: no data loaded"),r.processes--,s());for(var o=Us.parse.fromOBJ(e),n=Us.edit.unwrap(o.i_verts,o.c_verts,3),a=Us.edit.unwrap(o.i_norms,o.c_norms,3),l=Us.edit.unwrap(o.i_uvt,o.c_uvt,2),A=new Int32Array(o.i_verts.length),h=0;h0?a:null,autoNormals:0===a.length,uv:l,indices:A}))}),(function(e){console.error("loadOBJGeometry: "+e),r.processes--,s()}))}))},exports.math=c,exports.meshSurfaceArea=ir,exports.meshVolume=Xs,exports.rtcToWorldPos=function(e,t,i){return i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i},exports.sRGBEncoding=3001,exports.setFrustum=k,exports.stats=p,exports.touchPointSelector=fe,exports.transformToNode=ce,exports.utils=_,exports.worldToRTCPos=W,exports.worldToRTCPositions=K; +***************************************************************************** */var Kc=function(e,t){return Kc=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},Kc(e,t)};function Xc(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}Kc(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}var Jc=function(){return Jc=Object.assign||function(e){for(var t,i=1,s=arguments.length;i0&&r[r.length-1])||6!==o[0]&&2!==o[0])){n=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]=55296&&r<=56319&&i>10),n%1024+56320)),(r+1===i||s.length>16384)&&(o+=String.fromCharCode.apply(String,s),s.length=0)}return o},su="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ru="undefined"==typeof Uint8Array?[]:new Uint8Array(256),ou=0;ou=0){if(e<55296||e>56319&&e<=65535)return t=((t=this.index[e>>5])<<2)+(31&e),this.data[t];if(e<=65535)return t=((t=this.index[2048+(e-55296>>5)])<<2)+(31&e),this.data[t];if(e>11),t=this.index[t],t+=e>>5&63,t=((t=this.index[t])<<2)+(31&e),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},e}(),cu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",uu="undefined"==typeof Uint8Array?[]:new Uint8Array(256),du=0;du>4,h[l++]=(15&s)<<4|r>>2,h[l++]=(3&r)<<6|63&o;return A}(e),n=Array.isArray(o)?function(e){for(var t=e.length,i=[],s=0;s0;){var n=s[--o];if(Array.isArray(e)?-1!==e.indexOf(n):e===n)for(var a=i;a<=s.length;){var l;if((l=s[++a])===t)return!0;if(l!==pu)break}if(n!==pu)break}return!1},Xu=function(e,t){for(var i=e;i>=0;){var s=t[i];if(s!==pu)return s;i--}return 0},Ju=function(e,t,i,s,r){if(0===i[s])return"×";var o=s-1;if(Array.isArray(r)&&!0===r[o])return"×";var n=o-1,a=o+1,l=t[o],A=n>=0?t[n]:0,h=t[a];if(2===l&&3===h)return"×";if(-1!==Vu.indexOf(l))return"!";if(-1!==Vu.indexOf(h))return"×";if(-1!==Hu.indexOf(h))return"×";if(8===Xu(o,t))return"÷";if(11===Nu.get(e[o]))return"×";if((l===Fu||l===Iu)&&11===Nu.get(e[a]))return"×";if(7===l||7===h)return"×";if(9===l)return"×";if(-1===[pu,fu,gu].indexOf(l)&&9===h)return"×";if(-1!==[mu,_u,vu,Bu,Mu].indexOf(h))return"×";if(Xu(o,t)===xu)return"×";if(Ku(23,xu,o,t))return"×";if(Ku([mu,_u],yu,o,t))return"×";if(Ku(12,12,o,t))return"×";if(l===pu)return"÷";if(23===l||23===h)return"×";if(16===h||16===l)return"÷";if(-1!==[fu,gu,yu].indexOf(h)||14===l)return"×";if(36===A&&-1!==Wu.indexOf(l))return"×";if(l===Mu&&36===h)return"×";if(h===bu)return"×";if(-1!==Qu.indexOf(h)&&l===wu||-1!==Qu.indexOf(l)&&h===wu)return"×";if(l===Cu&&-1!==[Tu,Fu,Iu].indexOf(h)||-1!==[Tu,Fu,Iu].indexOf(l)&&h===Pu)return"×";if(-1!==Qu.indexOf(l)&&-1!==ju.indexOf(h)||-1!==ju.indexOf(l)&&-1!==Qu.indexOf(h))return"×";if(-1!==[Cu,Pu].indexOf(l)&&(h===wu||-1!==[xu,gu].indexOf(h)&&t[a+1]===wu)||-1!==[xu,gu].indexOf(l)&&h===wu||l===wu&&-1!==[wu,Mu,Bu].indexOf(h))return"×";if(-1!==[wu,Mu,Bu,mu,_u].indexOf(h))for(var c=o;c>=0;){if((u=t[c])===wu)return"×";if(-1===[Mu,Bu].indexOf(u))break;c--}if(-1!==[Cu,Pu].indexOf(h))for(c=-1!==[mu,_u].indexOf(l)?n:o;c>=0;){var u;if((u=t[c])===wu)return"×";if(-1===[Mu,Bu].indexOf(u))break;c--}if(Ru===l&&-1!==[Ru,Lu,Du,Su].indexOf(h)||-1!==[Lu,Du].indexOf(l)&&-1!==[Lu,Uu].indexOf(h)||-1!==[Uu,Su].indexOf(l)&&h===Uu)return"×";if(-1!==zu.indexOf(l)&&-1!==[bu,Pu].indexOf(h)||-1!==zu.indexOf(h)&&l===Cu)return"×";if(-1!==Qu.indexOf(l)&&-1!==Qu.indexOf(h))return"×";if(l===Bu&&-1!==Qu.indexOf(h))return"×";if(-1!==Qu.concat(wu).indexOf(l)&&h===xu&&-1===ku.indexOf(e[a])||-1!==Qu.concat(wu).indexOf(h)&&l===_u)return"×";if(41===l&&41===h){for(var d=i[o],p=1;d>0&&41===t[--d];)p++;if(p%2!=0)return"×"}return l===Fu&&h===Iu?"×":"÷"},Yu=function(e,t){t||(t={lineBreak:"normal",wordBreak:"normal"});var i=function(e,t){void 0===t&&(t="strict");var i=[],s=[],r=[];return e.forEach((function(e,o){var n=Nu.get(e);if(n>50?(r.push(!0),n-=50):r.push(!1),-1!==["normal","auto","loose"].indexOf(t)&&-1!==[8208,8211,12316,12448].indexOf(e))return s.push(o),i.push(16);if(4===n||11===n){if(0===o)return s.push(o),i.push(Eu);var a=i[o-1];return-1===Gu.indexOf(a)?(s.push(s[o-1]),i.push(a)):(s.push(o),i.push(Eu))}return s.push(o),31===n?i.push("strict"===t?yu:Tu):n===Ou||29===n?i.push(Eu):43===n?e>=131072&&e<=196605||e>=196608&&e<=262141?i.push(Tu):i.push(Eu):void i.push(n)})),[s,i,r]}(e,t.lineBreak),s=i[0],r=i[1],o=i[2];"break-all"!==t.wordBreak&&"break-word"!==t.wordBreak||(r=r.map((function(e){return-1!==[wu,Eu,Ou].indexOf(e)?Tu:e})));var n="keep-all"===t.wordBreak?o.map((function(t,i){return t&&e[i]>=19968&&e[i]<=40959})):void 0;return[s,r,n]},Zu=function(){function e(e,t,i,s){this.codePoints=e,this.required="!"===t,this.start=i,this.end=s}return e.prototype.slice=function(){return iu.apply(void 0,this.codePoints.slice(this.start,this.end))},e}(),qu=function(e){return e>=48&&e<=57},$u=function(e){return qu(e)||e>=65&&e<=70||e>=97&&e<=102},ed=function(e){return 10===e||9===e||32===e},td=function(e){return function(e){return function(e){return e>=97&&e<=122}(e)||function(e){return e>=65&&e<=90}(e)}(e)||function(e){return e>=128}(e)||95===e},id=function(e){return td(e)||qu(e)||45===e},sd=function(e){return e>=0&&e<=8||11===e||e>=14&&e<=31||127===e},rd=function(e,t){return 92===e&&10!==t},od=function(e,t,i){return 45===e?td(t)||rd(t,i):!!td(e)||!(92!==e||!rd(e,t))},nd=function(e,t,i){return 43===e||45===e?!!qu(t)||46===t&&qu(i):qu(46===e?t:e)},ad=function(e){var t=0,i=1;43!==e[t]&&45!==e[t]||(45===e[t]&&(i=-1),t++);for(var s=[];qu(e[t]);)s.push(e[t++]);var r=s.length?parseInt(iu.apply(void 0,s),10):0;46===e[t]&&t++;for(var o=[];qu(e[t]);)o.push(e[t++]);var n=o.length,a=n?parseInt(iu.apply(void 0,o),10):0;69!==e[t]&&101!==e[t]||t++;var l=1;43!==e[t]&&45!==e[t]||(45===e[t]&&(l=-1),t++);for(var A=[];qu(e[t]);)A.push(e[t++]);var h=A.length?parseInt(iu.apply(void 0,A),10):0;return i*(r+a*Math.pow(10,-n))*Math.pow(10,l*h)},ld={type:2},Ad={type:3},hd={type:4},cd={type:13},ud={type:8},dd={type:21},pd={type:9},fd={type:10},gd={type:11},md={type:12},_d={type:14},vd={type:23},bd={type:1},yd={type:25},xd={type:24},Bd={type:26},wd={type:27},Pd={type:28},Cd={type:29},Md={type:31},Ed={type:32},Fd=function(){function e(){this._value=[]}return e.prototype.write=function(e){this._value=this._value.concat(tu(e))},e.prototype.read=function(){for(var e=[],t=this.consumeToken();t!==Ed;)e.push(t),t=this.consumeToken();return e},e.prototype.consumeToken=function(){var e=this.consumeCodePoint();switch(e){case 34:return this.consumeStringToken(34);case 35:var t=this.peekCodePoint(0),i=this.peekCodePoint(1),s=this.peekCodePoint(2);if(id(t)||rd(i,s)){var r=od(t,i,s)?2:1;return{type:5,value:this.consumeName(),flags:r}}break;case 36:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),cd;break;case 39:return this.consumeStringToken(39);case 40:return ld;case 41:return Ad;case 42:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),_d;break;case 43:if(nd(e,this.peekCodePoint(0),this.peekCodePoint(1)))return this.reconsumeCodePoint(e),this.consumeNumericToken();break;case 44:return hd;case 45:var o=e,n=this.peekCodePoint(0),a=this.peekCodePoint(1);if(nd(o,n,a))return this.reconsumeCodePoint(e),this.consumeNumericToken();if(od(o,n,a))return this.reconsumeCodePoint(e),this.consumeIdentLikeToken();if(45===n&&62===a)return this.consumeCodePoint(),this.consumeCodePoint(),xd;break;case 46:if(nd(e,this.peekCodePoint(0),this.peekCodePoint(1)))return this.reconsumeCodePoint(e),this.consumeNumericToken();break;case 47:if(42===this.peekCodePoint(0))for(this.consumeCodePoint();;){var l=this.consumeCodePoint();if(42===l&&47===(l=this.consumeCodePoint()))return this.consumeToken();if(-1===l)return this.consumeToken()}break;case 58:return Bd;case 59:return wd;case 60:if(33===this.peekCodePoint(0)&&45===this.peekCodePoint(1)&&45===this.peekCodePoint(2))return this.consumeCodePoint(),this.consumeCodePoint(),yd;break;case 64:var A=this.peekCodePoint(0),h=this.peekCodePoint(1),c=this.peekCodePoint(2);if(od(A,h,c))return{type:7,value:this.consumeName()};break;case 91:return Pd;case 92:if(rd(e,this.peekCodePoint(0)))return this.reconsumeCodePoint(e),this.consumeIdentLikeToken();break;case 93:return Cd;case 61:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),ud;break;case 123:return gd;case 125:return md;case 117:case 85:var u=this.peekCodePoint(0),d=this.peekCodePoint(1);return 43!==u||!$u(d)&&63!==d||(this.consumeCodePoint(),this.consumeUnicodeRangeToken()),this.reconsumeCodePoint(e),this.consumeIdentLikeToken();case 124:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),pd;if(124===this.peekCodePoint(0))return this.consumeCodePoint(),dd;break;case 126:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),fd;break;case-1:return Ed}return ed(e)?(this.consumeWhiteSpace(),Md):qu(e)?(this.reconsumeCodePoint(e),this.consumeNumericToken()):td(e)?(this.reconsumeCodePoint(e),this.consumeIdentLikeToken()):{type:6,value:iu(e)}},e.prototype.consumeCodePoint=function(){var e=this._value.shift();return void 0===e?-1:e},e.prototype.reconsumeCodePoint=function(e){this._value.unshift(e)},e.prototype.peekCodePoint=function(e){return e>=this._value.length?-1:this._value[e]},e.prototype.consumeUnicodeRangeToken=function(){for(var e=[],t=this.consumeCodePoint();$u(t)&&e.length<6;)e.push(t),t=this.consumeCodePoint();for(var i=!1;63===t&&e.length<6;)e.push(t),t=this.consumeCodePoint(),i=!0;if(i)return{type:30,start:parseInt(iu.apply(void 0,e.map((function(e){return 63===e?48:e}))),16),end:parseInt(iu.apply(void 0,e.map((function(e){return 63===e?70:e}))),16)};var s=parseInt(iu.apply(void 0,e),16);if(45===this.peekCodePoint(0)&&$u(this.peekCodePoint(1))){this.consumeCodePoint(),t=this.consumeCodePoint();for(var r=[];$u(t)&&r.length<6;)r.push(t),t=this.consumeCodePoint();return{type:30,start:s,end:parseInt(iu.apply(void 0,r),16)}}return{type:30,start:s,end:s}},e.prototype.consumeIdentLikeToken=function(){var e=this.consumeName();return"url"===e.toLowerCase()&&40===this.peekCodePoint(0)?(this.consumeCodePoint(),this.consumeUrlToken()):40===this.peekCodePoint(0)?(this.consumeCodePoint(),{type:19,value:e}):{type:20,value:e}},e.prototype.consumeUrlToken=function(){var e=[];if(this.consumeWhiteSpace(),-1===this.peekCodePoint(0))return{type:22,value:""};var t=this.peekCodePoint(0);if(39===t||34===t){var i=this.consumeStringToken(this.consumeCodePoint());return 0===i.type&&(this.consumeWhiteSpace(),-1===this.peekCodePoint(0)||41===this.peekCodePoint(0))?(this.consumeCodePoint(),{type:22,value:i.value}):(this.consumeBadUrlRemnants(),vd)}for(;;){var s=this.consumeCodePoint();if(-1===s||41===s)return{type:22,value:iu.apply(void 0,e)};if(ed(s))return this.consumeWhiteSpace(),-1===this.peekCodePoint(0)||41===this.peekCodePoint(0)?(this.consumeCodePoint(),{type:22,value:iu.apply(void 0,e)}):(this.consumeBadUrlRemnants(),vd);if(34===s||39===s||40===s||sd(s))return this.consumeBadUrlRemnants(),vd;if(92===s){if(!rd(s,this.peekCodePoint(0)))return this.consumeBadUrlRemnants(),vd;e.push(this.consumeEscapedCodePoint())}else e.push(s)}},e.prototype.consumeWhiteSpace=function(){for(;ed(this.peekCodePoint(0));)this.consumeCodePoint()},e.prototype.consumeBadUrlRemnants=function(){for(;;){var e=this.consumeCodePoint();if(41===e||-1===e)return;rd(e,this.peekCodePoint(0))&&this.consumeEscapedCodePoint()}},e.prototype.consumeStringSlice=function(e){for(var t="";e>0;){var i=Math.min(5e4,e);t+=iu.apply(void 0,this._value.splice(0,i)),e-=i}return this._value.shift(),t},e.prototype.consumeStringToken=function(e){for(var t="",i=0;;){var s=this._value[i];if(-1===s||void 0===s||s===e)return{type:0,value:t+=this.consumeStringSlice(i)};if(10===s)return this._value.splice(0,i),bd;if(92===s){var r=this._value[i+1];-1!==r&&void 0!==r&&(10===r?(t+=this.consumeStringSlice(i),i=-1,this._value.shift()):rd(s,r)&&(t+=this.consumeStringSlice(i),t+=iu(this.consumeEscapedCodePoint()),i=-1))}i++}},e.prototype.consumeNumber=function(){var e=[],t=4,i=this.peekCodePoint(0);for(43!==i&&45!==i||e.push(this.consumeCodePoint());qu(this.peekCodePoint(0));)e.push(this.consumeCodePoint());i=this.peekCodePoint(0);var s=this.peekCodePoint(1);if(46===i&&qu(s))for(e.push(this.consumeCodePoint(),this.consumeCodePoint()),t=8;qu(this.peekCodePoint(0));)e.push(this.consumeCodePoint());i=this.peekCodePoint(0),s=this.peekCodePoint(1);var r=this.peekCodePoint(2);if((69===i||101===i)&&((43===s||45===s)&&qu(r)||qu(s)))for(e.push(this.consumeCodePoint(),this.consumeCodePoint()),t=8;qu(this.peekCodePoint(0));)e.push(this.consumeCodePoint());return[ad(e),t]},e.prototype.consumeNumericToken=function(){var e=this.consumeNumber(),t=e[0],i=e[1],s=this.peekCodePoint(0),r=this.peekCodePoint(1),o=this.peekCodePoint(2);return od(s,r,o)?{type:15,number:t,flags:i,unit:this.consumeName()}:37===s?(this.consumeCodePoint(),{type:16,number:t,flags:i}):{type:17,number:t,flags:i}},e.prototype.consumeEscapedCodePoint=function(){var e=this.consumeCodePoint();if($u(e)){for(var t=iu(e);$u(this.peekCodePoint(0))&&t.length<6;)t+=iu(this.consumeCodePoint());ed(this.peekCodePoint(0))&&this.consumeCodePoint();var i=parseInt(t,16);return 0===i||function(e){return e>=55296&&e<=57343}(i)||i>1114111?65533:i}return-1===e?65533:e},e.prototype.consumeName=function(){for(var e="";;){var t=this.consumeCodePoint();if(id(t))e+=iu(t);else{if(!rd(t,this.peekCodePoint(0)))return this.reconsumeCodePoint(t),e;e+=iu(this.consumeEscapedCodePoint())}}},e}(),Id=function(){function e(e){this._tokens=e}return e.create=function(t){var i=new Fd;return i.write(t),new e(i.read())},e.parseValue=function(t){return e.create(t).parseComponentValue()},e.parseValues=function(t){return e.create(t).parseComponentValues()},e.prototype.parseComponentValue=function(){for(var e=this.consumeToken();31===e.type;)e=this.consumeToken();if(32===e.type)throw new SyntaxError("Error parsing CSS component value, unexpected EOF");this.reconsumeToken(e);var t=this.consumeComponentValue();do{e=this.consumeToken()}while(31===e.type);if(32===e.type)return t;throw new SyntaxError("Error parsing CSS component value, multiple values found when expecting only one")},e.prototype.parseComponentValues=function(){for(var e=[];;){var t=this.consumeComponentValue();if(32===t.type)return e;e.push(t),e.push()}},e.prototype.consumeComponentValue=function(){var e=this.consumeToken();switch(e.type){case 11:case 28:case 2:return this.consumeSimpleBlock(e.type);case 19:return this.consumeFunction(e)}return e},e.prototype.consumeSimpleBlock=function(e){for(var t={type:e,values:[]},i=this.consumeToken();;){if(32===i.type||Nd(i,e))return t;this.reconsumeToken(i),t.values.push(this.consumeComponentValue()),i=this.consumeToken()}},e.prototype.consumeFunction=function(e){for(var t={name:e.value,values:[],type:18};;){var i=this.consumeToken();if(32===i.type||3===i.type)return t;this.reconsumeToken(i),t.values.push(this.consumeComponentValue())}},e.prototype.consumeToken=function(){var e=this._tokens.shift();return void 0===e?Ed:e},e.prototype.reconsumeToken=function(e){this._tokens.unshift(e)},e}(),Dd=function(e){return 15===e.type},Sd=function(e){return 17===e.type},Td=function(e){return 20===e.type},Rd=function(e){return 0===e.type},Ld=function(e,t){return Td(e)&&e.value===t},Ud=function(e){return 31!==e.type},Od=function(e){return 31!==e.type&&4!==e.type},kd=function(e){var t=[],i=[];return e.forEach((function(e){if(4===e.type){if(0===i.length)throw new Error("Error parsing function args, zero tokens for arg");return t.push(i),void(i=[])}31!==e.type&&i.push(e)})),i.length&&t.push(i),t},Nd=function(e,t){return 11===t&&12===e.type||(28===t&&29===e.type||2===t&&3===e.type)},Qd=function(e){return 17===e.type||15===e.type},Vd=function(e){return 16===e.type||Qd(e)},Hd=function(e){return e.length>1?[e[0],e[1]]:[e[0]]},jd={type:17,number:0,flags:4},Gd={type:16,number:50,flags:4},zd={type:16,number:100,flags:4},Wd=function(e,t,i){var s=e[0],r=e[1];return[Kd(s,t),Kd(void 0!==r?r:s,i)]},Kd=function(e,t){if(16===e.type)return e.number/100*t;if(Dd(e))switch(e.unit){case"rem":case"em":return 16*e.number;default:return e.number}return e.number},Xd=function(e,t){if(15===t.type)switch(t.unit){case"deg":return Math.PI*t.number/180;case"grad":return Math.PI/200*t.number;case"rad":return t.number;case"turn":return 2*Math.PI*t.number}throw new Error("Unsupported angle type")},Jd=function(e){return 15===e.type&&("deg"===e.unit||"grad"===e.unit||"rad"===e.unit||"turn"===e.unit)},Yd=function(e){switch(e.filter(Td).map((function(e){return e.value})).join(" ")){case"to bottom right":case"to right bottom":case"left top":case"top left":return[jd,jd];case"to top":case"bottom":return Zd(0);case"to bottom left":case"to left bottom":case"right top":case"top right":return[jd,zd];case"to right":case"left":return Zd(90);case"to top left":case"to left top":case"right bottom":case"bottom right":return[zd,zd];case"to bottom":case"top":return Zd(180);case"to top right":case"to right top":case"left bottom":case"bottom left":return[zd,jd];case"to left":case"right":return Zd(270)}return 0},Zd=function(e){return Math.PI*e/180},qd=function(e,t){if(18===t.type){var i=np[t.name];if(void 0===i)throw new Error('Attempting to parse an unsupported color function "'+t.name+'"');return i(e,t.values)}if(5===t.type){if(3===t.value.length){var s=t.value.substring(0,1),r=t.value.substring(1,2),o=t.value.substring(2,3);return tp(parseInt(s+s,16),parseInt(r+r,16),parseInt(o+o,16),1)}if(4===t.value.length){s=t.value.substring(0,1),r=t.value.substring(1,2),o=t.value.substring(2,3);var n=t.value.substring(3,4);return tp(parseInt(s+s,16),parseInt(r+r,16),parseInt(o+o,16),parseInt(n+n,16)/255)}if(6===t.value.length){s=t.value.substring(0,2),r=t.value.substring(2,4),o=t.value.substring(4,6);return tp(parseInt(s,16),parseInt(r,16),parseInt(o,16),1)}if(8===t.value.length){s=t.value.substring(0,2),r=t.value.substring(2,4),o=t.value.substring(4,6),n=t.value.substring(6,8);return tp(parseInt(s,16),parseInt(r,16),parseInt(o,16),parseInt(n,16)/255)}}if(20===t.type){var a=lp[t.value.toUpperCase()];if(void 0!==a)return a}return lp.TRANSPARENT},$d=function(e){return 0==(255&e)},ep=function(e){var t=255&e,i=255&e>>8,s=255&e>>16,r=255&e>>24;return t<255?"rgba("+r+","+s+","+i+","+t/255+")":"rgb("+r+","+s+","+i+")"},tp=function(e,t,i,s){return(e<<24|t<<16|i<<8|Math.round(255*s)<<0)>>>0},ip=function(e,t){if(17===e.type)return e.number;if(16===e.type){var i=3===t?1:255;return 3===t?e.number/100*i:Math.round(e.number/100*i)}return 0},sp=function(e,t){var i=t.filter(Od);if(3===i.length){var s=i.map(ip),r=s[0],o=s[1],n=s[2];return tp(r,o,n,1)}if(4===i.length){var a=i.map(ip),l=(r=a[0],o=a[1],n=a[2],a[3]);return tp(r,o,n,l)}return 0};function rp(e,t,i){return i<0&&(i+=1),i>=1&&(i-=1),i<1/6?(t-e)*i*6+e:i<.5?t:i<2/3?6*(t-e)*(2/3-i)+e:e}var op=function(e,t){var i=t.filter(Od),s=i[0],r=i[1],o=i[2],n=i[3],a=(17===s.type?Zd(s.number):Xd(e,s))/(2*Math.PI),l=Vd(r)?r.number/100:0,A=Vd(o)?o.number/100:0,h=void 0!==n&&Vd(n)?Kd(n,1):1;if(0===l)return tp(255*A,255*A,255*A,1);var c=A<=.5?A*(l+1):A+l-A*l,u=2*A-c,d=rp(u,c,a+1/3),p=rp(u,c,a),f=rp(u,c,a-1/3);return tp(255*d,255*p,255*f,h)},np={hsl:op,hsla:op,rgb:sp,rgba:sp},ap=function(e,t){return qd(e,Id.create(t).parseComponentValue())},lp={ALICEBLUE:4042850303,ANTIQUEWHITE:4209760255,AQUA:16777215,AQUAMARINE:2147472639,AZURE:4043309055,BEIGE:4126530815,BISQUE:4293182719,BLACK:255,BLANCHEDALMOND:4293643775,BLUE:65535,BLUEVIOLET:2318131967,BROWN:2771004159,BURLYWOOD:3736635391,CADETBLUE:1604231423,CHARTREUSE:2147418367,CHOCOLATE:3530104575,CORAL:4286533887,CORNFLOWERBLUE:1687547391,CORNSILK:4294499583,CRIMSON:3692313855,CYAN:16777215,DARKBLUE:35839,DARKCYAN:9145343,DARKGOLDENROD:3095837695,DARKGRAY:2846468607,DARKGREEN:6553855,DARKGREY:2846468607,DARKKHAKI:3182914559,DARKMAGENTA:2332068863,DARKOLIVEGREEN:1433087999,DARKORANGE:4287365375,DARKORCHID:2570243327,DARKRED:2332033279,DARKSALMON:3918953215,DARKSEAGREEN:2411499519,DARKSLATEBLUE:1211993087,DARKSLATEGRAY:793726975,DARKSLATEGREY:793726975,DARKTURQUOISE:13554175,DARKVIOLET:2483082239,DEEPPINK:4279538687,DEEPSKYBLUE:12582911,DIMGRAY:1768516095,DIMGREY:1768516095,DODGERBLUE:512819199,FIREBRICK:2988581631,FLORALWHITE:4294635775,FORESTGREEN:579543807,FUCHSIA:4278255615,GAINSBORO:3705462015,GHOSTWHITE:4177068031,GOLD:4292280575,GOLDENROD:3668254975,GRAY:2155905279,GREEN:8388863,GREENYELLOW:2919182335,GREY:2155905279,HONEYDEW:4043305215,HOTPINK:4285117695,INDIANRED:3445382399,INDIGO:1258324735,IVORY:4294963455,KHAKI:4041641215,LAVENDER:3873897215,LAVENDERBLUSH:4293981695,LAWNGREEN:2096890111,LEMONCHIFFON:4294626815,LIGHTBLUE:2916673279,LIGHTCORAL:4034953471,LIGHTCYAN:3774873599,LIGHTGOLDENRODYELLOW:4210742015,LIGHTGRAY:3553874943,LIGHTGREEN:2431553791,LIGHTGREY:3553874943,LIGHTPINK:4290167295,LIGHTSALMON:4288707327,LIGHTSEAGREEN:548580095,LIGHTSKYBLUE:2278488831,LIGHTSLATEGRAY:2005441023,LIGHTSLATEGREY:2005441023,LIGHTSTEELBLUE:2965692159,LIGHTYELLOW:4294959359,LIME:16711935,LIMEGREEN:852308735,LINEN:4210091775,MAGENTA:4278255615,MAROON:2147483903,MEDIUMAQUAMARINE:1724754687,MEDIUMBLUE:52735,MEDIUMORCHID:3126187007,MEDIUMPURPLE:2473647103,MEDIUMSEAGREEN:1018393087,MEDIUMSLATEBLUE:2070474495,MEDIUMSPRINGGREEN:16423679,MEDIUMTURQUOISE:1221709055,MEDIUMVIOLETRED:3340076543,MIDNIGHTBLUE:421097727,MINTCREAM:4127193855,MISTYROSE:4293190143,MOCCASIN:4293178879,NAVAJOWHITE:4292783615,NAVY:33023,OLDLACE:4260751103,OLIVE:2155872511,OLIVEDRAB:1804477439,ORANGE:4289003775,ORANGERED:4282712319,ORCHID:3664828159,PALEGOLDENROD:4008225535,PALEGREEN:2566625535,PALETURQUOISE:2951671551,PALEVIOLETRED:3681588223,PAPAYAWHIP:4293907967,PEACHPUFF:4292524543,PERU:3448061951,PINK:4290825215,PLUM:3718307327,POWDERBLUE:2967529215,PURPLE:2147516671,REBECCAPURPLE:1714657791,RED:4278190335,ROSYBROWN:3163525119,ROYALBLUE:1097458175,SADDLEBROWN:2336560127,SALMON:4202722047,SANDYBROWN:4104413439,SEAGREEN:780883967,SEASHELL:4294307583,SIENNA:2689740287,SILVER:3233857791,SKYBLUE:2278484991,SLATEBLUE:1784335871,SLATEGRAY:1887473919,SLATEGREY:1887473919,SNOW:4294638335,SPRINGGREEN:16744447,STEELBLUE:1182971135,TAN:3535047935,TEAL:8421631,THISTLE:3636451583,TOMATO:4284696575,TRANSPARENT:0,TURQUOISE:1088475391,VIOLET:4001558271,WHEAT:4125012991,WHITE:4294967295,WHITESMOKE:4126537215,YELLOW:4294902015,YELLOWGREEN:2597139199},Ap={name:"background-clip",initialValue:"border-box",prefix:!1,type:1,parse:function(e,t){return t.map((function(e){if(Td(e))switch(e.value){case"padding-box":return 1;case"content-box":return 2}return 0}))}},hp={name:"background-color",initialValue:"transparent",prefix:!1,type:3,format:"color"},cp=function(e,t){var i=qd(e,t[0]),s=t[1];return s&&Vd(s)?{color:i,stop:s}:{color:i,stop:null}},up=function(e,t){var i=e[0],s=e[e.length-1];null===i.stop&&(i.stop=jd),null===s.stop&&(s.stop=zd);for(var r=[],o=0,n=0;no?r.push(l):r.push(o),o=l}else r.push(null)}var A=null;for(n=0;ne.optimumDistance)?{optimumCorner:t,optimumDistance:a}:e}),{optimumDistance:r?1/0:-1/0,optimumCorner:null}).optimumCorner},gp=function(e,t){var i=Zd(180),s=[];return kd(t).forEach((function(t,r){if(0===r){var o=t[0];if(20===o.type&&-1!==["top","left","right","bottom"].indexOf(o.value))return void(i=Yd(t));if(Jd(o))return void(i=(Xd(e,o)+Zd(270))%Zd(360))}var n=cp(e,t);s.push(n)})),{angle:i,stops:s,type:1}},mp=function(e,t){var i=0,s=3,r=[],o=[];return kd(t).forEach((function(t,n){var a=!0;if(0===n?a=t.reduce((function(e,t){if(Td(t))switch(t.value){case"center":return o.push(Gd),!1;case"top":case"left":return o.push(jd),!1;case"right":case"bottom":return o.push(zd),!1}else if(Vd(t)||Qd(t))return o.push(t),!1;return e}),a):1===n&&(a=t.reduce((function(e,t){if(Td(t))switch(t.value){case"circle":return i=0,!1;case"ellipse":return i=1,!1;case"contain":case"closest-side":return s=0,!1;case"farthest-side":return s=1,!1;case"closest-corner":return s=2,!1;case"cover":case"farthest-corner":return s=3,!1}else if(Qd(t)||Vd(t))return Array.isArray(s)||(s=[]),s.push(t),!1;return e}),a)),a){var l=cp(e,t);r.push(l)}})),{size:s,shape:i,stops:r,position:o,type:2}},_p=function(e,t){if(22===t.type){var i={url:t.value,type:0};return e.cache.addImage(t.value),i}if(18===t.type){var s=bp[t.name];if(void 0===s)throw new Error('Attempting to parse an unsupported image function "'+t.name+'"');return s(e,t.values)}throw new Error("Unsupported image type "+t.type)};var vp,bp={"linear-gradient":function(e,t){var i=Zd(180),s=[];return kd(t).forEach((function(t,r){if(0===r){var o=t[0];if(20===o.type&&"to"===o.value)return void(i=Yd(t));if(Jd(o))return void(i=Xd(e,o))}var n=cp(e,t);s.push(n)})),{angle:i,stops:s,type:1}},"-moz-linear-gradient":gp,"-ms-linear-gradient":gp,"-o-linear-gradient":gp,"-webkit-linear-gradient":gp,"radial-gradient":function(e,t){var i=0,s=3,r=[],o=[];return kd(t).forEach((function(t,n){var a=!0;if(0===n){var l=!1;a=t.reduce((function(e,t){if(l)if(Td(t))switch(t.value){case"center":return o.push(Gd),e;case"top":case"left":return o.push(jd),e;case"right":case"bottom":return o.push(zd),e}else(Vd(t)||Qd(t))&&o.push(t);else if(Td(t))switch(t.value){case"circle":return i=0,!1;case"ellipse":return i=1,!1;case"at":return l=!0,!1;case"closest-side":return s=0,!1;case"cover":case"farthest-side":return s=1,!1;case"contain":case"closest-corner":return s=2,!1;case"farthest-corner":return s=3,!1}else if(Qd(t)||Vd(t))return Array.isArray(s)||(s=[]),s.push(t),!1;return e}),a)}if(a){var A=cp(e,t);r.push(A)}})),{size:s,shape:i,stops:r,position:o,type:2}},"-moz-radial-gradient":mp,"-ms-radial-gradient":mp,"-o-radial-gradient":mp,"-webkit-radial-gradient":mp,"-webkit-gradient":function(e,t){var i=Zd(180),s=[],r=1;return kd(t).forEach((function(t,i){var o=t[0];if(0===i){if(Td(o)&&"linear"===o.value)return void(r=1);if(Td(o)&&"radial"===o.value)return void(r=2)}if(18===o.type)if("from"===o.name){var n=qd(e,o.values[0]);s.push({stop:jd,color:n})}else if("to"===o.name){n=qd(e,o.values[0]);s.push({stop:zd,color:n})}else if("color-stop"===o.name){var a=o.values.filter(Od);if(2===a.length){n=qd(e,a[1]);var l=a[0];Sd(l)&&s.push({stop:{type:16,number:100*l.number,flags:l.flags},color:n})}}})),1===r?{angle:(i+Zd(180))%Zd(360),stops:s,type:r}:{size:3,shape:0,stops:s,position:[],type:r}}},yp={name:"background-image",initialValue:"none",type:1,prefix:!1,parse:function(e,t){if(0===t.length)return[];var i=t[0];return 20===i.type&&"none"===i.value?[]:t.filter((function(e){return Od(e)&&function(e){return!(20===e.type&&"none"===e.value||18===e.type&&!bp[e.name])}(e)})).map((function(t){return _p(e,t)}))}},xp={name:"background-origin",initialValue:"border-box",prefix:!1,type:1,parse:function(e,t){return t.map((function(e){if(Td(e))switch(e.value){case"padding-box":return 1;case"content-box":return 2}return 0}))}},Bp={name:"background-position",initialValue:"0% 0%",type:1,prefix:!1,parse:function(e,t){return kd(t).map((function(e){return e.filter(Vd)})).map(Hd)}},wp={name:"background-repeat",initialValue:"repeat",prefix:!1,type:1,parse:function(e,t){return kd(t).map((function(e){return e.filter(Td).map((function(e){return e.value})).join(" ")})).map(Pp)}},Pp=function(e){switch(e){case"no-repeat":return 1;case"repeat-x":case"repeat no-repeat":return 2;case"repeat-y":case"no-repeat repeat":return 3;default:return 0}};!function(e){e.AUTO="auto",e.CONTAIN="contain",e.COVER="cover"}(vp||(vp={}));var Cp,Mp={name:"background-size",initialValue:"0",prefix:!1,type:1,parse:function(e,t){return kd(t).map((function(e){return e.filter(Ep)}))}},Ep=function(e){return Td(e)||Vd(e)},Fp=function(e){return{name:"border-"+e+"-color",initialValue:"transparent",prefix:!1,type:3,format:"color"}},Ip=Fp("top"),Dp=Fp("right"),Sp=Fp("bottom"),Tp=Fp("left"),Rp=function(e){return{name:"border-radius-"+e,initialValue:"0 0",prefix:!1,type:1,parse:function(e,t){return Hd(t.filter(Vd))}}},Lp=Rp("top-left"),Up=Rp("top-right"),Op=Rp("bottom-right"),kp=Rp("bottom-left"),Np=function(e){return{name:"border-"+e+"-style",initialValue:"solid",prefix:!1,type:2,parse:function(e,t){switch(t){case"none":return 0;case"dashed":return 2;case"dotted":return 3;case"double":return 4}return 1}}},Qp=Np("top"),Vp=Np("right"),Hp=Np("bottom"),jp=Np("left"),Gp=function(e){return{name:"border-"+e+"-width",initialValue:"0",type:0,prefix:!1,parse:function(e,t){return Dd(t)?t.number:0}}},zp=Gp("top"),Wp=Gp("right"),Kp=Gp("bottom"),Xp=Gp("left"),Jp={name:"color",initialValue:"transparent",prefix:!1,type:3,format:"color"},Yp={name:"direction",initialValue:"ltr",prefix:!1,type:2,parse:function(e,t){return"rtl"===t?1:0}},Zp={name:"display",initialValue:"inline-block",prefix:!1,type:1,parse:function(e,t){return t.filter(Td).reduce((function(e,t){return e|qp(t.value)}),0)}},qp=function(e){switch(e){case"block":case"-webkit-box":return 2;case"inline":return 4;case"run-in":return 8;case"flow":return 16;case"flow-root":return 32;case"table":return 64;case"flex":case"-webkit-flex":return 128;case"grid":case"-ms-grid":return 256;case"ruby":return 512;case"subgrid":return 1024;case"list-item":return 2048;case"table-row-group":return 4096;case"table-header-group":return 8192;case"table-footer-group":return 16384;case"table-row":return 32768;case"table-cell":return 65536;case"table-column-group":return 131072;case"table-column":return 262144;case"table-caption":return 524288;case"ruby-base":return 1048576;case"ruby-text":return 2097152;case"ruby-base-container":return 4194304;case"ruby-text-container":return 8388608;case"contents":return 16777216;case"inline-block":return 33554432;case"inline-list-item":return 67108864;case"inline-table":return 134217728;case"inline-flex":return 268435456;case"inline-grid":return 536870912}return 0},$p={name:"float",initialValue:"none",prefix:!1,type:2,parse:function(e,t){switch(t){case"left":return 1;case"right":return 2;case"inline-start":return 3;case"inline-end":return 4}return 0}},ef={name:"letter-spacing",initialValue:"0",prefix:!1,type:0,parse:function(e,t){return 20===t.type&&"normal"===t.value?0:17===t.type||15===t.type?t.number:0}};!function(e){e.NORMAL="normal",e.STRICT="strict"}(Cp||(Cp={}));var tf,sf={name:"line-break",initialValue:"normal",prefix:!1,type:2,parse:function(e,t){return"strict"===t?Cp.STRICT:Cp.NORMAL}},rf={name:"line-height",initialValue:"normal",prefix:!1,type:4},of=function(e,t){return Td(e)&&"normal"===e.value?1.2*t:17===e.type?t*e.number:Vd(e)?Kd(e,t):t},nf={name:"list-style-image",initialValue:"none",type:0,prefix:!1,parse:function(e,t){return 20===t.type&&"none"===t.value?null:_p(e,t)}},af={name:"list-style-position",initialValue:"outside",prefix:!1,type:2,parse:function(e,t){return"inside"===t?0:1}},lf={name:"list-style-type",initialValue:"none",prefix:!1,type:2,parse:function(e,t){switch(t){case"disc":return 0;case"circle":return 1;case"square":return 2;case"decimal":return 3;case"cjk-decimal":return 4;case"decimal-leading-zero":return 5;case"lower-roman":return 6;case"upper-roman":return 7;case"lower-greek":return 8;case"lower-alpha":return 9;case"upper-alpha":return 10;case"arabic-indic":return 11;case"armenian":return 12;case"bengali":return 13;case"cambodian":return 14;case"cjk-earthly-branch":return 15;case"cjk-heavenly-stem":return 16;case"cjk-ideographic":return 17;case"devanagari":return 18;case"ethiopic-numeric":return 19;case"georgian":return 20;case"gujarati":return 21;case"gurmukhi":case"hebrew":return 22;case"hiragana":return 23;case"hiragana-iroha":return 24;case"japanese-formal":return 25;case"japanese-informal":return 26;case"kannada":return 27;case"katakana":return 28;case"katakana-iroha":return 29;case"khmer":return 30;case"korean-hangul-formal":return 31;case"korean-hanja-formal":return 32;case"korean-hanja-informal":return 33;case"lao":return 34;case"lower-armenian":return 35;case"malayalam":return 36;case"mongolian":return 37;case"myanmar":return 38;case"oriya":return 39;case"persian":return 40;case"simp-chinese-formal":return 41;case"simp-chinese-informal":return 42;case"tamil":return 43;case"telugu":return 44;case"thai":return 45;case"tibetan":return 46;case"trad-chinese-formal":return 47;case"trad-chinese-informal":return 48;case"upper-armenian":return 49;case"disclosure-open":return 50;case"disclosure-closed":return 51;default:return-1}}},Af=function(e){return{name:"margin-"+e,initialValue:"0",prefix:!1,type:4}},hf=Af("top"),cf=Af("right"),uf=Af("bottom"),df=Af("left"),pf={name:"overflow",initialValue:"visible",prefix:!1,type:1,parse:function(e,t){return t.filter(Td).map((function(e){switch(e.value){case"hidden":return 1;case"scroll":return 2;case"clip":return 3;case"auto":return 4;default:return 0}}))}},ff={name:"overflow-wrap",initialValue:"normal",prefix:!1,type:2,parse:function(e,t){return"break-word"===t?"break-word":"normal"}},gf=function(e){return{name:"padding-"+e,initialValue:"0",prefix:!1,type:3,format:"length-percentage"}},mf=gf("top"),_f=gf("right"),vf=gf("bottom"),bf=gf("left"),yf={name:"text-align",initialValue:"left",prefix:!1,type:2,parse:function(e,t){switch(t){case"right":return 2;case"center":case"justify":return 1;default:return 0}}},xf={name:"position",initialValue:"static",prefix:!1,type:2,parse:function(e,t){switch(t){case"relative":return 1;case"absolute":return 2;case"fixed":return 3;case"sticky":return 4}return 0}},Bf={name:"text-shadow",initialValue:"none",type:1,prefix:!1,parse:function(e,t){return 1===t.length&&Ld(t[0],"none")?[]:kd(t).map((function(t){for(var i={color:lp.TRANSPARENT,offsetX:jd,offsetY:jd,blur:jd},s=0,r=0;r1?1:0],this.overflowWrap=ig(e,ff,t.overflowWrap),this.paddingTop=ig(e,mf,t.paddingTop),this.paddingRight=ig(e,_f,t.paddingRight),this.paddingBottom=ig(e,vf,t.paddingBottom),this.paddingLeft=ig(e,bf,t.paddingLeft),this.paintOrder=ig(e,Yf,t.paintOrder),this.position=ig(e,xf,t.position),this.textAlign=ig(e,yf,t.textAlign),this.textDecorationColor=ig(e,Lf,null!==(i=t.textDecorationColor)&&void 0!==i?i:t.color),this.textDecorationLine=ig(e,Uf,null!==(s=t.textDecorationLine)&&void 0!==s?s:t.textDecoration),this.textShadow=ig(e,Bf,t.textShadow),this.textTransform=ig(e,wf,t.textTransform),this.transform=ig(e,Pf,t.transform),this.transformOrigin=ig(e,Ff,t.transformOrigin),this.visibility=ig(e,If,t.visibility),this.webkitTextStrokeColor=ig(e,Zf,t.webkitTextStrokeColor),this.webkitTextStrokeWidth=ig(e,qf,t.webkitTextStrokeWidth),this.wordBreak=ig(e,Df,t.wordBreak),this.zIndex=ig(e,Sf,t.zIndex)}return e.prototype.isVisible=function(){return this.display>0&&this.opacity>0&&0===this.visibility},e.prototype.isTransparent=function(){return $d(this.backgroundColor)},e.prototype.isTransformed=function(){return null!==this.transform},e.prototype.isPositioned=function(){return 0!==this.position},e.prototype.isPositionedWithZIndex=function(){return this.isPositioned()&&!this.zIndex.auto},e.prototype.isFloating=function(){return 0!==this.float},e.prototype.isInlineLevel=function(){return Hf(this.display,4)||Hf(this.display,33554432)||Hf(this.display,268435456)||Hf(this.display,536870912)||Hf(this.display,67108864)||Hf(this.display,134217728)},e}(),eg=function(e,t){this.content=ig(e,jf,t.content),this.quotes=ig(e,Kf,t.quotes)},tg=function(e,t){this.counterIncrement=ig(e,Gf,t.counterIncrement),this.counterReset=ig(e,zf,t.counterReset)},ig=function(e,t,i){var s=new Fd,r=null!=i?i.toString():t.initialValue;s.write(r);var o=new Id(s.read());switch(t.type){case 2:var n=o.parseComponentValue();return t.parse(e,Td(n)?n.value:t.initialValue);case 0:return t.parse(e,o.parseComponentValue());case 1:return t.parse(e,o.parseComponentValues());case 4:return o.parseComponentValue();case 3:switch(t.format){case"angle":return Xd(e,o.parseComponentValue());case"color":return qd(e,o.parseComponentValue());case"image":return _p(e,o.parseComponentValue());case"length":var a=o.parseComponentValue();return Qd(a)?a:jd;case"length-percentage":var l=o.parseComponentValue();return Vd(l)?l:jd;case"time":return Tf(e,o.parseComponentValue())}}},sg=function(e,t){var i=function(e){switch(e.getAttribute("data-html2canvas-debug")){case"all":return 1;case"clone":return 2;case"parse":return 3;case"render":return 4;default:return 0}}(e);return 1===i||t===i},rg=function(e,t){this.context=e,this.textNodes=[],this.elements=[],this.flags=0,sg(t,3),this.styles=new $f(e,window.getComputedStyle(t,null)),rm(t)&&(this.styles.animationDuration.some((function(e){return e>0}))&&(t.style.animationDuration="0s"),null!==this.styles.transform&&(t.style.transform="none")),this.bounds=eu(this.context,t),sg(t,4)&&(this.flags|=16)},og="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ng="undefined"==typeof Uint8Array?[]:new Uint8Array(256),ag=0;ag=0){if(e<55296||e>56319&&e<=65535)return t=((t=this.index[e>>5])<<2)+(31&e),this.data[t];if(e<=65535)return t=((t=this.index[2048+(e-55296>>5)])<<2)+(31&e),this.data[t];if(e>11),t=this.index[t],t+=e>>5&63,t=((t=this.index[t])<<2)+(31&e),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},e}(),hg="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",cg="undefined"==typeof Uint8Array?[]:new Uint8Array(256),ug=0;ug>10),n%1024+56320)),(r+1===i||s.length>16384)&&(o+=String.fromCharCode.apply(String,s),s.length=0)}return o},vg=function(e,t){var i,s,r,o=function(e){var t,i,s,r,o,n=.75*e.length,a=e.length,l=0;"="===e[e.length-1]&&(n--,"="===e[e.length-2]&&n--);var A="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&void 0!==Uint8Array.prototype.slice?new ArrayBuffer(n):new Array(n),h=Array.isArray(A)?A:new Uint8Array(A);for(t=0;t>4,h[l++]=(15&s)<<4|r>>2,h[l++]=(3&r)<<6|63&o;return A}(e),n=Array.isArray(o)?function(e){for(var t=e.length,i=[],s=0;s=55296&&r<=56319&&i=i)return{done:!0,value:null};for(var e="×";sn.x||r.y>n.y;return n=r,0===t||a}));return e.body.removeChild(t),a}(document);return Object.defineProperty(Cg,"SUPPORT_WORD_BREAKING",{value:e}),e},get SUPPORT_SVG_DRAWING(){var e=function(e){var t=new Image,i=e.createElement("canvas"),s=i.getContext("2d");if(!s)return!1;t.src="data:image/svg+xml,";try{s.drawImage(t,0,0),i.toDataURL()}catch(e){return!1}return!0}(document);return Object.defineProperty(Cg,"SUPPORT_SVG_DRAWING",{value:e}),e},get SUPPORT_FOREIGNOBJECT_DRAWING(){var e="function"==typeof Array.from&&"function"==typeof window.fetch?function(e){var t=e.createElement("canvas"),i=100;t.width=i,t.height=i;var s=t.getContext("2d");if(!s)return Promise.reject(!1);s.fillStyle="rgb(0, 255, 0)",s.fillRect(0,0,i,i);var r=new Image,o=t.toDataURL();r.src=o;var n=wg(i,i,0,0,r);return s.fillStyle="red",s.fillRect(0,0,i,i),Pg(n).then((function(t){s.drawImage(t,0,0);var r=s.getImageData(0,0,i,i).data;s.fillStyle="red",s.fillRect(0,0,i,i);var n=e.createElement("div");return n.style.backgroundImage="url("+o+")",n.style.height="100px",Bg(r)?Pg(wg(i,i,0,0,n)):Promise.reject(!1)})).then((function(e){return s.drawImage(e,0,0),Bg(s.getImageData(0,0,i,i).data)})).catch((function(){return!1}))}(document):Promise.resolve(!1);return Object.defineProperty(Cg,"SUPPORT_FOREIGNOBJECT_DRAWING",{value:e}),e},get SUPPORT_CORS_IMAGES(){var e=void 0!==(new Image).crossOrigin;return Object.defineProperty(Cg,"SUPPORT_CORS_IMAGES",{value:e}),e},get SUPPORT_RESPONSE_TYPE(){var e="string"==typeof(new XMLHttpRequest).responseType;return Object.defineProperty(Cg,"SUPPORT_RESPONSE_TYPE",{value:e}),e},get SUPPORT_CORS_XHR(){var e="withCredentials"in new XMLHttpRequest;return Object.defineProperty(Cg,"SUPPORT_CORS_XHR",{value:e}),e},get SUPPORT_NATIVE_TEXT_SEGMENTATION(){var e=!("undefined"==typeof Intl||!Intl.Segmenter);return Object.defineProperty(Cg,"SUPPORT_NATIVE_TEXT_SEGMENTATION",{value:e}),e}},Mg=function(e,t){this.text=e,this.bounds=t},Eg=function(e,t){var i=t.ownerDocument;if(i){var s=i.createElement("html2canvaswrapper");s.appendChild(t.cloneNode(!0));var r=t.parentNode;if(r){r.replaceChild(s,t);var o=eu(e,s);return s.firstChild&&r.replaceChild(s.firstChild,s),o}}return $c.EMPTY},Fg=function(e,t,i){var s=e.ownerDocument;if(!s)throw new Error("Node has no owner document");var r=s.createRange();return r.setStart(e,t),r.setEnd(e,t+i),r},Ig=function(e){if(Cg.SUPPORT_NATIVE_TEXT_SEGMENTATION){var t=new Intl.Segmenter(void 0,{granularity:"grapheme"});return Array.from(t.segment(e)).map((function(e){return e.segment}))}return function(e){for(var t,i=xg(e),s=[];!(t=i.next()).done;)t.value&&s.push(t.value.slice());return s}(e)},Dg=function(e,t){return 0!==t.letterSpacing?Ig(e):function(e,t){if(Cg.SUPPORT_NATIVE_TEXT_SEGMENTATION){var i=new Intl.Segmenter(void 0,{granularity:"word"});return Array.from(i.segment(e)).map((function(e){return e.segment}))}return Tg(e,t)}(e,t)},Sg=[32,160,4961,65792,65793,4153,4241],Tg=function(e,t){for(var i,s=function(e,t){var i=tu(e),s=Yu(i,t),r=s[0],o=s[1],n=s[2],a=i.length,l=0,A=0;return{next:function(){if(A>=a)return{done:!0,value:null};for(var e="×";A0)if(Cg.SUPPORT_RANGE_BOUNDS){var r=Fg(s,n,t.length).getClientRects();if(r.length>1){var a=Ig(t),l=0;a.forEach((function(t){o.push(new Mg(t,$c.fromDOMRectList(e,Fg(s,l+n,t.length).getClientRects()))),l+=t.length}))}else o.push(new Mg(t,$c.fromDOMRectList(e,r)))}else{var A=s.splitText(t.length);o.push(new Mg(t,Eg(e,s))),s=A}else Cg.SUPPORT_RANGE_BOUNDS||(s=s.splitText(t.length));n+=t.length})),o}(e,this.text,i,t)},Lg=function(e,t){switch(t){case 1:return e.toLowerCase();case 3:return e.replace(Ug,Og);case 2:return e.toUpperCase();default:return e}},Ug=/(^|\s|:|-|\(|\))([a-z])/g,Og=function(e,t,i){return e.length>0?t+i.toUpperCase():e},kg=function(e){function t(t,i){var s=e.call(this,t,i)||this;return s.src=i.currentSrc||i.src,s.intrinsicWidth=i.naturalWidth,s.intrinsicHeight=i.naturalHeight,s.context.cache.addImage(s.src),s}return Xc(t,e),t}(rg),Ng=function(e){function t(t,i){var s=e.call(this,t,i)||this;return s.canvas=i,s.intrinsicWidth=i.width,s.intrinsicHeight=i.height,s}return Xc(t,e),t}(rg),Qg=function(e){function t(t,i){var s=e.call(this,t,i)||this,r=new XMLSerializer,o=eu(t,i);return i.setAttribute("width",o.width+"px"),i.setAttribute("height",o.height+"px"),s.svg="data:image/svg+xml,"+encodeURIComponent(r.serializeToString(i)),s.intrinsicWidth=i.width.baseVal.value,s.intrinsicHeight=i.height.baseVal.value,s.context.cache.addImage(s.svg),s}return Xc(t,e),t}(rg),Vg=function(e){function t(t,i){var s=e.call(this,t,i)||this;return s.value=i.value,s}return Xc(t,e),t}(rg),Hg=function(e){function t(t,i){var s=e.call(this,t,i)||this;return s.start=i.start,s.reversed="boolean"==typeof i.reversed&&!0===i.reversed,s}return Xc(t,e),t}(rg),jg=[{type:15,flags:0,unit:"px",number:3}],Gg=[{type:16,flags:0,number:50}],zg="password",Wg=function(e){function t(t,i){var s,r=e.call(this,t,i)||this;switch(r.type=i.type.toLowerCase(),r.checked=i.checked,r.value=function(e){var t=e.type===zg?new Array(e.value.length+1).join("•"):e.value;return 0===t.length?e.placeholder||"":t}(i),"checkbox"!==r.type&&"radio"!==r.type||(r.styles.backgroundColor=3739148031,r.styles.borderTopColor=r.styles.borderRightColor=r.styles.borderBottomColor=r.styles.borderLeftColor=2779096575,r.styles.borderTopWidth=r.styles.borderRightWidth=r.styles.borderBottomWidth=r.styles.borderLeftWidth=1,r.styles.borderTopStyle=r.styles.borderRightStyle=r.styles.borderBottomStyle=r.styles.borderLeftStyle=1,r.styles.backgroundClip=[0],r.styles.backgroundOrigin=[0],r.bounds=(s=r.bounds).width>s.height?new $c(s.left+(s.width-s.height)/2,s.top,s.height,s.height):s.width0)i.textNodes.push(new Rg(e,r,i.styles));else if(sm(r))if(_m(r)&&r.assignedNodes)r.assignedNodes().forEach((function(t){return Zg(e,t,i,s)}));else{var n=qg(e,r);n.styles.isVisible()&&(em(r,n,s)?n.flags|=4:tm(n.styles)&&(n.flags|=2),-1!==Yg.indexOf(r.tagName)&&(n.flags|=8),i.elements.push(n),r.slot,r.shadowRoot?Zg(e,r.shadowRoot,n,s):gm(r)||Am(r)||mm(r)||Zg(e,r,n,s))}},qg=function(e,t){return dm(t)?new kg(e,t):cm(t)?new Ng(e,t):Am(t)?new Qg(e,t):nm(t)?new Vg(e,t):am(t)?new Hg(e,t):lm(t)?new Wg(e,t):mm(t)?new Kg(e,t):gm(t)?new Xg(e,t):pm(t)?new Jg(e,t):new rg(e,t)},$g=function(e,t){var i=qg(e,t);return i.flags|=4,Zg(e,t,i,i),i},em=function(e,t,i){return t.styles.isPositionedWithZIndex()||t.styles.opacity<1||t.styles.isTransformed()||hm(e)&&i.styles.isTransparent()},tm=function(e){return e.isPositioned()||e.isFloating()},im=function(e){return e.nodeType===Node.TEXT_NODE},sm=function(e){return e.nodeType===Node.ELEMENT_NODE},rm=function(e){return sm(e)&&void 0!==e.style&&!om(e)},om=function(e){return"object"==typeof e.className},nm=function(e){return"LI"===e.tagName},am=function(e){return"OL"===e.tagName},lm=function(e){return"INPUT"===e.tagName},Am=function(e){return"svg"===e.tagName},hm=function(e){return"BODY"===e.tagName},cm=function(e){return"CANVAS"===e.tagName},um=function(e){return"VIDEO"===e.tagName},dm=function(e){return"IMG"===e.tagName},pm=function(e){return"IFRAME"===e.tagName},fm=function(e){return"STYLE"===e.tagName},gm=function(e){return"TEXTAREA"===e.tagName},mm=function(e){return"SELECT"===e.tagName},_m=function(e){return"SLOT"===e.tagName},vm=function(e){return e.tagName.indexOf("-")>0},bm=function(){function e(){this.counters={}}return e.prototype.getCounterValue=function(e){var t=this.counters[e];return t&&t.length?t[t.length-1]:1},e.prototype.getCounterValues=function(e){var t=this.counters[e];return t||[]},e.prototype.pop=function(e){var t=this;e.forEach((function(e){return t.counters[e].pop()}))},e.prototype.parse=function(e){var t=this,i=e.counterIncrement,s=e.counterReset,r=!0;null!==i&&i.forEach((function(e){var i=t.counters[e.counter];i&&0!==e.increment&&(r=!1,i.length||i.push(1),i[Math.max(0,i.length-1)]+=e.increment)}));var o=[];return r&&s.forEach((function(e){var i=t.counters[e.counter];o.push(e.counter),i||(i=t.counters[e.counter]=[]),i.push(e.reset)})),o},e}(),ym={integers:[1e3,900,500,400,100,90,50,40,10,9,5,4,1],values:["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]},xm={integers:[9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],values:["Ք","Փ","Ւ","Ց","Ր","Տ","Վ","Ս","Ռ","Ջ","Պ","Չ","Ո","Շ","Ն","Յ","Մ","Ճ","Ղ","Ձ","Հ","Կ","Ծ","Խ","Լ","Ի","Ժ","Թ","Ը","Է","Զ","Ե","Դ","Գ","Բ","Ա"]},Bm={integers:[1e4,9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,400,300,200,100,90,80,70,60,50,40,30,20,19,18,17,16,15,10,9,8,7,6,5,4,3,2,1],values:["י׳","ט׳","ח׳","ז׳","ו׳","ה׳","ד׳","ג׳","ב׳","א׳","ת","ש","ר","ק","צ","פ","ע","ס","נ","מ","ל","כ","יט","יח","יז","טז","טו","י","ט","ח","ז","ו","ה","ד","ג","ב","א"]},wm={integers:[1e4,9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],values:["ჵ","ჰ","ჯ","ჴ","ხ","ჭ","წ","ძ","ც","ჩ","შ","ყ","ღ","ქ","ფ","ჳ","ტ","ს","რ","ჟ","პ","ო","ჲ","ნ","მ","ლ","კ","ი","თ","ჱ","ზ","ვ","ე","დ","გ","ბ","ა"]},Pm=function(e,t,i,s,r,o){return ei?Im(e,r,o.length>0):s.integers.reduce((function(t,i,r){for(;e>=i;)e-=i,t+=s.values[r];return t}),"")+o},Cm=function(e,t,i,s){var r="";do{i||e--,r=s(e)+r,e/=t}while(e*t>=t);return r},Mm=function(e,t,i,s,r){var o=i-t+1;return(e<0?"-":"")+(Cm(Math.abs(e),o,s,(function(e){return iu(Math.floor(e%o)+t)}))+r)},Em=function(e,t,i){void 0===i&&(i=". ");var s=t.length;return Cm(Math.abs(e),s,!1,(function(e){return t[Math.floor(e%s)]}))+i},Fm=function(e,t,i,s,r,o){if(e<-9999||e>9999)return Im(e,4,r.length>0);var n=Math.abs(e),a=r;if(0===n)return t[0]+a;for(var l=0;n>0&&l<=4;l++){var A=n%10;0===A&&Hf(o,1)&&""!==a?a=t[A]+a:A>1||1===A&&0===l||1===A&&1===l&&Hf(o,2)||1===A&&1===l&&Hf(o,4)&&e>100||1===A&&l>1&&Hf(o,8)?a=t[A]+(l>0?i[l-1]:"")+a:1===A&&l>0&&(a=i[l-1]+a),n=Math.floor(n/10)}return(e<0?s:"")+a},Im=function(e,t,i){var s=i?". ":"",r=i?"、":"",o=i?", ":"",n=i?" ":"";switch(t){case 0:return"•"+n;case 1:return"◦"+n;case 2:return"◾"+n;case 5:var a=Mm(e,48,57,!0,s);return a.length<4?"0"+a:a;case 4:return Em(e,"〇一二三四五六七八九",r);case 6:return Pm(e,1,3999,ym,3,s).toLowerCase();case 7:return Pm(e,1,3999,ym,3,s);case 8:return Mm(e,945,969,!1,s);case 9:return Mm(e,97,122,!1,s);case 10:return Mm(e,65,90,!1,s);case 11:return Mm(e,1632,1641,!0,s);case 12:case 49:return Pm(e,1,9999,xm,3,s);case 35:return Pm(e,1,9999,xm,3,s).toLowerCase();case 13:return Mm(e,2534,2543,!0,s);case 14:case 30:return Mm(e,6112,6121,!0,s);case 15:return Em(e,"子丑寅卯辰巳午未申酉戌亥",r);case 16:return Em(e,"甲乙丙丁戊己庚辛壬癸",r);case 17:case 48:return Fm(e,"零一二三四五六七八九","十百千萬","負",r,14);case 47:return Fm(e,"零壹貳參肆伍陸柒捌玖","拾佰仟萬","負",r,15);case 42:return Fm(e,"零一二三四五六七八九","十百千萬","负",r,14);case 41:return Fm(e,"零壹贰叁肆伍陆柒捌玖","拾佰仟萬","负",r,15);case 26:return Fm(e,"〇一二三四五六七八九","十百千万","マイナス",r,0);case 25:return Fm(e,"零壱弐参四伍六七八九","拾百千万","マイナス",r,7);case 31:return Fm(e,"영일이삼사오육칠팔구","십백천만","마이너스",o,7);case 33:return Fm(e,"零一二三四五六七八九","十百千萬","마이너스",o,0);case 32:return Fm(e,"零壹貳參四五六七八九","拾百千","마이너스",o,7);case 18:return Mm(e,2406,2415,!0,s);case 20:return Pm(e,1,19999,wm,3,s);case 21:return Mm(e,2790,2799,!0,s);case 22:return Mm(e,2662,2671,!0,s);case 22:return Pm(e,1,10999,Bm,3,s);case 23:return Em(e,"あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわゐゑをん");case 24:return Em(e,"いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす");case 27:return Mm(e,3302,3311,!0,s);case 28:return Em(e,"アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヰヱヲン",r);case 29:return Em(e,"イロハニホヘトチリヌルヲワカヨタレソツネナラムウヰノオクヤマケフコエテアサキユメミシヱヒモセス",r);case 34:return Mm(e,3792,3801,!0,s);case 37:return Mm(e,6160,6169,!0,s);case 38:return Mm(e,4160,4169,!0,s);case 39:return Mm(e,2918,2927,!0,s);case 40:return Mm(e,1776,1785,!0,s);case 43:return Mm(e,3046,3055,!0,s);case 44:return Mm(e,3174,3183,!0,s);case 45:return Mm(e,3664,3673,!0,s);case 46:return Mm(e,3872,3881,!0,s);default:return Mm(e,48,57,!0,s)}},Dm=function(){function e(e,t,i){if(this.context=e,this.options=i,this.scrolledElements=[],this.referenceElement=t,this.counters=new bm,this.quoteDepth=0,!t.ownerDocument)throw new Error("Cloned element does not have an owner document");this.documentElement=this.cloneNode(t.ownerDocument.documentElement,!1)}return e.prototype.toIFrame=function(e,t){var i=this,s=Tm(e,t);if(!s.contentWindow)return Promise.reject("Unable to find iframe window");var r=e.defaultView.pageXOffset,o=e.defaultView.pageYOffset,n=s.contentWindow,a=n.document,l=Um(s).then((function(){return Yc(i,void 0,void 0,(function(){var e,i;return Zc(this,(function(r){switch(r.label){case 0:return this.scrolledElements.forEach(Vm),n&&(n.scrollTo(t.left,t.top),!/(iPad|iPhone|iPod)/g.test(navigator.userAgent)||n.scrollY===t.top&&n.scrollX===t.left||(this.context.logger.warn("Unable to restore scroll position for cloned document"),this.context.windowBounds=this.context.windowBounds.add(n.scrollX-t.left,n.scrollY-t.top,0,0))),e=this.options.onclone,void 0===(i=this.clonedReferenceElement)?[2,Promise.reject("Error finding the "+this.referenceElement.nodeName+" in the cloned document")]:a.fonts&&a.fonts.ready?[4,a.fonts.ready]:[3,2];case 1:r.sent(),r.label=2;case 2:return/(AppleWebKit)/g.test(navigator.userAgent)?[4,Lm(a)]:[3,4];case 3:r.sent(),r.label=4;case 4:return"function"==typeof e?[2,Promise.resolve().then((function(){return e(a,i)})).then((function(){return s}))]:[2,s]}}))}))}));return a.open(),a.write(Nm(document.doctype)+""),Qm(this.referenceElement.ownerDocument,r,o),a.replaceChild(a.adoptNode(this.documentElement),a.documentElement),a.close(),l},e.prototype.createElementClone=function(e){if(sg(e,2),cm(e))return this.createCanvasClone(e);if(um(e))return this.createVideoClone(e);if(fm(e))return this.createStyleClone(e);var t=e.cloneNode(!1);return dm(t)&&(dm(e)&&e.currentSrc&&e.currentSrc!==e.src&&(t.src=e.currentSrc,t.srcset=""),"lazy"===t.loading&&(t.loading="eager")),vm(t)?this.createCustomElementClone(t):t},e.prototype.createCustomElementClone=function(e){var t=document.createElement("html2canvascustomelement");return km(e.style,t),t},e.prototype.createStyleClone=function(e){try{var t=e.sheet;if(t&&t.cssRules){var i=[].slice.call(t.cssRules,0).reduce((function(e,t){return t&&"string"==typeof t.cssText?e+t.cssText:e}),""),s=e.cloneNode(!1);return s.textContent=i,s}}catch(e){if(this.context.logger.error("Unable to access cssRules property",e),"SecurityError"!==e.name)throw e}return e.cloneNode(!1)},e.prototype.createCanvasClone=function(e){var t;if(this.options.inlineImages&&e.ownerDocument){var i=e.ownerDocument.createElement("img");try{return i.src=e.toDataURL(),i}catch(t){this.context.logger.info("Unable to inline canvas contents, canvas is tainted",e)}}var s=e.cloneNode(!1);try{s.width=e.width,s.height=e.height;var r=e.getContext("2d"),o=s.getContext("2d");if(o)if(!this.options.allowTaint&&r)o.putImageData(r.getImageData(0,0,e.width,e.height),0,0);else{var n=null!==(t=e.getContext("webgl2"))&&void 0!==t?t:e.getContext("webgl");if(n){var a=n.getContextAttributes();!1===(null==a?void 0:a.preserveDrawingBuffer)&&this.context.logger.warn("Unable to clone WebGL context as it has preserveDrawingBuffer=false",e)}o.drawImage(e,0,0)}return s}catch(t){this.context.logger.info("Unable to clone canvas as it is tainted",e)}return s},e.prototype.createVideoClone=function(e){var t=e.ownerDocument.createElement("canvas");t.width=e.offsetWidth,t.height=e.offsetHeight;var i=t.getContext("2d");try{return i&&(i.drawImage(e,0,0,t.width,t.height),this.options.allowTaint||i.getImageData(0,0,t.width,t.height)),t}catch(t){this.context.logger.info("Unable to clone video as it is tainted",e)}var s=e.ownerDocument.createElement("canvas");return s.width=e.offsetWidth,s.height=e.offsetHeight,s},e.prototype.appendChildNode=function(e,t,i){sm(t)&&(function(e){return"SCRIPT"===e.tagName}(t)||t.hasAttribute("data-html2canvas-ignore")||"function"==typeof this.options.ignoreElements&&this.options.ignoreElements(t))||this.options.copyStyles&&sm(t)&&fm(t)||e.appendChild(this.cloneNode(t,i))},e.prototype.cloneChildNodes=function(e,t,i){for(var s=this,r=e.shadowRoot?e.shadowRoot.firstChild:e.firstChild;r;r=r.nextSibling)if(sm(r)&&_m(r)&&"function"==typeof r.assignedNodes){var o=r.assignedNodes();o.length&&o.forEach((function(e){return s.appendChildNode(t,e,i)}))}else this.appendChildNode(t,r,i)},e.prototype.cloneNode=function(e,t){if(im(e))return document.createTextNode(e.data);if(!e.ownerDocument)return e.cloneNode(!1);var i=e.ownerDocument.defaultView;if(i&&sm(e)&&(rm(e)||om(e))){var s=this.createElementClone(e);s.style.transitionProperty="none";var r=i.getComputedStyle(e),o=i.getComputedStyle(e,":before"),n=i.getComputedStyle(e,":after");this.referenceElement===e&&rm(s)&&(this.clonedReferenceElement=s),hm(s)&&Gm(s);var a=this.counters.parse(new tg(this.context,r)),l=this.resolvePseudoContent(e,s,o,dg.BEFORE);vm(e)&&(t=!0),um(e)||this.cloneChildNodes(e,s,t),l&&s.insertBefore(l,s.firstChild);var A=this.resolvePseudoContent(e,s,n,dg.AFTER);return A&&s.appendChild(A),this.counters.pop(a),(r&&(this.options.copyStyles||om(e))&&!pm(e)||t)&&km(r,s),0===e.scrollTop&&0===e.scrollLeft||this.scrolledElements.push([s,e.scrollLeft,e.scrollTop]),(gm(e)||mm(e))&&(gm(s)||mm(s))&&(s.value=e.value),s}return e.cloneNode(!1)},e.prototype.resolvePseudoContent=function(e,t,i,s){var r=this;if(i){var o=i.content,n=t.ownerDocument;if(n&&o&&"none"!==o&&"-moz-alt-content"!==o&&"none"!==i.display){this.counters.parse(new tg(this.context,i));var a=new eg(this.context,i),l=n.createElement("html2canvaspseudoelement");km(i,l),a.content.forEach((function(t){if(0===t.type)l.appendChild(n.createTextNode(t.value));else if(22===t.type){var i=n.createElement("img");i.src=t.value,i.style.opacity="1",l.appendChild(i)}else if(18===t.type){if("attr"===t.name){var s=t.values.filter(Td);s.length&&l.appendChild(n.createTextNode(e.getAttribute(s[0].value)||""))}else if("counter"===t.name){var o=t.values.filter(Od),A=o[0],h=o[1];if(A&&Td(A)){var c=r.counters.getCounterValue(A.value),u=h&&Td(h)?lf.parse(r.context,h.value):3;l.appendChild(n.createTextNode(Im(c,u,!1)))}}else if("counters"===t.name){var d=t.values.filter(Od),p=(A=d[0],d[1]);h=d[2];if(A&&Td(A)){var f=r.counters.getCounterValues(A.value),g=h&&Td(h)?lf.parse(r.context,h.value):3,m=p&&0===p.type?p.value:"",_=f.map((function(e){return Im(e,g,!1)})).join(m);l.appendChild(n.createTextNode(_))}}}else if(20===t.type)switch(t.value){case"open-quote":l.appendChild(n.createTextNode(Xf(a.quotes,r.quoteDepth++,!0)));break;case"close-quote":l.appendChild(n.createTextNode(Xf(a.quotes,--r.quoteDepth,!1)));break;default:l.appendChild(n.createTextNode(t.value))}})),l.className=Hm+" "+jm;var A=s===dg.BEFORE?" "+Hm:" "+jm;return om(t)?t.className.baseValue+=A:t.className+=A,l}}},e.destroy=function(e){return!!e.parentNode&&(e.parentNode.removeChild(e),!0)},e}();!function(e){e[e.BEFORE=0]="BEFORE",e[e.AFTER=1]="AFTER"}(dg||(dg={}));var Sm,Tm=function(e,t){var i=e.createElement("iframe");return i.className="html2canvas-container",i.style.visibility="hidden",i.style.position="fixed",i.style.left="-10000px",i.style.top="0px",i.style.border="0",i.width=t.width.toString(),i.height=t.height.toString(),i.scrolling="no",i.setAttribute("data-html2canvas-ignore","true"),e.body.appendChild(i),i},Rm=function(e){return new Promise((function(t){e.complete?t():e.src?(e.onload=t,e.onerror=t):t()}))},Lm=function(e){return Promise.all([].slice.call(e.images,0).map(Rm))},Um=function(e){return new Promise((function(t,i){var s=e.contentWindow;if(!s)return i("No window assigned for iframe");var r=s.document;s.onload=e.onload=function(){s.onload=e.onload=null;var i=setInterval((function(){r.body.childNodes.length>0&&"complete"===r.readyState&&(clearInterval(i),t(e))}),50)}}))},Om=["all","d","content"],km=function(e,t){for(var i=e.length-1;i>=0;i--){var s=e.item(i);-1===Om.indexOf(s)&&t.style.setProperty(s,e.getPropertyValue(s))}return t},Nm=function(e){var t="";return e&&(t+=""),t},Qm=function(e,t,i){e&&e.defaultView&&(t!==e.defaultView.pageXOffset||i!==e.defaultView.pageYOffset)&&e.defaultView.scrollTo(t,i)},Vm=function(e){var t=e[0],i=e[1],s=e[2];t.scrollLeft=i,t.scrollTop=s},Hm="___html2canvas___pseudoelement_before",jm="___html2canvas___pseudoelement_after",Gm=function(e){zm(e,"."+Hm+':before{\n content: "" !important;\n display: none !important;\n}\n .'+jm+':after{\n content: "" !important;\n display: none !important;\n}')},zm=function(e,t){var i=e.ownerDocument;if(i){var s=i.createElement("style");s.textContent=t,e.appendChild(s)}},Wm=function(){function e(){}return e.getOrigin=function(t){var i=e._link;return i?(i.href=t,i.href=i.href,i.protocol+i.hostname+i.port):"about:blank"},e.isSameOrigin=function(t){return e.getOrigin(t)===e._origin},e.setContext=function(t){e._link=t.document.createElement("a"),e._origin=e.getOrigin(t.location.href)},e._origin="about:blank",e}(),Km=function(){function e(e,t){this.context=e,this._options=t,this._cache={}}return e.prototype.addImage=function(e){var t=Promise.resolve();return this.has(e)?t:e_(e)||Zm(e)?((this._cache[e]=this.loadImage(e)).catch((function(){})),t):t},e.prototype.match=function(e){return this._cache[e]},e.prototype.loadImage=function(e){return Yc(this,void 0,void 0,(function(){var t,i,s,r,o=this;return Zc(this,(function(n){switch(n.label){case 0:return t=Wm.isSameOrigin(e),i=!qm(e)&&!0===this._options.useCORS&&Cg.SUPPORT_CORS_IMAGES&&!t,s=!qm(e)&&!t&&!e_(e)&&"string"==typeof this._options.proxy&&Cg.SUPPORT_CORS_XHR&&!i,t||!1!==this._options.allowTaint||qm(e)||e_(e)||s||i?(r=e,s?[4,this.proxy(r)]:[3,2]):[2];case 1:r=n.sent(),n.label=2;case 2:return this.context.logger.debug("Added image "+e.substring(0,256)),[4,new Promise((function(e,t){var s=new Image;s.onload=function(){return e(s)},s.onerror=t,($m(r)||i)&&(s.crossOrigin="anonymous"),s.src=r,!0===s.complete&&setTimeout((function(){return e(s)}),500),o._options.imageTimeout>0&&setTimeout((function(){return t("Timed out ("+o._options.imageTimeout+"ms) loading image")}),o._options.imageTimeout)}))];case 3:return[2,n.sent()]}}))}))},e.prototype.has=function(e){return void 0!==this._cache[e]},e.prototype.keys=function(){return Promise.resolve(Object.keys(this._cache))},e.prototype.proxy=function(e){var t=this,i=this._options.proxy;if(!i)throw new Error("No proxy defined");var s=e.substring(0,256);return new Promise((function(r,o){var n=Cg.SUPPORT_RESPONSE_TYPE?"blob":"text",a=new XMLHttpRequest;a.onload=function(){if(200===a.status)if("text"===n)r(a.response);else{var e=new FileReader;e.addEventListener("load",(function(){return r(e.result)}),!1),e.addEventListener("error",(function(e){return o(e)}),!1),e.readAsDataURL(a.response)}else o("Failed to proxy resource "+s+" with status code "+a.status)},a.onerror=o;var l=i.indexOf("?")>-1?"&":"?";if(a.open("GET",""+i+l+"url="+encodeURIComponent(e)+"&responseType="+n),"text"!==n&&a instanceof XMLHttpRequest&&(a.responseType=n),t._options.imageTimeout){var A=t._options.imageTimeout;a.timeout=A,a.ontimeout=function(){return o("Timed out ("+A+"ms) proxying "+s)}}a.send()}))},e}(),Xm=/^data:image\/svg\+xml/i,Jm=/^data:image\/.*;base64,/i,Ym=/^data:image\/.*/i,Zm=function(e){return Cg.SUPPORT_SVG_DRAWING||!t_(e)},qm=function(e){return Ym.test(e)},$m=function(e){return Jm.test(e)},e_=function(e){return"blob"===e.substr(0,4)},t_=function(e){return"svg"===e.substr(-3).toLowerCase()||Xm.test(e)},i_=function(){function e(e,t){this.type=0,this.x=e,this.y=t}return e.prototype.add=function(t,i){return new e(this.x+t,this.y+i)},e}(),s_=function(e,t,i){return new i_(e.x+(t.x-e.x)*i,e.y+(t.y-e.y)*i)},r_=function(){function e(e,t,i,s){this.type=1,this.start=e,this.startControl=t,this.endControl=i,this.end=s}return e.prototype.subdivide=function(t,i){var s=s_(this.start,this.startControl,t),r=s_(this.startControl,this.endControl,t),o=s_(this.endControl,this.end,t),n=s_(s,r,t),a=s_(r,o,t),l=s_(n,a,t);return i?new e(this.start,s,n,l):new e(l,a,o,this.end)},e.prototype.add=function(t,i){return new e(this.start.add(t,i),this.startControl.add(t,i),this.endControl.add(t,i),this.end.add(t,i))},e.prototype.reverse=function(){return new e(this.end,this.endControl,this.startControl,this.start)},e}(),o_=function(e){return 1===e.type},n_=function(e){var t=e.styles,i=e.bounds,s=Wd(t.borderTopLeftRadius,i.width,i.height),r=s[0],o=s[1],n=Wd(t.borderTopRightRadius,i.width,i.height),a=n[0],l=n[1],A=Wd(t.borderBottomRightRadius,i.width,i.height),h=A[0],c=A[1],u=Wd(t.borderBottomLeftRadius,i.width,i.height),d=u[0],p=u[1],f=[];f.push((r+a)/i.width),f.push((d+h)/i.width),f.push((o+p)/i.height),f.push((l+c)/i.height);var g=Math.max.apply(Math,f);g>1&&(r/=g,o/=g,a/=g,l/=g,h/=g,c/=g,d/=g,p/=g);var m=i.width-a,_=i.height-c,v=i.width-h,b=i.height-p,y=t.borderTopWidth,x=t.borderRightWidth,B=t.borderBottomWidth,w=t.borderLeftWidth,P=Kd(t.paddingTop,e.bounds.width),C=Kd(t.paddingRight,e.bounds.width),M=Kd(t.paddingBottom,e.bounds.width),E=Kd(t.paddingLeft,e.bounds.width);this.topLeftBorderDoubleOuterBox=r>0||o>0?a_(i.left+w/3,i.top+y/3,r-w/3,o-y/3,Sm.TOP_LEFT):new i_(i.left+w/3,i.top+y/3),this.topRightBorderDoubleOuterBox=r>0||o>0?a_(i.left+m,i.top+y/3,a-x/3,l-y/3,Sm.TOP_RIGHT):new i_(i.left+i.width-x/3,i.top+y/3),this.bottomRightBorderDoubleOuterBox=h>0||c>0?a_(i.left+v,i.top+_,h-x/3,c-B/3,Sm.BOTTOM_RIGHT):new i_(i.left+i.width-x/3,i.top+i.height-B/3),this.bottomLeftBorderDoubleOuterBox=d>0||p>0?a_(i.left+w/3,i.top+b,d-w/3,p-B/3,Sm.BOTTOM_LEFT):new i_(i.left+w/3,i.top+i.height-B/3),this.topLeftBorderDoubleInnerBox=r>0||o>0?a_(i.left+2*w/3,i.top+2*y/3,r-2*w/3,o-2*y/3,Sm.TOP_LEFT):new i_(i.left+2*w/3,i.top+2*y/3),this.topRightBorderDoubleInnerBox=r>0||o>0?a_(i.left+m,i.top+2*y/3,a-2*x/3,l-2*y/3,Sm.TOP_RIGHT):new i_(i.left+i.width-2*x/3,i.top+2*y/3),this.bottomRightBorderDoubleInnerBox=h>0||c>0?a_(i.left+v,i.top+_,h-2*x/3,c-2*B/3,Sm.BOTTOM_RIGHT):new i_(i.left+i.width-2*x/3,i.top+i.height-2*B/3),this.bottomLeftBorderDoubleInnerBox=d>0||p>0?a_(i.left+2*w/3,i.top+b,d-2*w/3,p-2*B/3,Sm.BOTTOM_LEFT):new i_(i.left+2*w/3,i.top+i.height-2*B/3),this.topLeftBorderStroke=r>0||o>0?a_(i.left+w/2,i.top+y/2,r-w/2,o-y/2,Sm.TOP_LEFT):new i_(i.left+w/2,i.top+y/2),this.topRightBorderStroke=r>0||o>0?a_(i.left+m,i.top+y/2,a-x/2,l-y/2,Sm.TOP_RIGHT):new i_(i.left+i.width-x/2,i.top+y/2),this.bottomRightBorderStroke=h>0||c>0?a_(i.left+v,i.top+_,h-x/2,c-B/2,Sm.BOTTOM_RIGHT):new i_(i.left+i.width-x/2,i.top+i.height-B/2),this.bottomLeftBorderStroke=d>0||p>0?a_(i.left+w/2,i.top+b,d-w/2,p-B/2,Sm.BOTTOM_LEFT):new i_(i.left+w/2,i.top+i.height-B/2),this.topLeftBorderBox=r>0||o>0?a_(i.left,i.top,r,o,Sm.TOP_LEFT):new i_(i.left,i.top),this.topRightBorderBox=a>0||l>0?a_(i.left+m,i.top,a,l,Sm.TOP_RIGHT):new i_(i.left+i.width,i.top),this.bottomRightBorderBox=h>0||c>0?a_(i.left+v,i.top+_,h,c,Sm.BOTTOM_RIGHT):new i_(i.left+i.width,i.top+i.height),this.bottomLeftBorderBox=d>0||p>0?a_(i.left,i.top+b,d,p,Sm.BOTTOM_LEFT):new i_(i.left,i.top+i.height),this.topLeftPaddingBox=r>0||o>0?a_(i.left+w,i.top+y,Math.max(0,r-w),Math.max(0,o-y),Sm.TOP_LEFT):new i_(i.left+w,i.top+y),this.topRightPaddingBox=a>0||l>0?a_(i.left+Math.min(m,i.width-x),i.top+y,m>i.width+x?0:Math.max(0,a-x),Math.max(0,l-y),Sm.TOP_RIGHT):new i_(i.left+i.width-x,i.top+y),this.bottomRightPaddingBox=h>0||c>0?a_(i.left+Math.min(v,i.width-w),i.top+Math.min(_,i.height-B),Math.max(0,h-x),Math.max(0,c-B),Sm.BOTTOM_RIGHT):new i_(i.left+i.width-x,i.top+i.height-B),this.bottomLeftPaddingBox=d>0||p>0?a_(i.left+w,i.top+Math.min(b,i.height-B),Math.max(0,d-w),Math.max(0,p-B),Sm.BOTTOM_LEFT):new i_(i.left+w,i.top+i.height-B),this.topLeftContentBox=r>0||o>0?a_(i.left+w+E,i.top+y+P,Math.max(0,r-(w+E)),Math.max(0,o-(y+P)),Sm.TOP_LEFT):new i_(i.left+w+E,i.top+y+P),this.topRightContentBox=a>0||l>0?a_(i.left+Math.min(m,i.width+w+E),i.top+y+P,m>i.width+w+E?0:a-w+E,l-(y+P),Sm.TOP_RIGHT):new i_(i.left+i.width-(x+C),i.top+y+P),this.bottomRightContentBox=h>0||c>0?a_(i.left+Math.min(v,i.width-(w+E)),i.top+Math.min(_,i.height+y+P),Math.max(0,h-(x+C)),c-(B+M),Sm.BOTTOM_RIGHT):new i_(i.left+i.width-(x+C),i.top+i.height-(B+M)),this.bottomLeftContentBox=d>0||p>0?a_(i.left+w+E,i.top+b,Math.max(0,d-(w+E)),p-(B+M),Sm.BOTTOM_LEFT):new i_(i.left+w+E,i.top+i.height-(B+M))};!function(e){e[e.TOP_LEFT=0]="TOP_LEFT",e[e.TOP_RIGHT=1]="TOP_RIGHT",e[e.BOTTOM_RIGHT=2]="BOTTOM_RIGHT",e[e.BOTTOM_LEFT=3]="BOTTOM_LEFT"}(Sm||(Sm={}));var a_=function(e,t,i,s,r){var o=(Math.sqrt(2)-1)/3*4,n=i*o,a=s*o,l=e+i,A=t+s;switch(r){case Sm.TOP_LEFT:return new r_(new i_(e,A),new i_(e,A-a),new i_(l-n,t),new i_(l,t));case Sm.TOP_RIGHT:return new r_(new i_(e,t),new i_(e+n,t),new i_(l,A-a),new i_(l,A));case Sm.BOTTOM_RIGHT:return new r_(new i_(l,t),new i_(l,t+a),new i_(e+n,A),new i_(e,A));case Sm.BOTTOM_LEFT:default:return new r_(new i_(l,A),new i_(l-n,A),new i_(e,t+a),new i_(e,t))}},l_=function(e){return[e.topLeftBorderBox,e.topRightBorderBox,e.bottomRightBorderBox,e.bottomLeftBorderBox]},A_=function(e){return[e.topLeftPaddingBox,e.topRightPaddingBox,e.bottomRightPaddingBox,e.bottomLeftPaddingBox]},h_=function(e,t,i){this.offsetX=e,this.offsetY=t,this.matrix=i,this.type=0,this.target=6},c_=function(e,t){this.path=e,this.target=t,this.type=1},u_=function(e){this.opacity=e,this.type=2,this.target=6},d_=function(e){return 1===e.type},p_=function(e,t){return e.length===t.length&&e.some((function(e,i){return e===t[i]}))},f_=function(e){this.element=e,this.inlineLevel=[],this.nonInlineLevel=[],this.negativeZIndex=[],this.zeroOrAutoZIndexOrTransformedOrOpacity=[],this.positiveZIndex=[],this.nonPositionedFloats=[],this.nonPositionedInlineLevel=[]},g_=function(){function e(e,t){if(this.container=e,this.parent=t,this.effects=[],this.curves=new n_(this.container),this.container.styles.opacity<1&&this.effects.push(new u_(this.container.styles.opacity)),null!==this.container.styles.transform){var i=this.container.bounds.left+this.container.styles.transformOrigin[0].number,s=this.container.bounds.top+this.container.styles.transformOrigin[1].number,r=this.container.styles.transform;this.effects.push(new h_(i,s,r))}if(0!==this.container.styles.overflowX){var o=l_(this.curves),n=A_(this.curves);p_(o,n)?this.effects.push(new c_(o,6)):(this.effects.push(new c_(o,2)),this.effects.push(new c_(n,4)))}}return e.prototype.getEffects=function(e){for(var t=-1===[2,3].indexOf(this.container.styles.position),i=this.parent,s=this.effects.slice(0);i;){var r=i.effects.filter((function(e){return!d_(e)}));if(t||0!==i.container.styles.position||!i.parent){if(s.unshift.apply(s,r),t=-1===[2,3].indexOf(i.container.styles.position),0!==i.container.styles.overflowX){var o=l_(i.curves),n=A_(i.curves);p_(o,n)||s.unshift(new c_(n,6))}}else s.unshift.apply(s,r);i=i.parent}return s.filter((function(t){return Hf(t.target,e)}))},e}(),m_=function(e,t,i,s){e.container.elements.forEach((function(r){var o=Hf(r.flags,4),n=Hf(r.flags,2),a=new g_(r,e);Hf(r.styles.display,2048)&&s.push(a);var l=Hf(r.flags,8)?[]:s;if(o||n){var A=o||r.styles.isPositioned()?i:t,h=new f_(a);if(r.styles.isPositioned()||r.styles.opacity<1||r.styles.isTransformed()){var c=r.styles.zIndex.order;if(c<0){var u=0;A.negativeZIndex.some((function(e,t){return c>e.element.container.styles.zIndex.order?(u=t,!1):u>0})),A.negativeZIndex.splice(u,0,h)}else if(c>0){var d=0;A.positiveZIndex.some((function(e,t){return c>=e.element.container.styles.zIndex.order?(d=t+1,!1):d>0})),A.positiveZIndex.splice(d,0,h)}else A.zeroOrAutoZIndexOrTransformedOrOpacity.push(h)}else r.styles.isFloating()?A.nonPositionedFloats.push(h):A.nonPositionedInlineLevel.push(h);m_(a,h,o?h:i,l)}else r.styles.isInlineLevel()?t.inlineLevel.push(a):t.nonInlineLevel.push(a),m_(a,t,i,l);Hf(r.flags,8)&&__(r,l)}))},__=function(e,t){for(var i=e instanceof Hg?e.start:1,s=e instanceof Hg&&e.reversed,r=0;r0&&e.intrinsicHeight>0){var s=B_(e),r=A_(t);this.path(r),this.ctx.save(),this.ctx.clip(),this.ctx.drawImage(i,0,0,e.intrinsicWidth,e.intrinsicHeight,s.left,s.top,s.width,s.height),this.ctx.restore()}},t.prototype.renderNodeContent=function(e){return Yc(this,void 0,void 0,(function(){var i,s,r,o,n,a,l,A,h,c,u,d,p,f,g,m,_,v;return Zc(this,(function(b){switch(b.label){case 0:this.applyEffects(e.getEffects(4)),i=e.container,s=e.curves,r=i.styles,o=0,n=i.textNodes,b.label=1;case 1:return o0&&B>0&&(m=s.ctx.createPattern(p,"repeat"),s.renderRepeat(v,m,P,C))):function(e){return 2===e.type}(i)&&(_=w_(e,t,[null,null,null]),v=_[0],b=_[1],y=_[2],x=_[3],B=_[4],w=0===i.position.length?[Gd]:i.position,P=Kd(w[0],x),C=Kd(w[w.length-1],B),M=function(e,t,i,s,r){var o=0,n=0;switch(e.size){case 0:0===e.shape?o=n=Math.min(Math.abs(t),Math.abs(t-s),Math.abs(i),Math.abs(i-r)):1===e.shape&&(o=Math.min(Math.abs(t),Math.abs(t-s)),n=Math.min(Math.abs(i),Math.abs(i-r)));break;case 2:if(0===e.shape)o=n=Math.min(pp(t,i),pp(t,i-r),pp(t-s,i),pp(t-s,i-r));else if(1===e.shape){var a=Math.min(Math.abs(i),Math.abs(i-r))/Math.min(Math.abs(t),Math.abs(t-s)),l=fp(s,r,t,i,!0),A=l[0],h=l[1];n=a*(o=pp(A-t,(h-i)/a))}break;case 1:0===e.shape?o=n=Math.max(Math.abs(t),Math.abs(t-s),Math.abs(i),Math.abs(i-r)):1===e.shape&&(o=Math.max(Math.abs(t),Math.abs(t-s)),n=Math.max(Math.abs(i),Math.abs(i-r)));break;case 3:if(0===e.shape)o=n=Math.max(pp(t,i),pp(t,i-r),pp(t-s,i),pp(t-s,i-r));else if(1===e.shape){a=Math.max(Math.abs(i),Math.abs(i-r))/Math.max(Math.abs(t),Math.abs(t-s));var c=fp(s,r,t,i,!1);A=c[0],h=c[1],n=a*(o=pp(A-t,(h-i)/a))}}return Array.isArray(e.size)&&(o=Kd(e.size[0],s),n=2===e.size.length?Kd(e.size[1],r):o),[o,n]}(i,P,C,x,B),E=M[0],F=M[1],E>0&&F>0&&(I=s.ctx.createRadialGradient(b+P,y+C,0,b+P,y+C,E),up(i.stops,2*E).forEach((function(e){return I.addColorStop(e.stop,ep(e.color))})),s.path(v),s.ctx.fillStyle=I,E!==F?(D=e.bounds.left+.5*e.bounds.width,S=e.bounds.top+.5*e.bounds.height,R=1/(T=F/E),s.ctx.save(),s.ctx.translate(D,S),s.ctx.transform(1,0,0,T,0,0),s.ctx.translate(-D,-S),s.ctx.fillRect(b,R*(y-S)+S,x,B*R),s.ctx.restore()):s.ctx.fill())),L.label=6;case 6:return t--,[2]}}))},s=this,r=0,o=e.styles.backgroundImage.slice(0).reverse(),a.label=1;case 1:return r0?2!==l.style?[3,5]:[4,this.renderDashedDottedBorder(l.color,l.width,o,e.curves,2)]:[3,11]:[3,13];case 4:return h.sent(),[3,11];case 5:return 3!==l.style?[3,7]:[4,this.renderDashedDottedBorder(l.color,l.width,o,e.curves,3)];case 6:return h.sent(),[3,11];case 7:return 4!==l.style?[3,9]:[4,this.renderDoubleBorder(l.color,l.width,o,e.curves)];case 8:return h.sent(),[3,11];case 9:return[4,this.renderSolidBorder(l.color,o,e.curves)];case 10:h.sent(),h.label=11;case 11:o++,h.label=12;case 12:return n++,[3,3];case 13:return[2]}}))}))},t.prototype.renderDashedDottedBorder=function(e,t,i,s,r){return Yc(this,void 0,void 0,(function(){var o,n,a,l,A,h,c,u,d,p,f,g,m,_,v,b;return Zc(this,(function(y){return this.ctx.save(),o=function(e,t){switch(t){case 0:return b_(e.topLeftBorderStroke,e.topRightBorderStroke);case 1:return b_(e.topRightBorderStroke,e.bottomRightBorderStroke);case 2:return b_(e.bottomRightBorderStroke,e.bottomLeftBorderStroke);default:return b_(e.bottomLeftBorderStroke,e.topLeftBorderStroke)}}(s,i),n=v_(s,i),2===r&&(this.path(n),this.ctx.clip()),o_(n[0])?(a=n[0].start.x,l=n[0].start.y):(a=n[0].x,l=n[0].y),o_(n[1])?(A=n[1].end.x,h=n[1].end.y):(A=n[1].x,h=n[1].y),c=0===i||2===i?Math.abs(a-A):Math.abs(l-h),this.ctx.beginPath(),3===r?this.formatPath(o):this.formatPath(n.slice(0,2)),u=t<3?3*t:2*t,d=t<3?2*t:t,3===r&&(u=t,d=t),p=!0,c<=2*u?p=!1:c<=2*u+d?(u*=f=c/(2*u+d),d*=f):(g=Math.floor((c+d)/(u+d)),m=(c-g*u)/(g-1),d=(_=(c-(g+1)*u)/g)<=0||Math.abs(d-m){})),tv(this,"_reject",(()=>{})),this.name=e,this.workerThread=t,this.result=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}postMessage(e,t){this.workerThread.postMessage({source:"loaders.gl",type:e,payload:t})}done(e){X_(this.isRunning),this.isRunning=!1,this._resolve(e)}error(e){X_(this.isRunning),this.isRunning=!1,this._reject(e)}}class sv{}const rv=new Map;function ov(e){X_(e.source&&!e.url||!e.source&&e.url);let t=rv.get(e.source||e.url);return t||(e.url&&(t=function(e){if(!e.startsWith("http"))return e;return nv((t=e,"try {\n importScripts('".concat(t,"');\n} catch (error) {\n console.error(error);\n throw error;\n}")));var t}(e.url),rv.set(e.url,t)),e.source&&(t=nv(e.source),rv.set(e.source,t))),X_(t),t}function nv(e){const t=new Blob([e],{type:"application/javascript"});return URL.createObjectURL(t)}function av(e,t=!0,i){const s=i||new Set;if(e){if(lv(e))s.add(e);else if(lv(e.buffer))s.add(e.buffer);else if(ArrayBuffer.isView(e));else if(t&&"object"==typeof e)for(const i in e)av(e[i],t,s)}else;return void 0===i?Array.from(s):[]}function lv(e){return!!e&&(e instanceof ArrayBuffer||("undefined"!=typeof MessagePort&&e instanceof MessagePort||("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)))}const Av=()=>{};class hv{static isSupported(){return"undefined"!=typeof Worker&&Z_||void 0!==typeof sv}constructor(e){tv(this,"name",void 0),tv(this,"source",void 0),tv(this,"url",void 0),tv(this,"terminated",!1),tv(this,"worker",void 0),tv(this,"onMessage",void 0),tv(this,"onError",void 0),tv(this,"_loadableURL","");const{name:t,source:i,url:s}=e;X_(i||s),this.name=t,this.source=i,this.url=s,this.onMessage=Av,this.onError=e=>console.log(e),this.worker=Z_?this._createBrowserWorker():this._createNodeWorker()}destroy(){this.onMessage=Av,this.onError=Av,this.worker.terminate(),this.terminated=!0}get isRunning(){return Boolean(this.onMessage)}postMessage(e,t){t=t||av(e),this.worker.postMessage(e,t)}_getErrorFromErrorEvent(e){let t="Failed to load ";return t+="worker ".concat(this.name," from ").concat(this.url,". "),e.message&&(t+="".concat(e.message," in ")),e.lineno&&(t+=":".concat(e.lineno,":").concat(e.colno)),new Error(t)}_createBrowserWorker(){this._loadableURL=ov({source:this.source,url:this.url});const e=new Worker(this._loadableURL,{name:this.name});return e.onmessage=e=>{e.data?this.onMessage(e.data):this.onError(new Error("No data received"))},e.onerror=e=>{this.onError(this._getErrorFromErrorEvent(e)),this.terminated=!0},e.onmessageerror=e=>console.error(e),e}_createNodeWorker(){let e;if(this.url){const t=this.url.includes(":/")||this.url.startsWith("/")?this.url:"./".concat(this.url);e=new sv(t,{eval:!1})}else{if(!this.source)throw new Error("no worker");e=new sv(this.source,{eval:!0})}return e.on("message",(e=>{this.onMessage(e)})),e.on("error",(e=>{this.onError(e)})),e.on("exit",(e=>{})),e}}class cv{static isSupported(){return hv.isSupported()}constructor(e){tv(this,"name","unnamed"),tv(this,"source",void 0),tv(this,"url",void 0),tv(this,"maxConcurrency",1),tv(this,"maxMobileConcurrency",1),tv(this,"onDebug",(()=>{})),tv(this,"reuseWorkers",!0),tv(this,"props",{}),tv(this,"jobQueue",[]),tv(this,"idleQueue",[]),tv(this,"count",0),tv(this,"isDestroyed",!1),this.source=e.source,this.url=e.url,this.setProps(e)}destroy(){this.idleQueue.forEach((e=>e.destroy())),this.isDestroyed=!0}setProps(e){this.props={...this.props,...e},void 0!==e.name&&(this.name=e.name),void 0!==e.maxConcurrency&&(this.maxConcurrency=e.maxConcurrency),void 0!==e.maxMobileConcurrency&&(this.maxMobileConcurrency=e.maxMobileConcurrency),void 0!==e.reuseWorkers&&(this.reuseWorkers=e.reuseWorkers),void 0!==e.onDebug&&(this.onDebug=e.onDebug)}async startJob(e,t=((e,t,i)=>e.done(i)),i=((e,t)=>e.error(t))){const s=new Promise((s=>(this.jobQueue.push({name:e,onMessage:t,onError:i,onStart:s}),this)));return this._startQueuedJob(),await s}async _startQueuedJob(){if(!this.jobQueue.length)return;const e=this._getAvailableWorker();if(!e)return;const t=this.jobQueue.shift();if(t){this.onDebug({message:"Starting job",name:t.name,workerThread:e,backlog:this.jobQueue.length});const i=new iv(t.name,e);e.onMessage=e=>t.onMessage(i,e.type,e.payload),e.onError=e=>t.onError(i,e),t.onStart(i);try{await i.result}finally{this.returnWorkerToQueue(e)}}}returnWorkerToQueue(e){this.isDestroyed||!this.reuseWorkers||this.count>this._getMaxConcurrency()?(e.destroy(),this.count--):this.idleQueue.push(e),this.isDestroyed||this._startQueuedJob()}_getAvailableWorker(){if(this.idleQueue.length>0)return this.idleQueue.shift()||null;if(this.count{}};class dv{static isSupported(){return hv.isSupported()}static getWorkerFarm(e={}){return dv._workerFarm=dv._workerFarm||new dv({}),dv._workerFarm.setProps(e),dv._workerFarm}constructor(e){tv(this,"props",void 0),tv(this,"workerPools",new Map),this.props={...uv},this.setProps(e),this.workerPools=new Map}destroy(){for(const e of this.workerPools.values())e.destroy();this.workerPools=new Map}setProps(e){this.props={...this.props,...e};for(const e of this.workerPools.values())e.setProps(this._getWorkerPoolProps())}getWorkerPool(e){const{name:t,source:i,url:s}=e;let r=this.workerPools.get(t);return r||(r=new cv({name:t,source:i,url:s}),r.setProps(this._getWorkerPoolProps()),this.workerPools.set(t,r)),r}_getWorkerPoolProps(){return{maxConcurrency:this.props.maxConcurrency,maxMobileConcurrency:this.props.maxMobileConcurrency,reuseWorkers:this.props.reuseWorkers,onDebug:this.props.onDebug}}}tv(dv,"_workerFarm",void 0);var pv=Object.freeze({__proto__:null,default:{}});const fv={};async function gv(e,t=null,i={}){return t&&(e=function(e,t,i){if(e.startsWith("http"))return e;const s=i.modules||{};if(s[e])return s[e];if(!Z_)return"modules/".concat(t,"/dist/libs/").concat(e);if(i.CDN)return X_(i.CDN.startsWith("http")),"".concat(i.CDN,"/").concat(t,"@").concat("3.2.6","/dist/libs/").concat(e);if(q_)return"../src/libs/".concat(e);return"modules/".concat(t,"/src/libs/").concat(e)}(e,t,i)),fv[e]=fv[e]||async function(e){if(e.endsWith("wasm")){const t=await fetch(e);return await t.arrayBuffer()}if(!Z_)try{return pv&&void 0}catch{return null}if(q_)return importScripts(e);const t=await fetch(e);return function(e,t){if(!Z_)return;if(q_)return eval.call(Y_,e),null;const i=document.createElement("script");i.id=t;try{i.appendChild(document.createTextNode(e))}catch(t){i.text=e}return document.body.appendChild(i),null}(await t.text(),e)}(e),await fv[e]}async function mv(e,t,i,s,r){const o=e.id,n=function(e,t={}){const i=t[e.id]||{},s="".concat(e.id,"-worker.js");let r=i.workerUrl;if(r||"compression"!==e.id||(r=t.workerUrl),"test"===t._workerType&&(r="modules/".concat(e.module,"/dist/").concat(s)),!r){let t=e.version;"latest"===t&&(t="latest");const i=t?"@".concat(t):"";r="https://unpkg.com/@loaders.gl/".concat(e.module).concat(i,"/dist/").concat(s)}return X_(r),r}(e,i),a=dv.getWorkerFarm(i).getWorkerPool({name:o,url:n});i=JSON.parse(JSON.stringify(i)),s=JSON.parse(JSON.stringify(s||{}));const l=await a.startJob("process-on-worker",_v.bind(null,r));l.postMessage("process",{input:t,options:i,context:s});const A=await l.result;return await A.result}async function _v(e,t,i,s){switch(i){case"done":t.done(s);break;case"error":t.error(new Error(s.error));break;case"process":const{id:r,input:o,options:n}=s;try{const i=await e(o,n);t.postMessage("done",{id:r,result:i})}catch(e){const i=e instanceof Error?e.message:"unknown error";t.postMessage("error",{id:r,error:i})}break;default:console.warn("parse-with-worker unknown message ".concat(i))}}function vv(e,t,i){if(e.byteLength<=t+i)return"";const s=new DataView(e);let r="";for(let e=0;e=0),z_(t>0),e+(t-1)&~(t-1)}function Pv(e,t,i){let s;if(e instanceof ArrayBuffer)s=new Uint8Array(e);else{const t=e.byteOffset,i=e.byteLength;s=new Uint8Array(e.buffer||e.arrayBuffer,t,i)}return t.set(s,i),i+wv(s.byteLength,4)}async function Cv(e){const t=[];for await(const i of e)t.push(i);return function(...e){const t=e.map((e=>e instanceof ArrayBuffer?new Uint8Array(e):e)),i=t.reduce(((e,t)=>e+t.byteLength),0),s=new Uint8Array(i);let r=0;for(const e of t)s.set(e,r),r+=e.byteLength;return s.buffer}(...t)}const Mv={};const Ev=e=>"function"==typeof e,Fv=e=>null!==e&&"object"==typeof e,Iv=e=>Fv(e)&&e.constructor==={}.constructor,Dv=e=>"undefined"!=typeof Response&&e instanceof Response||e&&e.arrayBuffer&&e.text&&e.json,Sv=e=>"undefined"!=typeof Blob&&e instanceof Blob,Tv=e=>(e=>"undefined"!=typeof ReadableStream&&e instanceof ReadableStream||Fv(e)&&Ev(e.tee)&&Ev(e.cancel)&&Ev(e.getReader))(e)||(e=>Fv(e)&&Ev(e.read)&&Ev(e.pipe)&&(e=>"boolean"==typeof e)(e.readable))(e),Rv=/^data:([-\w.]+\/[-\w.+]+)(;|,)/,Lv=/^([-\w.]+\/[-\w.+]+)/;function Uv(e){const t=Lv.exec(e);return t?t[1]:e}function Ov(e){const t=Rv.exec(e);return t?t[1]:""}const kv=/\?.*/;function Nv(e){if(Dv(e)){const t=Qv(e.url||"");return{url:t,type:Uv(e.headers.get("content-type")||"")||Ov(t)}}return Sv(e)?{url:Qv(e.name||""),type:e.type||""}:"string"==typeof e?{url:Qv(e),type:Ov(e)}:{url:"",type:""}}function Qv(e){return e.replace(kv,"")}async function Vv(e){if(Dv(e))return e;const t={},i=function(e){return Dv(e)?e.headers["content-length"]||-1:Sv(e)?e.size:"string"==typeof e?e.length:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:-1}(e);i>=0&&(t["content-length"]=String(i));const{url:s,type:r}=Nv(e);r&&(t["content-type"]=r);const o=await async function(e){const t=5;if("string"==typeof e)return"data:,".concat(e.slice(0,t));if(e instanceof Blob){const t=e.slice(0,5);return await new Promise((e=>{const i=new FileReader;i.onload=t=>{var i;return e(null==t||null===(i=t.target)||void 0===i?void 0:i.result)},i.readAsDataURL(t)}))}if(e instanceof ArrayBuffer){const i=function(e){let t="";const i=new Uint8Array(e);for(let e=0;e=0)}();class Xv{constructor(e,t,i="sessionStorage"){this.storage=function(e){try{const t=window[e],i="__storage_test__";return t.setItem(i,i),t.removeItem(i),t}catch(e){return null}}(i),this.id=e,this.config={},Object.assign(this.config,t),this._loadConfiguration()}getConfiguration(){return this.config}setConfiguration(e){return this.config={},this.updateConfiguration(e)}updateConfiguration(e){if(Object.assign(this.config,e),this.storage){const e=JSON.stringify(this.config);this.storage.setItem(this.id,e)}return this}_loadConfiguration(){let e={};if(this.storage){const t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}}function Jv(e,t,i,s=600){const r=e.src.replace(/\(/g,"%28").replace(/\)/g,"%29");e.width>s&&(i=Math.min(i,s/e.width));const o=e.width*i,n=e.height*i,a=["font-size:1px;","padding:".concat(Math.floor(n/2),"px ").concat(Math.floor(o/2),"px;"),"line-height:".concat(n,"px;"),"background:url(".concat(r,");"),"background-size:".concat(o,"px ").concat(n,"px;"),"color:transparent;"].join("");return["".concat(t," %c+"),a]}const Yv={BLACK:30,RED:31,GREEN:32,YELLOW:33,BLUE:34,MAGENTA:35,CYAN:36,WHITE:37,BRIGHT_BLACK:90,BRIGHT_RED:91,BRIGHT_GREEN:92,BRIGHT_YELLOW:93,BRIGHT_BLUE:94,BRIGHT_MAGENTA:95,BRIGHT_CYAN:96,BRIGHT_WHITE:97};function Zv(e){return"string"==typeof e?Yv[e.toUpperCase()]||Yv.WHITE:e}function qv(e,t){if(!e)throw new Error(t||"Assertion failed")}function $v(){let e;if(Kv&&Gv.performance)e=Gv.performance.now();else if(zv.hrtime){const t=zv.hrtime();e=1e3*t[0]+t[1]/1e6}else e=Date.now();return e}const eb={debug:Kv&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},tb={enabled:!0,level:0};function ib(){}const sb={},rb={once:!0};function ob(e){for(const t in e)for(const i in e[t])return i||"untitled";return"empty"}class nb{constructor({id:e}={id:""}){this.id=e,this.VERSION=Wv,this._startTs=$v(),this._deltaTs=$v(),this.LOG_THROTTLE_TIMEOUT=0,this._storage=new Xv("__probe-".concat(this.id,"__"),tb),this.userData={},this.timeStamp("".concat(this.id," started")),function(e,t=["constructor"]){const i=Object.getPrototypeOf(e),s=Object.getOwnPropertyNames(i);for(const i of s)"function"==typeof e[i]&&(t.find((e=>i===e))||(e[i]=e[i].bind(e)))}(this),Object.seal(this)}set level(e){this.setLevel(e)}get level(){return this.getLevel()}isEnabled(){return this._storage.config.enabled}getLevel(){return this._storage.config.level}getTotal(){return Number(($v()-this._startTs).toPrecision(10))}getDelta(){return Number(($v()-this._deltaTs).toPrecision(10))}set priority(e){this.level=e}get priority(){return this.level}getPriority(){return this.level}enable(e=!0){return this._storage.updateConfiguration({enabled:e}),this}setLevel(e){return this._storage.updateConfiguration({level:e}),this}assert(e,t){qv(e,t)}warn(e){return this._getLogFunction(0,e,eb.warn,arguments,rb)}error(e){return this._getLogFunction(0,e,eb.error,arguments)}deprecated(e,t){return this.warn("`".concat(e,"` is deprecated and will be removed in a later version. Use `").concat(t,"` instead"))}removed(e,t){return this.error("`".concat(e,"` has been removed. Use `").concat(t,"` instead"))}probe(e,t){return this._getLogFunction(e,t,eb.log,arguments,{time:!0,once:!0})}log(e,t){return this._getLogFunction(e,t,eb.debug,arguments)}info(e,t){return this._getLogFunction(e,t,console.info,arguments)}once(e,t){return this._getLogFunction(e,t,eb.debug||eb.info,arguments,rb)}table(e,t,i){return t?this._getLogFunction(e,t,console.table||ib,i&&[i],{tag:ob(t)}):ib}image({logLevel:e,priority:t,image:i,message:s="",scale:r=1}){return this._shouldLog(e||t)?Kv?function({image:e,message:t="",scale:i=1}){if("string"==typeof e){const s=new Image;return s.onload=()=>{const e=Jv(s,t,i);console.log(...e)},s.src=e,ib}const s=e.nodeName||"";if("img"===s.toLowerCase())return console.log(...Jv(e,t,i)),ib;if("canvas"===s.toLowerCase()){const s=new Image;return s.onload=()=>console.log(...Jv(s,t,i)),s.src=e.toDataURL(),ib}return ib}({image:i,message:s,scale:r}):function({image:e,message:t="",scale:i=1}){let s=null;try{s=module.require("asciify-image")}catch(e){}if(s)return()=>s(e,{fit:"box",width:"".concat(Math.round(80*i),"%")}).then((e=>console.log(e)));return ib}({image:i,message:s,scale:r}):ib}settings(){console.table?console.table(this._storage.config):console.log(this._storage.config)}get(e){return this._storage.config[e]}set(e,t){this._storage.updateConfiguration({[e]:t})}time(e,t){return this._getLogFunction(e,t,console.time?console.time:console.info)}timeEnd(e,t){return this._getLogFunction(e,t,console.timeEnd?console.timeEnd:console.info)}timeStamp(e,t){return this._getLogFunction(e,t,console.timeStamp||ib)}group(e,t,i={collapsed:!1}){i=lb({logLevel:e,message:t,opts:i});const{collapsed:s}=i;return i.method=(s?console.groupCollapsed:console.group)||console.info,this._getLogFunction(i)}groupCollapsed(e,t,i={}){return this.group(e,t,Object.assign({},i,{collapsed:!0}))}groupEnd(e){return this._getLogFunction(e,"",console.groupEnd||ib)}withGroup(e,t,i){this.group(e,t)();try{i()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&this.getLevel()>=ab(e)}_getLogFunction(e,t,i,s=[],r){if(this._shouldLog(e)){r=lb({logLevel:e,message:t,args:s,opts:r}),qv(i=i||r.method),r.total=this.getTotal(),r.delta=this.getDelta(),this._deltaTs=$v();const o=r.tag||r.message;if(r.once){if(sb[o])return ib;sb[o]=$v()}return t=function(e,t,i){if("string"==typeof t){const s=i.time?function(e,t=8){const i=Math.max(t-e.length,0);return"".concat(" ".repeat(i)).concat(e)}(function(e){let t;return t=e<10?"".concat(e.toFixed(2),"ms"):e<100?"".concat(e.toFixed(1),"ms"):e<1e3?"".concat(e.toFixed(0),"ms"):"".concat((e/1e3).toFixed(2),"s"),t}(i.total)):"";t=i.time?"".concat(e,": ").concat(s," ").concat(t):"".concat(e,": ").concat(t),t=function(e,t,i){return Kv||"string"!=typeof e||(t&&(t=Zv(t),e="[".concat(t,"m").concat(e,"")),i&&(t=Zv(i),e="[".concat(i+10,"m").concat(e,""))),e}(t,i.color,i.background)}return t}(this.id,r.message,r),i.bind(console,t,...r.args)}return ib}}function ab(e){if(!e)return 0;let t;switch(typeof e){case"number":t=e;break;case"object":t=e.logLevel||e.priority||0;break;default:return 0}return qv(Number.isFinite(t)&&t>=0),t}function lb(e){const{logLevel:t,message:i}=e;e.logLevel=ab(t);const s=e.args?Array.from(e.args):[];for(;s.length&&s.shift()!==i;);switch(e.args=s,typeof t){case"string":case"function":void 0!==i&&s.unshift(i),e.message=t;break;case"object":Object.assign(e,t)}"function"==typeof e.message&&(e.message=e.message());const r=typeof e.message;return qv("string"===r||"object"===r),Object.assign(e,e.opts)}nb.VERSION=Wv;const Ab=new nb({id:"loaders.gl"});class hb{log(){return()=>{}}info(){return()=>{}}warn(){return()=>{}}error(){return()=>{}}}const cb={fetch:null,mimeType:void 0,nothrow:!1,log:new class{constructor(){tv(this,"console",void 0),this.console=console}log(...e){return this.console.log.bind(this.console,...e)}info(...e){return this.console.info.bind(this.console,...e)}warn(...e){return this.console.warn.bind(this.console,...e)}error(...e){return this.console.error.bind(this.console,...e)}},CDN:"https://unpkg.com/@loaders.gl",worker:!0,maxConcurrency:3,maxMobileConcurrency:1,reuseWorkers:W_,_nodeWorkers:!1,_workerType:"",limit:0,_limitMB:0,batchSize:"auto",batchDebounceMs:0,metadata:!1,transforms:[]},ub={throws:"nothrow",dataType:"(no longer used)",uri:"baseUri",method:"fetch.method",headers:"fetch.headers",body:"fetch.body",mode:"fetch.mode",credentials:"fetch.credentials",cache:"fetch.cache",redirect:"fetch.redirect",referrer:"fetch.referrer",referrerPolicy:"fetch.referrerPolicy",integrity:"fetch.integrity",keepalive:"fetch.keepalive",signal:"fetch.signal"};function db(){globalThis.loaders=globalThis.loaders||{};const{loaders:e}=globalThis;return e._state=e._state||{},e._state}const pb=()=>{const e=db();return e.globalOptions=e.globalOptions||{...cb},e.globalOptions};function fb(e,t,i,s){return i=i||[],function(e,t){mb(e,null,cb,ub,t);for(const i of t){const s=e&&e[i.id]||{},r=i.options&&i.options[i.id]||{},o=i.deprecatedOptions&&i.deprecatedOptions[i.id]||{};mb(s,i.id,r,o,t)}}(e,i=Array.isArray(i)?i:[i]),function(e,t,i){const s={...e.options||{}};(function(e,t){t&&!("baseUri"in e)&&(e.baseUri=t)})(s,i),null===s.log&&(s.log=new hb);return vb(s,pb()),vb(s,t),s}(t,e,s)}function gb(e,t){const i=pb(),s=e||i;return"function"==typeof s.fetch?s.fetch:Fv(s.fetch)?e=>Hv(e,s):null!=t&&t.fetch?null==t?void 0:t.fetch:Hv}function mb(e,t,i,s,r){const o=t||"Top level",n=t?"".concat(t,"."):"";for(const a in e){const l=!t&&Fv(e[a]),A="baseUri"===a&&!t,h="workerUrl"===a&&t;if(!(a in i)&&!A&&!h)if(a in s)Ab.warn("".concat(o," loader option '").concat(n).concat(a,"' no longer supported, use '").concat(s[a],"'"))();else if(!l){const e=_b(a,r);Ab.warn("".concat(o," loader option '").concat(n).concat(a,"' not recognized. ").concat(e))()}}}function _b(e,t){const i=e.toLowerCase();let s="";for(const r of t)for(const t in r.options){if(e===t)return"Did you mean '".concat(r.id,".").concat(t,"'?");const o=t.toLowerCase();(i.startsWith(o)||o.startsWith(i))&&(s=s||"Did you mean '".concat(r.id,".").concat(t,"'?"))}return s}function vb(e,t){for(const i in t)if(i in t){const s=t[i];Iv(s)&&Iv(e[i])?e[i]={...e[i],...t[i]}:e[i]=t[i]}}function bb(e){var t;if(!e)return!1;Array.isArray(e)&&(e=e[0]);return Array.isArray(null===(t=e)||void 0===t?void 0:t.extensions)}function yb(e){var t,i;let s;return z_(e,"null loader"),z_(bb(e),"invalid loader"),Array.isArray(e)&&(s=e[1],e=e[0],e={...e,options:{...e.options,...s}}),(null!==(t=e)&&void 0!==t&&t.parseTextSync||null!==(i=e)&&void 0!==i&&i.parseText)&&(e.text=!0),e.text||(e.binary=!0),e}function xb(){return(()=>{const e=db();return e.loaderRegistry=e.loaderRegistry||[],e.loaderRegistry})()}function Bb(){return!("object"==typeof process&&"[object process]"===String(process)&&!process.browser)||function(e){if("undefined"!=typeof window&&"object"==typeof window.process&&"renderer"===window.process.type)return!0;if("undefined"!=typeof process&&"object"==typeof process.versions&&Boolean(process.versions.electron))return!0;const t="object"==typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent,i=e||t;return!!(i&&i.indexOf("Electron")>=0)}()}const wb={self:"undefined"!=typeof self&&self,window:"undefined"!=typeof window&&window,global:"undefined"!=typeof global&&global,document:"undefined"!=typeof document&&document,process:"object"==typeof process&&process},Pb=wb.window||wb.self||wb.global,Cb=wb.process||{},Mb="undefined"!=typeof __VERSION__?__VERSION__:"untranspiled source";Bb();class Eb{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"sessionStorage";tv(this,"storage",void 0),tv(this,"id",void 0),tv(this,"config",{}),this.storage=function(e){try{const t=window[e],i="__storage_test__";return t.setItem(i,i),t.removeItem(i),t}catch(e){return null}}(i),this.id=e,this.config={},Object.assign(this.config,t),this._loadConfiguration()}getConfiguration(){return this.config}setConfiguration(e){return this.config={},this.updateConfiguration(e)}updateConfiguration(e){if(Object.assign(this.config,e),this.storage){const e=JSON.stringify(this.config);this.storage.setItem(this.id,e)}return this}_loadConfiguration(){let e={};if(this.storage){const t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}}function Fb(e,t,i){let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:600;const r=e.src.replace(/\(/g,"%28").replace(/\)/g,"%29");e.width>s&&(i=Math.min(i,s/e.width));const o=e.width*i,n=e.height*i,a=["font-size:1px;","padding:".concat(Math.floor(n/2),"px ").concat(Math.floor(o/2),"px;"),"line-height:".concat(n,"px;"),"background:url(".concat(r,");"),"background-size:".concat(o,"px ").concat(n,"px;"),"color:transparent;"].join("");return["".concat(t," %c+"),a]}let Ib;function Db(e){return"string"==typeof e?Ib[e.toUpperCase()]||Ib.WHITE:e}function Sb(e,t){if(!e)throw new Error(t||"Assertion failed")}function Tb(){let e;var t,i;if(Bb&&"performance"in Pb)e=null==Pb||null===(t=Pb.performance)||void 0===t||null===(i=t.now)||void 0===i?void 0:i.call(t);else if("hrtime"in Cb){var s;const t=null==Cb||null===(s=Cb.hrtime)||void 0===s?void 0:s.call(Cb);e=1e3*t[0]+t[1]/1e6}else e=Date.now();return e}!function(e){e[e.BLACK=30]="BLACK",e[e.RED=31]="RED",e[e.GREEN=32]="GREEN",e[e.YELLOW=33]="YELLOW",e[e.BLUE=34]="BLUE",e[e.MAGENTA=35]="MAGENTA",e[e.CYAN=36]="CYAN",e[e.WHITE=37]="WHITE",e[e.BRIGHT_BLACK=90]="BRIGHT_BLACK",e[e.BRIGHT_RED=91]="BRIGHT_RED",e[e.BRIGHT_GREEN=92]="BRIGHT_GREEN",e[e.BRIGHT_YELLOW=93]="BRIGHT_YELLOW",e[e.BRIGHT_BLUE=94]="BRIGHT_BLUE",e[e.BRIGHT_MAGENTA=95]="BRIGHT_MAGENTA",e[e.BRIGHT_CYAN=96]="BRIGHT_CYAN",e[e.BRIGHT_WHITE=97]="BRIGHT_WHITE"}(Ib||(Ib={}));const Rb={debug:Bb&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},Lb={enabled:!0,level:0};function Ub(){}const Ob={},kb={once:!0};class Nb{constructor(){let{id:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{id:""};tv(this,"id",void 0),tv(this,"VERSION",Mb),tv(this,"_startTs",Tb()),tv(this,"_deltaTs",Tb()),tv(this,"_storage",void 0),tv(this,"userData",{}),tv(this,"LOG_THROTTLE_TIMEOUT",0),this.id=e,this._storage=new Eb("__probe-".concat(this.id,"__"),Lb),this.userData={},this.timeStamp("".concat(this.id," started")),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:["constructor"];const i=Object.getPrototypeOf(e),s=Object.getOwnPropertyNames(i);for(const i of s)"function"==typeof e[i]&&(t.find((e=>i===e))||(e[i]=e[i].bind(e)))}(this),Object.seal(this)}set level(e){this.setLevel(e)}get level(){return this.getLevel()}isEnabled(){return this._storage.config.enabled}getLevel(){return this._storage.config.level}getTotal(){return Number((Tb()-this._startTs).toPrecision(10))}getDelta(){return Number((Tb()-this._deltaTs).toPrecision(10))}set priority(e){this.level=e}get priority(){return this.level}getPriority(){return this.level}enable(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this._storage.updateConfiguration({enabled:e}),this}setLevel(e){return this._storage.updateConfiguration({level:e}),this}get(e){return this._storage.config[e]}set(e,t){this._storage.updateConfiguration({[e]:t})}settings(){console.table?console.table(this._storage.config):console.log(this._storage.config)}assert(e,t){Sb(e,t)}warn(e){return this._getLogFunction(0,e,Rb.warn,arguments,kb)}error(e){return this._getLogFunction(0,e,Rb.error,arguments)}deprecated(e,t){return this.warn("`".concat(e,"` is deprecated and will be removed in a later version. Use `").concat(t,"` instead"))}removed(e,t){return this.error("`".concat(e,"` has been removed. Use `").concat(t,"` instead"))}probe(e,t){return this._getLogFunction(e,t,Rb.log,arguments,{time:!0,once:!0})}log(e,t){return this._getLogFunction(e,t,Rb.debug,arguments)}info(e,t){return this._getLogFunction(e,t,console.info,arguments)}once(e,t){for(var i=arguments.length,s=new Array(i>2?i-2:0),r=2;r{const t=Fb(e,i,s);console.log(...t)},e.src=t,Ub}const r=t.nodeName||"";if("img"===r.toLowerCase())return console.log(...Fb(t,i,s)),Ub;if("canvas"===r.toLowerCase()){const e=new Image;return e.onload=()=>console.log(...Fb(e,i,s)),e.src=t.toDataURL(),Ub}return Ub}({image:s,message:r,scale:o}):function(e){let{image:t,message:i="",scale:s=1}=e,r=null;try{r=module.require("asciify-image")}catch(e){}if(r)return()=>r(t,{fit:"box",width:"".concat(Math.round(80*s),"%")}).then((e=>console.log(e)));return Ub}({image:s,message:r,scale:o}):Ub}time(e,t){return this._getLogFunction(e,t,console.time?console.time:console.info)}timeEnd(e,t){return this._getLogFunction(e,t,console.timeEnd?console.timeEnd:console.info)}timeStamp(e,t){return this._getLogFunction(e,t,console.timeStamp||Ub)}group(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{collapsed:!1};const s=Vb({logLevel:e,message:t,opts:i}),{collapsed:r}=i;return s.method=(r?console.groupCollapsed:console.group)||console.info,this._getLogFunction(s)}groupCollapsed(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.group(e,t,Object.assign({},i,{collapsed:!0}))}groupEnd(e){return this._getLogFunction(e,"",console.groupEnd||Ub)}withGroup(e,t,i){this.group(e,t)();try{i()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&this.getLevel()>=Qb(e)}_getLogFunction(e,t,i,s,r){if(this._shouldLog(e)){r=Vb({logLevel:e,message:t,args:s,opts:r}),Sb(i=i||r.method),r.total=this.getTotal(),r.delta=this.getDelta(),this._deltaTs=Tb();const o=r.tag||r.message;if(r.once){if(Ob[o])return Ub;Ob[o]=Tb()}return t=function(e,t,i){if("string"==typeof t){const s=i.time?function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8;const i=Math.max(t-e.length,0);return"".concat(" ".repeat(i)).concat(e)}(function(e){let t;return t=e<10?"".concat(e.toFixed(2),"ms"):e<100?"".concat(e.toFixed(1),"ms"):e<1e3?"".concat(e.toFixed(0),"ms"):"".concat((e/1e3).toFixed(2),"s"),t}(i.total)):"";t=i.time?"".concat(e,": ").concat(s," ").concat(t):"".concat(e,": ").concat(t),t=function(e,t,i){return Bb||"string"!=typeof e||(t&&(t=Db(t),e="[".concat(t,"m").concat(e,"")),i&&(t=Db(i),e="[".concat(i+10,"m").concat(e,""))),e}(t,i.color,i.background)}return t}(this.id,r.message,r),i.bind(console,t,...r.args)}return Ub}}function Qb(e){if(!e)return 0;let t;switch(typeof e){case"number":t=e;break;case"object":t=e.logLevel||e.priority||0;break;default:return 0}return Sb(Number.isFinite(t)&&t>=0),t}function Vb(e){const{logLevel:t,message:i}=e;e.logLevel=Qb(t);const s=e.args?Array.from(e.args):[];for(;s.length&&s.shift()!==i;);switch(typeof t){case"string":case"function":void 0!==i&&s.unshift(i),e.message=t;break;case"object":Object.assign(e,t)}"function"==typeof e.message&&(e.message=e.message());const r=typeof e.message;return Sb("string"===r||"object"===r),Object.assign(e,{args:s},e.opts)}function Hb(e){for(const t in e)for(const i in e[t])return i||"untitled";return"empty"}tv(Nb,"VERSION",Mb);const jb=new Nb({id:"loaders.gl"}),Gb=/\.([^.]+)$/;function zb(e,t=[],i,s){if(!Wb(e))return null;if(t&&!Array.isArray(t))return yb(t);let r=[];t&&(r=r.concat(t)),null!=i&&i.ignoreRegisteredLoaders||r.push(...xb()),function(e){for(const t of e)yb(t)}(r);const o=function(e,t,i,s){const{url:r,type:o}=Nv(e),n=r||(null==s?void 0:s.url);let a=null,l="";null!=i&&i.mimeType&&(a=Xb(t,null==i?void 0:i.mimeType),l="match forced by supplied MIME type ".concat(null==i?void 0:i.mimeType));var A;a=a||function(e,t){const i=t&&Gb.exec(t),s=i&&i[1];return s?function(e,t){t=t.toLowerCase();for(const i of e)for(const e of i.extensions)if(e.toLowerCase()===t)return i;return null}(e,s):null}(t,n),l=l||(a?"matched url ".concat(n):""),a=a||Xb(t,o),l=l||(a?"matched MIME type ".concat(o):""),a=a||function(e,t){if(!t)return null;for(const i of e)if("string"==typeof t){if(Jb(t,i))return i}else if(ArrayBuffer.isView(t)){if(Yb(t.buffer,t.byteOffset,i))return i}else if(t instanceof ArrayBuffer){if(Yb(t,0,i))return i}return null}(t,e),l=l||(a?"matched initial data ".concat(Zb(e)):""),a=a||Xb(t,null==i?void 0:i.fallbackMimeType),l=l||(a?"matched fallback MIME type ".concat(o):""),l&&jb.log(1,"selectLoader selected ".concat(null===(A=a)||void 0===A?void 0:A.name,": ").concat(l,"."));return a}(e,r,i,s);if(!(o||null!=i&&i.nothrow))throw new Error(Kb(e));return o}function Wb(e){return!(e instanceof Response&&204===e.status)}function Kb(e){const{url:t,type:i}=Nv(e);let s="No valid loader found (";s+=t?"".concat(function(e){const t=e&&e.lastIndexOf("/");return t>=0?e.substr(t+1):""}(t),", "):"no url provided, ",s+="MIME type: ".concat(i?'"'.concat(i,'"'):"not provided",", ");const r=e?Zb(e):"";return s+=r?' first bytes: "'.concat(r,'"'):"first bytes: not available",s+=")",s}function Xb(e,t){for(const i of e){if(i.mimeTypes&&i.mimeTypes.includes(t))return i;if(t==="application/x.".concat(i.id))return i}return null}function Jb(e,t){if(t.testText)return t.testText(e);return(Array.isArray(t.tests)?t.tests:[t.tests]).some((t=>e.startsWith(t)))}function Yb(e,t,i){return(Array.isArray(i.tests)?i.tests:[i.tests]).some((s=>function(e,t,i,s){if(s instanceof ArrayBuffer)return function(e,t,i){if(i=i||e.byteLength,e.byteLength60?"".concat(t.slice(0,60),"..."):t}catch(e){}return t}(e);throw new Error(t)}}(i),t.binary?await i.arrayBuffer():await i.text()}if(Tv(e)&&(e=ty(e,i)),(r=e)&&"function"==typeof r[Symbol.iterator]||(e=>e&&"function"==typeof e[Symbol.asyncIterator])(e))return Cv(e);var r;throw new Error(iy)}async function ry(e,t,i,s){X_(!s||"object"==typeof s),!t||Array.isArray(t)||bb(t)||(s=void 0,i=t,t=void 0),e=await e,i=i||{};const{url:r}=Nv(e),o=function(e,t){if(!t&&e&&!Array.isArray(e))return e;let i;if(e&&(i=Array.isArray(e)?e:[e]),t&&t.loaders){const e=Array.isArray(t.loaders)?t.loaders:[t.loaders];i=i?[...i,...e]:e}return i&&i.length?i:null}(t,s),n=await async function(e,t=[],i,s){if(!Wb(e))return null;let r=zb(e,t,{...i,nothrow:!0},s);if(r)return r;if(Sv(e)&&(r=zb(e=await e.slice(0,10).arrayBuffer(),t,i,s)),!(r||null!=i&&i.nothrow))throw new Error(Kb(e));return r}(e,o,i);return n?(s=function(e,t,i=null){if(i)return i;const s={fetch:gb(t,e),...e};return Array.isArray(s.loaders)||(s.loaders=null),s}({url:r,parse:ry,loaders:o},i=fb(i,n,o,r),s),await async function(e,t,i,s){if(function(e,t="3.2.6"){X_(e,"no worker provided");const i=e.version}(e),Dv(t)){const e=t,{ok:i,redirected:r,status:o,statusText:n,type:a,url:l}=e,A=Object.fromEntries(e.headers.entries());s.response={headers:A,ok:i,redirected:r,status:o,statusText:n,type:a,url:l}}if(t=await sy(t,e,i),e.parseTextSync&&"string"==typeof t)return i.dataType="text",e.parseTextSync(t,i,s,e);if(function(e,t){return!!dv.isSupported()&&!!(Z_||null!=t&&t._nodeWorkers)&&e.worker&&(null==t?void 0:t.worker)}(e,i))return await mv(e,t,i,s,ry);if(e.parseText&&"string"==typeof t)return await e.parseText(t,i,s,e);if(e.parse)return await e.parse(t,i,s,e);throw X_(!e.parseSync),new Error("".concat(e.id," loader - no parser found and worker is disabled"))}(n,e,i,s)):null}const oy="https://unpkg.com/@loaders.gl/textures@".concat("3.2.6","/dist/libs/basis_encoder.wasm"),ny="https://unpkg.com/@loaders.gl/textures@".concat("3.2.6","/dist/libs/basis_encoder.js");let ay,ly;async function Ay(e){const t=e.modules||{};return t.basis?t.basis:(ay=ay||async function(e){let t=null,i=null;return[t,i]=await Promise.all([await gv("basis_transcoder.js","textures",e),await gv("basis_transcoder.wasm","textures",e)]),t=t||globalThis.BASIS,await function(e,t){const i={};t&&(i.wasmBinary=t);return new Promise((t=>{e(i).then((e=>{const{BasisFile:i,initializeBasis:s}=e;s(),t({BasisFile:i})}))}))}(t,i)}(e),await ay)}async function hy(e){const t=e.modules||{};return t.basisEncoder?t.basisEncoder:(ly=ly||async function(e){let t=null,i=null;return[t,i]=await Promise.all([await gv(ny,"textures",e),await gv(oy,"textures",e)]),t=t||globalThis.BASIS,await function(e,t){const i={};t&&(i.wasmBinary=t);return new Promise((t=>{e(i).then((e=>{const{BasisFile:i,KTX2File:s,initializeBasis:r,BasisEncoder:o}=e;r(),t({BasisFile:i,KTX2File:s,BasisEncoder:o})}))}))}(t,i)}(e),await ly)}const cy=33776,uy=33779,dy=35840,py=35842,fy=36196,gy=37808,my=["","WEBKIT_","MOZ_"],_y={WEBGL_compressed_texture_s3tc:"dxt",WEBGL_compressed_texture_s3tc_srgb:"dxt-srgb",WEBGL_compressed_texture_etc1:"etc1",WEBGL_compressed_texture_etc:"etc2",WEBGL_compressed_texture_pvrtc:"pvrtc",WEBGL_compressed_texture_atc:"atc",WEBGL_compressed_texture_astc:"astc",EXT_texture_compression_rgtc:"rgtc"};let vy=null;function by(e){if(!vy){e=e||function(){try{return document.createElement("canvas").getContext("webgl")}catch(e){return null}}()||void 0,vy=new Set;for(const t of my)for(const i in _y)if(e&&e.getExtension("".concat(t).concat(i))){const e=_y[i];vy.add(e)}}return vy}var yy,xy,By,wy,Py,Cy,My,Ey,Fy;(Fy=yy||(yy={}))[Fy.NONE=0]="NONE",Fy[Fy.BASISLZ=1]="BASISLZ",Fy[Fy.ZSTD=2]="ZSTD",Fy[Fy.ZLIB=3]="ZLIB",function(e){e[e.BASICFORMAT=0]="BASICFORMAT"}(xy||(xy={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.ETC1S=163]="ETC1S",e[e.UASTC=166]="UASTC"}(By||(By={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.SRGB=1]="SRGB"}(wy||(wy={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.LINEAR=1]="LINEAR",e[e.SRGB=2]="SRGB",e[e.ITU=3]="ITU",e[e.NTSC=4]="NTSC",e[e.SLOG=5]="SLOG",e[e.SLOG2=6]="SLOG2"}(Py||(Py={})),function(e){e[e.ALPHA_STRAIGHT=0]="ALPHA_STRAIGHT",e[e.ALPHA_PREMULTIPLIED=1]="ALPHA_PREMULTIPLIED"}(Cy||(Cy={})),function(e){e[e.RGB=0]="RGB",e[e.RRR=3]="RRR",e[e.GGG=4]="GGG",e[e.AAA=15]="AAA"}(My||(My={})),function(e){e[e.RGB=0]="RGB",e[e.RGBA=3]="RGBA",e[e.RRR=4]="RRR",e[e.RRRG=5]="RRRG"}(Ey||(Ey={}));const Iy=[171,75,84,88,32,50,48,187,13,10,26,10];const Dy={etc1:{basisFormat:0,compressed:!0,format:fy},etc2:{basisFormat:1,compressed:!0},bc1:{basisFormat:2,compressed:!0,format:cy},bc3:{basisFormat:3,compressed:!0,format:uy},bc4:{basisFormat:4,compressed:!0},bc5:{basisFormat:5,compressed:!0},"bc7-m6-opaque-only":{basisFormat:6,compressed:!0},"bc7-m5":{basisFormat:7,compressed:!0},"pvrtc1-4-rgb":{basisFormat:8,compressed:!0,format:dy},"pvrtc1-4-rgba":{basisFormat:9,compressed:!0,format:py},"astc-4x4":{basisFormat:10,compressed:!0,format:gy},"atc-rgb":{basisFormat:11,compressed:!0},"atc-rgba-interpolated-alpha":{basisFormat:12,compressed:!0},rgba32:{basisFormat:13,compressed:!1},rgb565:{basisFormat:14,compressed:!1},bgr565:{basisFormat:15,compressed:!1},rgba4444:{basisFormat:16,compressed:!1}};function Sy(e,t,i){const s=new e(new Uint8Array(t));try{if(!s.startTranscoding())throw new Error("Failed to start basis transcoding");const e=s.getNumImages(),t=[];for(let r=0;r{try{i.onload=()=>t(i),i.onerror=t=>s(new Error("Could not load image ".concat(e,": ").concat(t)))}catch(e){s(e)}}))}(o||s,t)}finally{o&&r.revokeObjectURL(o)}}const Yy={};let Zy=!0;async function qy(e,t,i){let s;if(Ky(i)){s=await Jy(e,t,i)}else s=Xy(e,i);const r=t&&t.imagebitmap;return await async function(e,t=null){!function(e){for(const t in e||Yy)return!1;return!0}(t)&&Zy||(t=null);if(t)try{return await createImageBitmap(e,t)}catch(e){console.warn(e),Zy=!1}return await createImageBitmap(e)}(s,r)}function $y(e){const t=ex(e);return function(e){const t=ex(e);if(!(t.byteLength>=24&&2303741511===t.getUint32(0,false)))return null;return{mimeType:"image/png",width:t.getUint32(16,false),height:t.getUint32(20,false)}}(t)||function(e){const t=ex(e);if(!(t.byteLength>=3&&65496===t.getUint16(0,false)&&255===t.getUint8(2)))return null;const{tableMarkers:i,sofMarkers:s}=function(){const e=new Set([65499,65476,65484,65501,65534]);for(let t=65504;t<65520;++t)e.add(t);const t=new Set([65472,65473,65474,65475,65477,65478,65479,65481,65482,65483,65485,65486,65487,65502]);return{tableMarkers:e,sofMarkers:t}}();let r=2;for(;r+9=10&&1195984440===t.getUint32(0,false)))return null;return{mimeType:"image/gif",width:t.getUint16(6,true),height:t.getUint16(8,true)}}(t)||function(e){const t=ex(e);if(!(t.byteLength>=14&&16973===t.getUint16(0,false)&&t.getUint32(2,true)===t.byteLength))return null;return{mimeType:"image/bmp",width:t.getUint32(18,true),height:t.getUint32(22,true)}}(t)}function ex(e){if(e instanceof DataView)return e;if(ArrayBuffer.isView(e))return new DataView(e.buffer);if(e instanceof ArrayBuffer)return new DataView(e);throw new Error("toDataView")}const tx={id:"image",module:"images",name:"Images",version:"3.2.6",mimeTypes:["image/png","image/jpeg","image/gif","image/webp","image/bmp","image/vnd.microsoft.icon","image/svg+xml"],extensions:["png","jpg","jpeg","gif","webp","bmp","ico","svg"],parse:async function(e,t,i){const s=((t=t||{}).image||{}).type||"auto",{url:r}=i||{};let o;switch(function(e){switch(e){case"auto":case"data":return function(){if(Vy)return"imagebitmap";if(Qy)return"image";if(jy)return"data";throw new Error("Install '@loaders.gl/polyfills' to parse images under Node.js")}();default:return function(e){switch(e){case"auto":return Vy||Qy||jy;case"imagebitmap":return Vy;case"image":return Qy;case"data":return jy;default:throw new Error("@loaders.gl/images: image ".concat(e," not supported in this environment"))}}(e),e}}(s)){case"imagebitmap":o=await qy(e,t,r);break;case"image":o=await Jy(e,t,r);break;case"data":o=await async function(e,t){const{mimeType:i}=$y(e)||{},s=globalThis._parseImageNode;return z_(s),await s(e,i)}(e);break;default:z_(!1)}return"data"===s&&(o=function(e){switch(Gy(e)){case"data":return e;case"image":case"imagebitmap":const t=document.createElement("canvas"),i=t.getContext("2d");if(!i)throw new Error("getImageData");return t.width=e.width,t.height=e.height,i.drawImage(e,0,0),i.getImageData(0,0,e.width,e.height);default:throw new Error("getImageData")}}(o)),o},tests:[e=>Boolean($y(new DataView(e)))],options:{image:{type:"auto",decode:!0}}},ix=["image/png","image/jpeg","image/gif"],sx={};function rx(e){return void 0===sx[e]&&(sx[e]=function(e){switch(e){case"image/webp":return function(){if(!W_)return!1;try{return 0===document.createElement("canvas").toDataURL("image/webp").indexOf("data:image/webp")}catch{return!1}}();case"image/svg":return W_;default:if(!W_){const{_parseImageNode:t}=globalThis;return Boolean(t)&&ix.includes(e)}return!0}}(e)),sx[e]}function ox(e,t){if(!e)throw new Error(t||"assert failed: gltf")}function nx(e,t){if(e.startsWith("data:")||e.startsWith("http:")||e.startsWith("https:"))return e;const i=t.baseUri||t.uri;if(!i)throw new Error("'baseUri' must be provided to resolve relative url ".concat(e));return i.substr(0,i.lastIndexOf("/")+1)+e}const ax=["SCALAR","VEC2","VEC3","VEC4"],lx=[[Int8Array,5120],[Uint8Array,5121],[Int16Array,5122],[Uint16Array,5123],[Uint32Array,5125],[Float32Array,5126],[Float64Array,5130]],Ax=new Map(lx),hx={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},cx={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},ux={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array};function dx(e){return ax[e-1]||ax[0]}function px(e){const t=Ax.get(e.constructor);if(!t)throw new Error("Illegal typed array");return t}function fx(e,t){const i=ux[e.componentType],s=hx[e.type],r=cx[e.componentType],o=e.count*s,n=e.count*s*r;return ox(n>=0&&n<=t.byteLength),{ArrayType:i,length:o,byteLength:n}}const gx={asset:{version:"2.0",generator:"loaders.gl"},buffers:[]};class mx{constructor(e){tv(this,"gltf",void 0),tv(this,"sourceBuffers",void 0),tv(this,"byteLength",void 0),this.gltf=e||{json:{...gx},buffers:[]},this.sourceBuffers=[],this.byteLength=0,this.gltf.buffers&&this.gltf.buffers[0]&&(this.byteLength=this.gltf.buffers[0].byteLength,this.sourceBuffers=[this.gltf.buffers[0]])}get json(){return this.gltf.json}getApplicationData(e){return this.json[e]}getExtraData(e){return(this.json.extras||{})[e]}getExtension(e){const t=this.getUsedExtensions().find((t=>t===e)),i=this.json.extensions||{};return t?i[e]||!0:null}getRequiredExtension(e){const t=this.getRequiredExtensions().find((t=>t===e));return t?this.getExtension(e):null}getRequiredExtensions(){return this.json.extensionsRequired||[]}getUsedExtensions(){return this.json.extensionsUsed||[]}getObjectExtension(e,t){return(e.extensions||{})[t]}getScene(e){return this.getObject("scenes",e)}getNode(e){return this.getObject("nodes",e)}getSkin(e){return this.getObject("skins",e)}getMesh(e){return this.getObject("meshes",e)}getMaterial(e){return this.getObject("materials",e)}getAccessor(e){return this.getObject("accessors",e)}getTexture(e){return this.getObject("textures",e)}getSampler(e){return this.getObject("samplers",e)}getImage(e){return this.getObject("images",e)}getBufferView(e){return this.getObject("bufferViews",e)}getBuffer(e){return this.getObject("buffers",e)}getObject(e,t){if("object"==typeof t)return t;const i=this.json[e]&&this.json[e][t];if(!i)throw new Error("glTF file error: Could not find ".concat(e,"[").concat(t,"]"));return i}getTypedArrayForBufferView(e){const t=(e=this.getBufferView(e)).buffer,i=this.gltf.buffers[t];ox(i);const s=(e.byteOffset||0)+i.byteOffset;return new Uint8Array(i.arrayBuffer,s,e.byteLength)}getTypedArrayForAccessor(e){e=this.getAccessor(e);const t=this.getBufferView(e.bufferView),i=this.getBuffer(t.buffer).data,{ArrayType:s,length:r}=fx(e,t);return new s(i,t.byteOffset+e.byteOffset,r)}getTypedArrayForImageData(e){e=this.getAccessor(e);const t=this.getBufferView(e.bufferView),i=this.getBuffer(t.buffer).data,s=t.byteOffset||0;return new Uint8Array(i,s,t.byteLength)}addApplicationData(e,t){return this.json[e]=t,this}addExtraData(e,t){return this.json.extras=this.json.extras||{},this.json.extras[e]=t,this}addObjectExtension(e,t,i){return e.extensions=e.extensions||{},e.extensions[t]=i,this.registerUsedExtension(t),this}setObjectExtension(e,t,i){(e.extensions||{})[t]=i}removeObjectExtension(e,t){const i=e.extensions||{},s=i[t];return delete i[t],s}addExtension(e,t={}){return ox(t),this.json.extensions=this.json.extensions||{},this.json.extensions[e]=t,this.registerUsedExtension(e),t}addRequiredExtension(e,t={}){return ox(t),this.addExtension(e,t),this.registerRequiredExtension(e),t}registerUsedExtension(e){this.json.extensionsUsed=this.json.extensionsUsed||[],this.json.extensionsUsed.find((t=>t===e))||this.json.extensionsUsed.push(e)}registerRequiredExtension(e){this.registerUsedExtension(e),this.json.extensionsRequired=this.json.extensionsRequired||[],this.json.extensionsRequired.find((t=>t===e))||this.json.extensionsRequired.push(e)}removeExtension(e){this.json.extensionsRequired&&this._removeStringFromArray(this.json.extensionsRequired,e),this.json.extensionsUsed&&this._removeStringFromArray(this.json.extensionsUsed,e),this.json.extensions&&delete this.json.extensions[e]}setDefaultScene(e){this.json.scene=e}addScene(e){const{nodeIndices:t}=e;return this.json.scenes=this.json.scenes||[],this.json.scenes.push({nodes:t}),this.json.scenes.length-1}addNode(e){const{meshIndex:t,matrix:i}=e;this.json.nodes=this.json.nodes||[];const s={mesh:t};return i&&(s.matrix=i),this.json.nodes.push(s),this.json.nodes.length-1}addMesh(e){const{attributes:t,indices:i,material:s,mode:r=4}=e,o={primitives:[{attributes:this._addAttributes(t),mode:r}]};if(i){const e=this._addIndices(i);o.primitives[0].indices=e}return Number.isFinite(s)&&(o.primitives[0].material=s),this.json.meshes=this.json.meshes||[],this.json.meshes.push(o),this.json.meshes.length-1}addPointCloud(e){const t={primitives:[{attributes:this._addAttributes(e),mode:0}]};return this.json.meshes=this.json.meshes||[],this.json.meshes.push(t),this.json.meshes.length-1}addImage(e,t){const i=$y(e),s=t||(null==i?void 0:i.mimeType),r={bufferView:this.addBufferView(e),mimeType:s};return this.json.images=this.json.images||[],this.json.images.push(r),this.json.images.length-1}addBufferView(e){const t=e.byteLength;ox(Number.isFinite(t)),this.sourceBuffers=this.sourceBuffers||[],this.sourceBuffers.push(e);const i={buffer:0,byteOffset:this.byteLength,byteLength:t};return this.byteLength+=wv(t,4),this.json.bufferViews=this.json.bufferViews||[],this.json.bufferViews.push(i),this.json.bufferViews.length-1}addAccessor(e,t){const i={bufferView:e,type:dx(t.size),componentType:t.componentType,count:t.count,max:t.max,min:t.min};return this.json.accessors=this.json.accessors||[],this.json.accessors.push(i),this.json.accessors.length-1}addBinaryBuffer(e,t={size:3}){const i=this.addBufferView(e);let s={min:t.min,max:t.max};s.min&&s.max||(s=this._getAccessorMinMax(e,t.size));const r={size:t.size,componentType:px(e),count:Math.round(e.length/t.size),min:s.min,max:s.max};return this.addAccessor(i,Object.assign(r,t))}addTexture(e){const{imageIndex:t}=e,i={source:t};return this.json.textures=this.json.textures||[],this.json.textures.push(i),this.json.textures.length-1}addMaterial(e){return this.json.materials=this.json.materials||[],this.json.materials.push(e),this.json.materials.length-1}createBinaryChunk(){var e,t;this.gltf.buffers=[];const i=this.byteLength,s=new ArrayBuffer(i),r=new Uint8Array(s);let o=0;for(const e of this.sourceBuffers||[])o=Pv(e,r,o);null!==(e=this.json)&&void 0!==e&&null!==(t=e.buffers)&&void 0!==t&&t[0]?this.json.buffers[0].byteLength=i:this.json.buffers=[{byteLength:i}],this.gltf.binary=s,this.sourceBuffers=[s]}_removeStringFromArray(e,t){let i=!0;for(;i;){const s=e.indexOf(t);s>-1?e.splice(s,1):i=!1}}_addAttributes(e={}){const t={};for(const i in e){const s=e[i],r=this._getGltfAttributeName(i),o=this.addBinaryBuffer(s.value,s);t[r]=o}return t}_addIndices(e){return this.addBinaryBuffer(e,{size:1})}_getGltfAttributeName(e){switch(e.toLowerCase()){case"position":case"positions":case"vertices":return"POSITION";case"normal":case"normals":return"NORMAL";case"color":case"colors":return"COLOR_0";case"texcoord":case"texcoords":return"TEXCOORD_0";default:return e}}_getAccessorMinMax(e,t){const i={min:null,max:null};if(e.length96?s-71:s>64?s-65:s>47?s+4:s>46?63:62}let i=0;for(let s=0;st[e.name]));return new Dx(i,this.metadata)}selectAt(...e){const t=e.map((e=>this.fields[e])).filter(Boolean);return new Dx(t,this.metadata)}assign(e){let t,i=this.metadata;if(e instanceof Dx){const s=e;t=s.fields,i=Sx(Sx(new Map,this.metadata),s.metadata)}else t=e;const s=Object.create(null);for(const e of this.fields)s[e.name]=e;for(const e of t)s[e.name]=e;const r=Object.values(s);return new Dx(r,i)}}function Sx(e,t){return new Map([...e||new Map,...t||new Map])}class Tx{constructor(e,t,i=!1,s=new Map){tv(this,"name",void 0),tv(this,"type",void 0),tv(this,"nullable",void 0),tv(this,"metadata",void 0),this.name=e,this.type=t,this.nullable=i,this.metadata=s}get typeId(){return this.type&&this.type.typeId}clone(){return new Tx(this.name,this.type,this.nullable,this.metadata)}compareTo(e){return this.name===e.name&&this.type===e.type&&this.nullable===e.nullable&&this.metadata===e.metadata}toString(){return"".concat(this.type).concat(this.nullable?", nullable":"").concat(this.metadata?", metadata: ".concat(this.metadata):"")}}let Rx,Lx,Ux,Ox;!function(e){e[e.NONE=0]="NONE",e[e.Null=1]="Null",e[e.Int=2]="Int",e[e.Float=3]="Float",e[e.Binary=4]="Binary",e[e.Utf8=5]="Utf8",e[e.Bool=6]="Bool",e[e.Decimal=7]="Decimal",e[e.Date=8]="Date",e[e.Time=9]="Time",e[e.Timestamp=10]="Timestamp",e[e.Interval=11]="Interval",e[e.List=12]="List",e[e.Struct=13]="Struct",e[e.Union=14]="Union",e[e.FixedSizeBinary=15]="FixedSizeBinary",e[e.FixedSizeList=16]="FixedSizeList",e[e.Map=17]="Map",e[e.Dictionary=-1]="Dictionary",e[e.Int8=-2]="Int8",e[e.Int16=-3]="Int16",e[e.Int32=-4]="Int32",e[e.Int64=-5]="Int64",e[e.Uint8=-6]="Uint8",e[e.Uint16=-7]="Uint16",e[e.Uint32=-8]="Uint32",e[e.Uint64=-9]="Uint64",e[e.Float16=-10]="Float16",e[e.Float32=-11]="Float32",e[e.Float64=-12]="Float64",e[e.DateDay=-13]="DateDay",e[e.DateMillisecond=-14]="DateMillisecond",e[e.TimestampSecond=-15]="TimestampSecond",e[e.TimestampMillisecond=-16]="TimestampMillisecond",e[e.TimestampMicrosecond=-17]="TimestampMicrosecond",e[e.TimestampNanosecond=-18]="TimestampNanosecond",e[e.TimeSecond=-19]="TimeSecond",e[e.TimeMillisecond=-20]="TimeMillisecond",e[e.TimeMicrosecond=-21]="TimeMicrosecond",e[e.TimeNanosecond=-22]="TimeNanosecond",e[e.DenseUnion=-23]="DenseUnion",e[e.SparseUnion=-24]="SparseUnion",e[e.IntervalDayTime=-25]="IntervalDayTime",e[e.IntervalYearMonth=-26]="IntervalYearMonth"}(Rx||(Rx={}));class kx{static isNull(e){return e&&e.typeId===Rx.Null}static isInt(e){return e&&e.typeId===Rx.Int}static isFloat(e){return e&&e.typeId===Rx.Float}static isBinary(e){return e&&e.typeId===Rx.Binary}static isUtf8(e){return e&&e.typeId===Rx.Utf8}static isBool(e){return e&&e.typeId===Rx.Bool}static isDecimal(e){return e&&e.typeId===Rx.Decimal}static isDate(e){return e&&e.typeId===Rx.Date}static isTime(e){return e&&e.typeId===Rx.Time}static isTimestamp(e){return e&&e.typeId===Rx.Timestamp}static isInterval(e){return e&&e.typeId===Rx.Interval}static isList(e){return e&&e.typeId===Rx.List}static isStruct(e){return e&&e.typeId===Rx.Struct}static isUnion(e){return e&&e.typeId===Rx.Union}static isFixedSizeBinary(e){return e&&e.typeId===Rx.FixedSizeBinary}static isFixedSizeList(e){return e&&e.typeId===Rx.FixedSizeList}static isMap(e){return e&&e.typeId===Rx.Map}static isDictionary(e){return e&&e.typeId===Rx.Dictionary}get typeId(){return Rx.NONE}compareTo(e){return this===e}}Lx=Symbol.toStringTag;class Nx extends kx{constructor(e,t){super(),tv(this,"isSigned",void 0),tv(this,"bitWidth",void 0),this.isSigned=e,this.bitWidth=t}get typeId(){return Rx.Int}get[Lx](){return"Int"}toString(){return"".concat(this.isSigned?"I":"Ui","nt").concat(this.bitWidth)}}class Qx extends Nx{constructor(){super(!0,8)}}class Vx extends Nx{constructor(){super(!0,16)}}class Hx extends Nx{constructor(){super(!0,32)}}class jx extends Nx{constructor(){super(!1,8)}}class Gx extends Nx{constructor(){super(!1,16)}}class zx extends Nx{constructor(){super(!1,32)}}const Wx=32,Kx=64;Ux=Symbol.toStringTag;class Xx extends kx{constructor(e){super(),tv(this,"precision",void 0),this.precision=e}get typeId(){return Rx.Float}get[Ux](){return"Float"}toString(){return"Float".concat(this.precision)}}class Jx extends Xx{constructor(){super(Wx)}}class Yx extends Xx{constructor(){super(Kx)}}Ox=Symbol.toStringTag;class Zx extends kx{constructor(e,t){super(),tv(this,"listSize",void 0),tv(this,"children",void 0),this.listSize=e,this.children=[t]}get typeId(){return Rx.FixedSizeList}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get[Ox](){return"FixedSizeList"}toString(){return"FixedSizeList[".concat(this.listSize,"]<").concat(this.valueType,">")}}function qx(e,t,i){const s=function(e){switch(e.constructor){case Int8Array:return new Qx;case Uint8Array:return new jx;case Int16Array:return new Vx;case Uint16Array:return new Gx;case Int32Array:return new Hx;case Uint32Array:return new zx;case Float32Array:return new Jx;case Float64Array:return new Yx;default:throw new Error("array type not supported")}}(t.value),r=i||function(e){const t=new Map;"byteOffset"in e&&t.set("byteOffset",e.byteOffset.toString(10));"byteStride"in e&&t.set("byteStride",e.byteStride.toString(10));"normalized"in e&&t.set("normalized",e.normalized.toString());return t}(t);return new Tx(e,new Zx(t.size,new Tx("value",s)),!1,r)}function $x(e,t,i){return qx(e,t,i?eB(i.metadata):void 0)}function eB(e){const t=new Map;for(const i in e)t.set("".concat(i,".string"),JSON.stringify(e[i]));return t}const tB={POSITION:"POSITION",NORMAL:"NORMAL",COLOR:"COLOR_0",TEX_COORD:"TEXCOORD_0"},iB={1:Int8Array,2:Uint8Array,3:Int16Array,4:Uint16Array,5:Int32Array,6:Uint32Array,9:Float32Array};class sB{constructor(e){tv(this,"draco",void 0),tv(this,"decoder",void 0),tv(this,"metadataQuerier",void 0),this.draco=e,this.decoder=new this.draco.Decoder,this.metadataQuerier=new this.draco.MetadataQuerier}destroy(){this.draco.destroy(this.decoder),this.draco.destroy(this.metadataQuerier)}parseSync(e,t={}){const i=new this.draco.DecoderBuffer;i.Init(new Int8Array(e),e.byteLength),this._disableAttributeTransforms(t);const s=this.decoder.GetEncodedGeometryType(i),r=s===this.draco.TRIANGULAR_MESH?new this.draco.Mesh:new this.draco.PointCloud;try{let e;switch(s){case this.draco.TRIANGULAR_MESH:e=this.decoder.DecodeBufferToMesh(i,r);break;case this.draco.POINT_CLOUD:e=this.decoder.DecodeBufferToPointCloud(i,r);break;default:throw new Error("DRACO: Unknown geometry type.")}if(!e.ok()||!r.ptr){const t="DRACO decompression failed: ".concat(e.error_msg());throw new Error(t)}const o=this._getDracoLoaderData(r,s,t),n=this._getMeshData(r,o,t),a=function(e){let t=1/0,i=1/0,s=1/0,r=-1/0,o=-1/0,n=-1/0;const a=e.POSITION?e.POSITION.value:[],l=a&&a.length;for(let e=0;er?l:r,o=A>o?A:o,n=h>n?h:n}return[[t,i,s],[r,o,n]]}(n.attributes),l=function(e,t,i){const s=eB(t.metadata),r=[],o=function(e){const t={};for(const i in e){const s=e[i];t[s.name||"undefined"]=s}return t}(t.attributes);for(const t in e){const i=$x(t,e[t],o[t]);r.push(i)}if(i){const e=$x("indices",i);r.push(e)}return new Dx(r,s)}(n.attributes,o,n.indices);return{loader:"draco",loaderData:o,header:{vertexCount:r.num_points(),boundingBox:a},...n,schema:l}}finally{this.draco.destroy(i),r&&this.draco.destroy(r)}}_getDracoLoaderData(e,t,i){const s=this._getTopLevelMetadata(e),r=this._getDracoAttributes(e,i);return{geometry_type:t,num_attributes:e.num_attributes(),num_points:e.num_points(),num_faces:e instanceof this.draco.Mesh?e.num_faces():0,metadata:s,attributes:r}}_getDracoAttributes(e,t){const i={};for(let s=0;sthis.decoder[e])).includes(s)){const t=new this.draco.AttributeQuantizationTransform;try{if(t.InitFromAttribute(e))return{quantization_bits:t.quantization_bits(),range:t.range(),min_values:new Float32Array([1,2,3]).map((e=>t.min_value(e)))}}finally{this.draco.destroy(t)}}return null}_getOctahedronTransform(e,t){const{octahedronAttributes:i=[]}=t,s=e.attribute_type();if(i.map((e=>this.decoder[e])).includes(s)){const t=new this.draco.AttributeQuantizationTransform;try{if(t.InitFromAttribute(e))return{quantization_bits:t.quantization_bits()}}finally{this.draco.destroy(t)}}return null}}const rB="https://www.gstatic.com/draco/versioned/decoders/".concat("1.4.1","/draco_decoder.js"),oB="https://www.gstatic.com/draco/versioned/decoders/".concat("1.4.1","/draco_wasm_wrapper.js"),nB="https://www.gstatic.com/draco/versioned/decoders/".concat("1.4.1","/draco_decoder.wasm");let aB;async function lB(e){const t=e.modules||{};return aB=t.draco3d?aB||t.draco3d.createDecoderModule({}).then((e=>({draco:e}))):aB||async function(e){let t,i;if("js"===(e.draco&&e.draco.decoderType))t=await gv(rB,"draco",e);else[t,i]=await Promise.all([await gv(oB,"draco",e),await gv(nB,"draco",e)]);return t=t||globalThis.DracoDecoderModule,await function(e,t){const i={};t&&(i.wasmBinary=t);return new Promise((t=>{e({...i,onModuleLoaded:e=>t({draco:e})})}))}(t,i)}(e),await aB}const AB={...Ix,parse:async function(e,t){const{draco:i}=await lB(t),s=new sB(i);try{return s.parseSync(e,null==t?void 0:t.draco)}finally{s.destroy()}}};function hB(e){const{buffer:t,size:i,count:s}=function(e){let t=e,i=1,s=0;e&&e.value&&(t=e.value,i=e.size||1);t&&(ArrayBuffer.isView(t)||(t=function(e,t,i=!1){if(!e)return null;if(Array.isArray(e))return new t(e);if(i&&!(e instanceof t))return new t(e);return e}(t,Float32Array)),s=t.length/i);return{buffer:t,size:i,count:s}}(e);return{value:t,size:i,byteOffset:0,count:s,type:dx(i),componentType:px(t)}}async function cB(e,t,i,s){const r=e.getObjectExtension(t,"KHR_draco_mesh_compression");if(!r)return;const o=e.getTypedArrayForBufferView(r.bufferView),n=Bv(o.buffer,o.byteOffset),{parse:a}=s,l={...i};delete l["3d-tiles"];const A=await a(n,AB,l,s),h=function(e){const t={};for(const i in e){const s=e[i];if("indices"!==i){const e=hB(s);t[i]=e}}return t}(A.attributes);for(const[i,s]of Object.entries(h))if(i in t.attributes){const r=t.attributes[i],o=e.getAccessor(r);null!=o&&o.min&&null!=o&&o.max&&(s.min=o.min,s.max=o.max)}t.attributes=h,A.indices&&(t.indices=hB(A.indices)),function(e){if(!e.attributes&&Object.keys(e.attributes).length>0)throw new Error("glTF: Empty primitive detected: Draco decompression failure?")}(t)}function uB(e,t,i=4,s,r){var o;if(!s.DracoWriter)throw new Error("options.gltf.DracoWriter not provided");const n=s.DracoWriter.encodeSync({attributes:e}),a=null==r||null===(o=r.parseSync)||void 0===o?void 0:o.call(r,{attributes:e}),l=s._addFauxAttributes(a.attributes);return{primitives:[{attributes:l,mode:i,extensions:{KHR_draco_mesh_compression:{bufferView:s.addBufferView(n),attributes:l}}}]}}function*dB(e){for(const t of e.json.meshes||[])for(const e of t.primitives)yield e}var pB=Object.freeze({__proto__:null,name:"KHR_draco_mesh_compression",preprocess:function(e,t,i){const s=new mx(e);for(const e of dB(s))s.getObjectExtension(e,"KHR_draco_mesh_compression")},decode:async function(e,t,i){var s;if(null==t||null===(s=t.gltf)||void 0===s||!s.decompressMeshes)return;const r=new mx(e),o=[];for(const e of dB(r))r.getObjectExtension(e,"KHR_draco_mesh_compression")&&o.push(cB(r,e,t,i));await Promise.all(o),r.removeExtension("KHR_draco_mesh_compression")},encode:function(e,t={}){const i=new mx(e);for(const e of i.json.meshes||[])uB(e),i.addRequiredExtension("KHR_draco_mesh_compression")}});var fB=Object.freeze({__proto__:null,name:"KHR_lights_punctual",decode:async function(e){const t=new mx(e),{json:i}=t,s=t.getExtension("KHR_lights_punctual");s&&(t.json.lights=s.lights,t.removeExtension("KHR_lights_punctual"));for(const e of i.nodes||[]){const i=t.getObjectExtension(e,"KHR_lights_punctual");i&&(e.light=i.light),t.removeObjectExtension(e,"KHR_lights_punctual")}},encode:async function(e){const t=new mx(e),{json:i}=t;if(i.lights){const e=t.addExtension("KHR_lights_punctual");ox(!e.lights),e.lights=i.lights,delete i.lights}if(t.json.lights){for(const e of t.json.lights){const i=e.node;t.addObjectExtension(i,"KHR_lights_punctual",e)}delete t.json.lights}}});function gB(e,t){const i=Object.assign({},e.values);return Object.keys(e.uniforms||{}).forEach((t=>{e.uniforms[t].value&&!(t in i)&&(i[t]=e.uniforms[t].value)})),Object.keys(i).forEach((e=>{"object"==typeof i[e]&&void 0!==i[e].index&&(i[e].texture=t.getTexture(i[e].index))})),i}const mB=[Mx,Ex,Fx,pB,fB,Object.freeze({__proto__:null,name:"KHR_materials_unlit",decode:async function(e){const t=new mx(e),{json:i}=t;t.removeExtension("KHR_materials_unlit");for(const e of i.materials||[]){e.extensions&&e.extensions.KHR_materials_unlit&&(e.unlit=!0),t.removeObjectExtension(e,"KHR_materials_unlit")}},encode:function(e){const t=new mx(e),{json:i}=t;if(t.materials)for(const e of i.materials||[])e.unlit&&(delete e.unlit,t.addObjectExtension(e,"KHR_materials_unlit",{}),t.addExtension("KHR_materials_unlit"))}}),Object.freeze({__proto__:null,name:"KHR_techniques_webgl",decode:async function(e){const t=new mx(e),{json:i}=t,s=t.getExtension("KHR_techniques_webgl");if(s){const e=function(e,t){const{programs:i=[],shaders:s=[],techniques:r=[]}=e,o=new TextDecoder;return s.forEach((e=>{if(!Number.isFinite(e.bufferView))throw new Error("KHR_techniques_webgl: no shader code");e.code=o.decode(t.getTypedArrayForBufferView(e.bufferView))})),i.forEach((e=>{e.fragmentShader=s[e.fragmentShader],e.vertexShader=s[e.vertexShader]})),r.forEach((e=>{e.program=i[e.program]})),r}(s,t);for(const s of i.materials||[]){const i=t.getObjectExtension(s,"KHR_techniques_webgl");i&&(s.technique=Object.assign({},i,e[i.technique]),s.technique.values=gB(s.technique,t)),t.removeObjectExtension(s,"KHR_techniques_webgl")}t.removeExtension("KHR_techniques_webgl")}},encode:async function(e,t){}})];function _B(e,t){var i;const s=(null==t||null===(i=t.gltf)||void 0===i?void 0:i.excludeExtensions)||{};return!(e in s&&!s[e])}const vB={accessors:"accessor",animations:"animation",buffers:"buffer",bufferViews:"bufferView",images:"image",materials:"material",meshes:"mesh",nodes:"node",samplers:"sampler",scenes:"scene",skins:"skin",textures:"texture"},bB={accessor:"accessors",animations:"animation",buffer:"buffers",bufferView:"bufferViews",image:"images",material:"materials",mesh:"meshes",node:"nodes",sampler:"samplers",scene:"scenes",skin:"skins",texture:"textures"};class yB{constructor(){tv(this,"idToIndexMap",{animations:{},accessors:{},buffers:{},bufferViews:{},images:{},materials:{},meshes:{},nodes:{},samplers:{},scenes:{},skins:{},textures:{}}),tv(this,"json",void 0)}normalize(e,t){this.json=e.json;const i=e.json;switch(i.asset&&i.asset.version){case"2.0":return;case void 0:case"1.0":break;default:return void console.warn("glTF: Unknown version ".concat(i.asset.version))}if(!t.normalize)throw new Error("glTF v1 is not supported.");console.warn("Converting glTF v1 to glTF v2 format. This is experimental and may fail."),this._addAsset(i),this._convertTopLevelObjectsToArrays(i),function(e){const t=new mx(e),{json:i}=t;for(const e of i.images||[]){const i=t.getObjectExtension(e,"KHR_binary_glTF");i&&Object.assign(e,i),t.removeObjectExtension(e,"KHR_binary_glTF")}i.buffers&&i.buffers[0]&&delete i.buffers[0].uri,t.removeExtension("KHR_binary_glTF")}(e),this._convertObjectIdsToArrayIndices(i),this._updateObjects(i),this._updateMaterial(i)}_addAsset(e){e.asset=e.asset||{},e.asset.version="2.0",e.asset.generator=e.asset.generator||"Normalized to glTF 2.0 by loaders.gl"}_convertTopLevelObjectsToArrays(e){for(const t in vB)this._convertTopLevelObjectToArray(e,t)}_convertTopLevelObjectToArray(e,t){const i=e[t];if(i&&!Array.isArray(i)){e[t]=[];for(const s in i){const r=i[s];r.id=r.id||s;const o=e[t].length;e[t].push(r),this.idToIndexMap[t][s]=o}}}_convertObjectIdsToArrayIndices(e){for(const t in vB)this._convertIdsToIndices(e,t);"scene"in e&&(e.scene=this._convertIdToIndex(e.scene,"scene"));for(const t of e.textures)this._convertTextureIds(t);for(const t of e.meshes)this._convertMeshIds(t);for(const t of e.nodes)this._convertNodeIds(t);for(const t of e.scenes)this._convertSceneIds(t)}_convertTextureIds(e){e.source&&(e.source=this._convertIdToIndex(e.source,"image"))}_convertMeshIds(e){for(const t of e.primitives){const{attributes:e,indices:i,material:s}=t;for(const t in e)e[t]=this._convertIdToIndex(e[t],"accessor");i&&(t.indices=this._convertIdToIndex(i,"accessor")),s&&(t.material=this._convertIdToIndex(s,"material"))}}_convertNodeIds(e){e.children&&(e.children=e.children.map((e=>this._convertIdToIndex(e,"node")))),e.meshes&&(e.meshes=e.meshes.map((e=>this._convertIdToIndex(e,"mesh"))))}_convertSceneIds(e){e.nodes&&(e.nodes=e.nodes.map((e=>this._convertIdToIndex(e,"node"))))}_convertIdsToIndices(e,t){e[t]||(console.warn("gltf v1: json doesn't contain attribute ".concat(t)),e[t]=[]);for(const i of e[t])for(const e in i){const t=i[e],s=this._convertIdToIndex(t,e);i[e]=s}}_convertIdToIndex(e,t){const i=bB[t];if(i in this.idToIndexMap){const s=this.idToIndexMap[i][e];if(!Number.isFinite(s))throw new Error("gltf v1: failed to resolve ".concat(t," with id ").concat(e));return s}return e}_updateObjects(e){for(const e of this.json.buffers)delete e.type}_updateMaterial(e){for(const s of e.materials){var t,i;s.pbrMetallicRoughness={baseColorFactor:[1,1,1,1],metallicFactor:1,roughnessFactor:1};const r=(null===(t=s.values)||void 0===t?void 0:t.tex)||(null===(i=s.values)||void 0===i?void 0:i.texture2d_0),o=e.textures.findIndex((e=>e.id===r));-1!==o&&(s.pbrMetallicRoughness.baseColorTexture={index:o})}}}const xB={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},BB={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},wB=10240,PB=10241,CB=10242,MB=10243,EB=10497,FB={magFilter:wB,minFilter:PB,wrapS:CB,wrapT:MB},IB={[wB]:9729,[PB]:9986,[CB]:EB,[MB]:EB};class DB{constructor(){tv(this,"baseUri",""),tv(this,"json",{}),tv(this,"buffers",[]),tv(this,"images",[])}postProcess(e,t={}){const{json:i,buffers:s=[],images:r=[],baseUri:o=""}=e;return ox(i),this.baseUri=o,this.json=i,this.buffers=s,this.images=r,this._resolveTree(this.json,t),this.json}_resolveTree(e,t={}){e.bufferViews&&(e.bufferViews=e.bufferViews.map(((e,t)=>this._resolveBufferView(e,t)))),e.images&&(e.images=e.images.map(((e,t)=>this._resolveImage(e,t)))),e.samplers&&(e.samplers=e.samplers.map(((e,t)=>this._resolveSampler(e,t)))),e.textures&&(e.textures=e.textures.map(((e,t)=>this._resolveTexture(e,t)))),e.accessors&&(e.accessors=e.accessors.map(((e,t)=>this._resolveAccessor(e,t)))),e.materials&&(e.materials=e.materials.map(((e,t)=>this._resolveMaterial(e,t)))),e.meshes&&(e.meshes=e.meshes.map(((e,t)=>this._resolveMesh(e,t)))),e.nodes&&(e.nodes=e.nodes.map(((e,t)=>this._resolveNode(e,t)))),e.skins&&(e.skins=e.skins.map(((e,t)=>this._resolveSkin(e,t)))),e.scenes&&(e.scenes=e.scenes.map(((e,t)=>this._resolveScene(e,t)))),void 0!==e.scene&&(e.scene=e.scenes[this.json.scene])}getScene(e){return this._get("scenes",e)}getNode(e){return this._get("nodes",e)}getSkin(e){return this._get("skins",e)}getMesh(e){return this._get("meshes",e)}getMaterial(e){return this._get("materials",e)}getAccessor(e){return this._get("accessors",e)}getCamera(e){return null}getTexture(e){return this._get("textures",e)}getSampler(e){return this._get("samplers",e)}getImage(e){return this._get("images",e)}getBufferView(e){return this._get("bufferViews",e)}getBuffer(e){return this._get("buffers",e)}_get(e,t){if("object"==typeof t)return t;const i=this.json[e]&&this.json[e][t];return i||console.warn("glTF file error: Could not find ".concat(e,"[").concat(t,"]")),i}_resolveScene(e,t){return e.id=e.id||"scene-".concat(t),e.nodes=(e.nodes||[]).map((e=>this.getNode(e))),e}_resolveNode(e,t){return e.id=e.id||"node-".concat(t),e.children&&(e.children=e.children.map((e=>this.getNode(e)))),void 0!==e.mesh?e.mesh=this.getMesh(e.mesh):void 0!==e.meshes&&e.meshes.length&&(e.mesh=e.meshes.reduce(((e,t)=>{const i=this.getMesh(t);return e.id=i.id,e.primitives=e.primitives.concat(i.primitives),e}),{primitives:[]})),void 0!==e.camera&&(e.camera=this.getCamera(e.camera)),void 0!==e.skin&&(e.skin=this.getSkin(e.skin)),e}_resolveSkin(e,t){return e.id=e.id||"skin-".concat(t),e.inverseBindMatrices=this.getAccessor(e.inverseBindMatrices),e}_resolveMesh(e,t){return e.id=e.id||"mesh-".concat(t),e.primitives&&(e.primitives=e.primitives.map((e=>{const t=(e={...e}).attributes;e.attributes={};for(const i in t)e.attributes[i]=this.getAccessor(t[i]);return void 0!==e.indices&&(e.indices=this.getAccessor(e.indices)),void 0!==e.material&&(e.material=this.getMaterial(e.material)),e}))),e}_resolveMaterial(e,t){if(e.id=e.id||"material-".concat(t),e.normalTexture&&(e.normalTexture={...e.normalTexture},e.normalTexture.texture=this.getTexture(e.normalTexture.index)),e.occlusionTexture&&(e.occlustionTexture={...e.occlustionTexture},e.occlusionTexture.texture=this.getTexture(e.occlusionTexture.index)),e.emissiveTexture&&(e.emmisiveTexture={...e.emmisiveTexture},e.emissiveTexture.texture=this.getTexture(e.emissiveTexture.index)),e.emissiveFactor||(e.emissiveFactor=e.emmisiveTexture?[1,1,1]:[0,0,0]),e.pbrMetallicRoughness){e.pbrMetallicRoughness={...e.pbrMetallicRoughness};const t=e.pbrMetallicRoughness;t.baseColorTexture&&(t.baseColorTexture={...t.baseColorTexture},t.baseColorTexture.texture=this.getTexture(t.baseColorTexture.index)),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture={...t.metallicRoughnessTexture},t.metallicRoughnessTexture.texture=this.getTexture(t.metallicRoughnessTexture.index))}return e}_resolveAccessor(e,t){var i,s;if(e.id=e.id||"accessor-".concat(t),void 0!==e.bufferView&&(e.bufferView=this.getBufferView(e.bufferView)),e.bytesPerComponent=(i=e.componentType,BB[i]),e.components=(s=e.type,xB[s]),e.bytesPerElement=e.bytesPerComponent*e.components,e.bufferView){const t=e.bufferView.buffer,{ArrayType:i,byteLength:s}=fx(e,e.bufferView),r=(e.bufferView.byteOffset||0)+(e.byteOffset||0)+t.byteOffset;let o=t.arrayBuffer.slice(r,r+s);e.bufferView.byteStride&&(o=this._getValueFromInterleavedBuffer(t,r,e.bufferView.byteStride,e.bytesPerElement,e.count)),e.value=new i(o)}return e}_getValueFromInterleavedBuffer(e,t,i,s,r){const o=new Uint8Array(r*s);for(let n=0;n20);const s=t.getUint32(i+0,TB),r=t.getUint32(i+4,TB);return i+=8,z_(0===r),LB(e,t,i,s),i+=s,i+=UB(e,t,i,e.header.byteLength)}(e,r,i);case 2:return function(e,t,i,s){return z_(e.header.byteLength>20),function(e,t,i,s){for(;i+8<=e.header.byteLength;){const r=t.getUint32(i+0,TB),o=t.getUint32(i+4,TB);switch(i+=8,o){case 1313821514:LB(e,t,i,r);break;case 5130562:UB(e,t,i,r);break;case 0:s.strict||LB(e,t,i,r);break;case 1:s.strict||UB(e,t,i,r)}i+=wv(r,4)}}(e,t,i,s),i+e.header.byteLength}(e,r,i,{});default:throw new Error("Invalid GLB version ".concat(e.version,". Only supports v1 and v2."))}}function LB(e,t,i,s){const r=new Uint8Array(t.buffer,i,s),o=new TextDecoder("utf8").decode(r);return e.json=JSON.parse(o),wv(s,4)}function UB(e,t,i,s){return e.header.hasBinChunk=!0,e.binChunks.push({byteOffset:i,byteLength:s,arrayBuffer:t.buffer}),wv(s,4)}async function OB(e,t,i=0,s,r){var o,n,a,l;!function(e,t,i,s){s.uri&&(e.baseUri=s.uri);if(t instanceof ArrayBuffer&&!function(e,t=0,i={}){const s=new DataView(e),{magic:r=SB}=i,o=s.getUint32(t,!1);return o===r||o===SB}(t,i,s)){t=(new TextDecoder).decode(t)}if("string"==typeof t)e.json=bv(t);else if(t instanceof ArrayBuffer){const r={};i=RB(r,t,i,s.glb),ox("glTF"===r.type,"Invalid GLB magic string ".concat(r.type)),e._glb=r,e.json=r.json}else ox(!1,"GLTF: must be ArrayBuffer or string");const r=e.json.buffers||[];if(e.buffers=new Array(r.length).fill(null),e._glb&&e._glb.header.hasBinChunk){const{binChunks:t}=e._glb;e.buffers[0]={arrayBuffer:t[0].arrayBuffer,byteOffset:t[0].byteOffset,byteLength:t[0].byteLength}}const o=e.json.images||[];e.images=new Array(o.length).fill({})}(e,t,i,s),function(e,t={}){(new yB).normalize(e,t)}(e,{normalize:null==s||null===(o=s.gltf)||void 0===o?void 0:o.normalize}),function(e,t={},i){const s=mB.filter((e=>_B(e.name,t)));for(const o of s){var r;null===(r=o.preprocess)||void 0===r||r.call(o,e,t,i)}}(e,s,r);const A=[];if(null!=s&&null!==(n=s.gltf)&&void 0!==n&&n.loadBuffers&&e.json.buffers&&await async function(e,t,i){const s=e.json.buffers||[];for(let n=0;n_B(e.name,t)));for(const o of s){var r;await(null===(r=o.decode)||void 0===r?void 0:r.call(o,e,t,i))}}(e,s,r);return A.push(h),await Promise.all(A),null!=s&&null!==(l=s.gltf)&&void 0!==l&&l.postProcess?function(e,t){return(new DB).postProcess(e,t)}(e,s):e}async function kB(e,t,i,s,r){const{fetch:o,parse:n}=r;let a;if(t.uri){const e=nx(t.uri,s),i=await o(e);a=await i.arrayBuffer()}if(Number.isFinite(t.bufferView)){const i=function(e,t,i){const s=e.bufferViews[i];ox(s);const r=t[s.buffer];ox(r);const o=(s.byteOffset||0)+r.byteOffset;return new Uint8Array(r.arrayBuffer,o,s.byteLength)}(e.json,e.buffers,t.bufferView);a=Bv(i.buffer,i.byteOffset,i.byteLength)}ox(a,"glTF image has no data");let l=await n(a,[tx,ky],{mimeType:t.mimeType,basis:s.basis||{format:Oy()}},r);l&&l[0]&&(l={compressed:!0,mipmaps:!1,width:l[0].width,height:l[0].height,data:l[0]}),e.images=e.images||[],e.images[i]=l}const NB={name:"glTF",id:"gltf",module:"gltf",version:"3.2.6",extensions:["gltf","glb"],mimeTypes:["model/gltf+json","model/gltf-binary"],text:!0,binary:!0,tests:["glTF"],parse:async function(e,t={},i){(t={...NB.options,...t}).gltf={...NB.options.gltf,...t.gltf};const{byteOffset:s=0}=t;return await OB({},e,s,t,i)},options:{gltf:{normalize:!0,loadBuffers:!0,loadImages:!0,decompressMeshes:!0,postProcess:!0},log:console},deprecatedOptions:{fetchImages:"gltf.loadImages",createImages:"gltf.loadImages",decompress:"gltf.decompressMeshes",postProcess:"gltf.postProcess",gltf:{decompress:"gltf.decompressMeshes"}}};class QB{constructor(e){}load(e,t,i,s,r,o,n){!function(e,t,i,s,r,o,n){const a=e.viewer.scene.canvas.spinner;a.processes++;"glb"===t.split(".").pop()?e.dataSource.getGLB(t,(n=>{s.basePath=VB(t),HB(e,t,n,i,s,r,o),a.processes--}),(e=>{a.processes--,n(e)})):e.dataSource.getGLTF(t,(n=>{s.basePath=VB(t),HB(e,t,n,i,s,r,o),a.processes--}),(e=>{a.processes--,n(e)}))}(e,t,i,s=s||{},r,(function(){M.scheduleTask((function(){r.scene.fire("modelLoaded",r.id),r.fire("loaded",!0,!1)})),o&&o()}),(function(t){e.error(t),n&&n(t),r.fire("error",t)}))}parse(e,t,i,s,r,o,n){HB(e,"",t,i,s=s||{},r,(function(){r.scene.fire("modelLoaded",r.id),r.fire("loaded",!0,!1),o&&o()}))}}function VB(e){const t=e.lastIndexOf("/");return 0!==t?e.substring(0,t+1):""}function HB(e,t,i,s,r,o,n){const a=e.viewer.scene.canvas.spinner;a.processes++,ry(i,NB,{baseUri:r.basePath}).then((i=>{const l={src:t,entityId:r.entityId,metaModelJSON:s,autoMetaModel:r.autoMetaModel,globalizeObjectIds:r.globalizeObjectIds,metaObjects:[],loadBuffer:r.loadBuffer,basePath:r.basePath,handlenode:r.handlenode,backfaces:!!r.backfaces,gltfData:i,scene:o.scene,plugin:e,sceneModel:o,numObjects:0,nodes:[],nextId:0,log:t=>{e.log(t)}};!function(e){const t=e.gltfData.textures;if(t)for(let i=0,s=t.length;i{const i=t.mesh;i&&(i.instances||=0,i.instances+=1),t.children&&e(t.children)}))}(s);const r=[];let o=null;!function t(i,s,n){i.forEach((i=>{const a=i.name;let l=null!=a&&a||0===s&&"entity-"+e.nextId++;if(l){for(;e.sceneModel.objects[l];)l="entity-"+e.nextId++;r.push(o),o=[]}const A=function(e,t){let i;e.matrix&&(i=e.matrix,t=t?c.mulMat4(t,i,c.mat4()):i);e.translation&&(i=c.translationMat4v(e.translation),t=t?c.mulMat4(t,i,c.mat4()):i);e.rotation&&(i=c.quaternionToMat4(e.rotation),t=t?c.mulMat4(t,i,c.mat4()):i);e.scale&&(i=c.scalingMat4v(e.scale),t=t?c.mulMat4(t,i,c.mat4()):i);return t}(i,n);if(i.mesh&&function(e,t,i,s){const r=e.mesh;if(!r)return;const o=r.primitives.length;if(o>0)for(let e=0;e0){const t=e.globalizeObjectIds?c.globalizeObjectId(e.sceneModel.id,l):l;e.sceneModel.createEntity({id:t,meshIds:o,isObject:!0}),e.autoMetaModel&&e.metaObjects.push({id:t,type:"Default",name:t,parent:e.sceneModel.id})}o=r.pop()}}))}(s,0,null)}(l),o.finalize(),r.autoMetaModel&&e.viewer.metaScene.createMetaModel(o.id,{metaObjects:l.metaObjects}),a.processes--,n()}))}function jB(e,t){if(!t.source||!t.source.image)return;const i="texture-"+e.nextId++;let s=1005;switch(t.sampler.minFilter){case 9728:s=1003;break;case 9729:s=1006;break;case 9984:s=1004;break;case 9985:s=1007;break;case 9986:s=1005;break;case 9987:s=1008}let r=1006;switch(t.sampler.magFilter){case 9728:r=1003;break;case 9729:r=1006}let o=1e3;switch(t.sampler.wrapS){case 33071:o=1001;break;case 33648:o=1002;break;case 10497:o=1e3}let n=1e3;switch(t.sampler.wrapT){case 33071:n=1001;break;case 33648:n=1002;break;case 10497:n=1e3}let a=1e3;switch(t.sampler.wrapR){case 33071:a=1001;break;case 33648:a=1002;break;case 10497:a=1e3}e.sceneModel.createTexture({id:i,image:t.source.image,flipY:!!t.flipY,minFilter:s,magFilter:r,wrapS:o,wrapT:n,wrapR:a,encoding:3001}),t._textureId=i}function GB(e,t){const i={};switch(t.normalTexture&&(i.normalTextureId=t.normalTexture.texture._textureId),t.occlusionTexture&&(i.occlusionTextureId=t.occlusionTexture.texture._textureId),t.emissiveTexture&&(i.emissiveTextureId=t.emissiveTexture.texture._textureId),t.alphaMode){case"OPAQUE":break;case"MASK":const e=t.alphaCutoff;i.alphaCutoff=void 0!==e?e:.5}const s=t.pbrMetallicRoughness;if(t.pbrMetallicRoughness){const r=t.pbrMetallicRoughness,o=r.baseColorTexture||r.colorTexture;o&&(o.texture?i.colorTextureId=o.texture._textureId:i.colorTextureId=e.gltfData.textures[o.index]._textureId),s.metallicRoughnessTexture&&(i.metallicRoughnessTextureId=s.metallicRoughnessTexture.texture._textureId)}const r=t.extensions;if(r){const t=r.KHR_materials_pbrSpecularGlossiness;if(t){t.specularTexture;const s=t.specularColorTexture;null!=s&&(i.colorTextureId=e.gltfData.textures[s.index]._textureId)}}return void 0!==i.normalTextureId||void 0!==i.occlusionTextureId||void 0!==i.emissiveTextureId||void 0!==i.colorTextureId||void 0!==i.metallicRoughnessTextureId?(i.id=`textureSet-${e.nextId++};`,e.sceneModel.createTextureSet(i),i.id):null}function zB(e,t){const i=t.extensions,s={color:new Float32Array([1,1,1,1]),opacity:1,metallic:0,roughness:1,doubleSided:!0};if(i){const e=i.KHR_materials_pbrSpecularGlossiness;if(e){const t=e.diffuseFactor;null!=t&&s.color.set(t)}const t=i.KHR_materials_common;if(t){const e=t.technique,i=t.values||{},r="BLINN"===e,o="PHONG"===e,n="LAMBERT"===e,a=i.diffuse;a&&(r||o||n)&&(_.isString(a)||s.color.set(a));const l=i.transparency;null!=l&&(s.opacity=l);const A=i.transparent;null!=A&&(s.opacity=A)}}const r=t.pbrMetallicRoughness;if(r){const e=r.baseColorFactor;e&&(s.color[0]=e[0],s.color[1]=e[1],s.color[2]=e[2],s.opacity=e[3]);const t=r.metallicFactor;null!=t&&(s.metallic=t);const i=r.roughnessFactor;null!=i&&(s.roughness=i)}return s.doubleSided=!1!==t.doubleSided,s}const WB={DEFAULT:{}};function KB(e,t,i={}){const s="lightgrey",r=i.hoverColor||"rgba(0,0,0,0.4)",o=i.textColor||"black",n=500,a=n+n/3,l=a/24,A=[{boundary:[6,6,6,6],color:i.frontColor||i.color||"#55FF55"},{boundary:[18,6,6,6],color:i.backColor||i.color||"#55FF55"},{boundary:[12,6,6,6],color:i.rightColor||i.color||"#FF5555"},{boundary:[0,6,6,6],color:i.leftColor||i.color||"#FF5555"},{boundary:[6,0,6,6],color:i.topColor||i.color||"#7777FF"},{boundary:[6,12,6,6],color:i.bottomColor||i.color||"#7777FF"}],h=[{label:"NavCube.front",boundaries:[[7,7,4,4]],dir:[0,1,0],up:[0,0,1]},{label:"NavCube.back",boundaries:[[19,7,4,4]],dir:[0,-1,0],up:[0,0,1]},{label:"NavCube.right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,0,1]},{label:"NavCube.left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,0,1]},{label:"NavCube.top",boundaries:[[7,1,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"NavCube.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]}];i.frontColor||i.color,i.backColor||i.color,i.rightColor||i.color,i.leftColor||i.color,i.topColor||i.color,i.bottomColor||i.color;const u=[{yUp:"",label:"NavCube.front",boundaries:[[7,7,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"NavCube.back",boundaries:[[19,7,4,4]],dir:[0,0,1],up:[0,1,0]},{label:"NavCube.right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,1,0]},{label:"NavCube.left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,1,0]},{label:"NavCube.top",boundaries:[[7,1,4,4]],dir:[0,-1,0],up:[0,0,-1]},{label:"NavCube.bottom",boundaries:[[7,13,4,4]],dir:[0,1,0],up:[0,0,1]},{boundaries:[[7,5,4,2]],dir:[0,-.7071,-.7071],up:[0,.7071,-.7071]},{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,-.7071,.7071],up:[0,.7071,.7071]},{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:[.5,.7071,-.5],up:[-.5,.7071,.5]},{boundaries:[[23,11,1,1],[6,17,1,1],[0,11,1,1]],dir:[.5,.7071,.5],up:[-.5,.7071,-.5]},{boundaries:[[5,5,2,2]],dir:[.5,-.7071,-.5],up:[.5,.7071,-.5]},{boundaries:[[11,17,1,1],[17,11,2,1]],dir:[-.5,.7071,.5],up:[.5,.7071,-.5]},{boundaries:[[17,6,2,1],[11,0,1,1]],dir:[-.5,-.7071,.5],up:[-.5,.7071,.5]},{boundaries:[[11,11,2,2]],dir:[-.5,.7071,-.5],up:[.5,.7071,.5]},{boundaries:[[0,6,1,1],[6,0,1,1],[23,6,1,1]],dir:[.5,-.7071,.5],up:[.5,.7071,.5]},{boundaries:[[11,5,2,2]],dir:[-.5,-.7071,-.5],up:[-.5,.7071,-.5]}];for(let e=0,t=h.length;e=r[0]*l&&t<=(r[0]+r[2])*l&&i>=r[1]*l&&i<=(r[1]+r[3])*l)return s}}return-1},this.setAreaHighlighted=function(e,t){var i=d[e];if(!i)throw"Area not found: "+e;i.highlighted=!!t,g()},this.getAreaDir=function(e){var t=d[e];if(!t)throw"Unknown area: "+e;return t.dir},this.getAreaUp=function(e){var t=d[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)}}const XB=c.vec3(),JB=c.vec3();c.mat4();const YB=c.vec3();class ZB{load(e,t,i={}){var s=e.scene.canvas.spinner;s.processes++,qB(e,t,(function(t){!function(e,t,i){for(var s=t.basePath,r=Object.keys(t.materialLibraries),o=r.length,n=0,a=o;n=0?i-1:i+t/3)}function r(e,t){var i=parseInt(e,10);return 3*(i>=0?i-1:i+t/3)}function o(e,t){var i=parseInt(e,10);return 2*(i>=0?i-1:i+t/2)}function n(e,t,i,s){var r=e.positions,o=e.object.geometry.positions;o.push(r[t+0]),o.push(r[t+1]),o.push(r[t+2]),o.push(r[i+0]),o.push(r[i+1]),o.push(r[i+2]),o.push(r[s+0]),o.push(r[s+1]),o.push(r[s+2])}function a(e,t){var i=e.positions,s=e.object.geometry.positions;s.push(i[t+0]),s.push(i[t+1]),s.push(i[t+2])}function l(e,t,i,s){var r=e.normals,o=e.object.geometry.normals;o.push(r[t+0]),o.push(r[t+1]),o.push(r[t+2]),o.push(r[i+0]),o.push(r[i+1]),o.push(r[i+2]),o.push(r[s+0]),o.push(r[s+1]),o.push(r[s+2])}function A(e,t,i,s){var r=e.uv,o=e.object.geometry.uv;o.push(r[t+0]),o.push(r[t+1]),o.push(r[i+0]),o.push(r[i+1]),o.push(r[s+0]),o.push(r[s+1])}function h(e,t){var i=e.uv,s=e.object.geometry.uv;s.push(i[t+0]),s.push(i[t+1])}function c(e,t,i,a,h,c,u,d,p,f,g,m,_){var v,b=e.positions.length,y=s(t,b),x=s(i,b),B=s(a,b);if(void 0===h?n(e,y,x,B):(n(e,y,x,v=s(h,b)),n(e,x,B,v)),void 0!==c){var w=e.uv.length;y=o(c,w),x=o(u,w),B=o(d,w),void 0===h?A(e,y,x,B):(A(e,y,x,v=o(p,w)),A(e,x,B,v))}if(void 0!==f){var P=e.normals.length;y=r(f,P),x=f===g?y:r(g,P),B=f===m?y:r(m,P),void 0===h?l(e,y,x,B):(l(e,y,x,v=r(_,P)),l(e,x,B,v))}}function u(e,t,i){e.object.geometry.type="Line";for(var r=e.positions.length,n=e.uv.length,l=0,A=t.length;l=0?n.substring(0,a):n).toLowerCase(),A=(A=a>=0?n.substring(a+1):"").trim(),l.toLowerCase()){case"newmtl":i(e,u),u={id:A},d=!0;break;case"ka":u.ambient=s(A);break;case"kd":u.diffuse=s(A);break;case"ks":u.specular=s(A);break;case"map_kd":u.diffuseMap||(u.diffuseMap=t(e,o,A,"sRGB"));break;case"map_ks":u.specularMap||(u.specularMap=t(e,o,A,"linear"));break;case"map_bump":case"bump":u.normalMap||(u.normalMap=t(e,o,A));break;case"ns":u.shininess=parseFloat(A);break;case"d":(h=parseFloat(A))<1&&(u.alpha=h,u.alphaMode="blend");break;case"tr":(h=parseFloat(A))>0&&(u.alpha=1-h,u.alphaMode="blend")}d&&i(e,u)};function t(e,t,i,s){var r={},o=i.split(/\s+/),n=o.indexOf("-bm");return n>=0&&o.splice(n,2),(n=o.indexOf("-s"))>=0&&(r.scale=[parseFloat(o[n+1]),parseFloat(o[n+2])],o.splice(n,4)),(n=o.indexOf("-o"))>=0&&(r.translate=[parseFloat(o[n+1]),parseFloat(o[n+2])],o.splice(n,4)),r.src=t+o.join(" ").trim(),r.flipY=!0,r.encoding=s||"linear",new Ss(e,r).id}function i(e,t){new Jt(e,t)}function s(t){var i=t.split(e,3);return[parseFloat(i[0]),parseFloat(i[1]),parseFloat(i[2])]}}();function iw(e,t){for(var i=0,s=t.objects.length;i0&&(n.normals=o.normals),o.uv.length>0&&(n.uv=o.uv);for(var a=new Array(n.positions.length/3),l=0;l{this._setPos(this._sectionPlane.pos)})),this._onSectionPlaneDir=e.on("dir",(()=>{this._ignoreNextSectionPlaneDirUpdate?this._ignoreNextSectionPlaneDirUpdate=!1:this._setDir(this._sectionPlane.dir)})))}get sectionPlane(){return this._sectionPlane}_setPos(e){this._pos.set(e),W(this._pos,this._origin,this._rtcPos),this._rootNode.origin=this._origin,this._rootNode.position=this._rtcPos}_setDir(e){this._baseDir.set(e),this._rootNode.quaternion=c.vec3PairToQuaternion(rw,e,ow)}_setSectionPlaneDir(e){this._sectionPlane&&(this._ignoreNextSectionPlaneDirUpdate=!0,this._sectionPlane.dir=e)}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=!1,t=this._viewer.scene,i=.01;this._rootNode=new gs(t,{position:[0,0,0],scale:[5,5,5],isObject:!1});const s=this._rootNode,r={arrowHead:new Gt(s,is({radiusTop:.001,radiusBottom:.07,radialSegments:32,heightSegments:1,height:.2,openEnded:!1})),arrowHeadBig:new Gt(s,is({radiusTop:.001,radiusBottom:.09,radialSegments:32,heightSegments:1,height:.25,openEnded:!1})),arrowHeadHandle:new Gt(s,is({radiusTop:.09,radiusBottom:.09,radialSegments:8,heightSegments:1,height:.37,openEnded:!1})),curve:new Gt(s,Qs({radius:.8,tube:i,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),curveHandle:new Gt(s,Qs({radius:.8,tube:.06,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),hoop:new Gt(s,Qs({radius:.8,tube:i,radialSegments:64,tubeSegments:8,arc:2*Math.PI})),axis:new Gt(s,is({radiusTop:i,radiusBottom:i,radialSegments:20,heightSegments:1,height:1,openEnded:!1})),axisHandle:new Gt(s,is({radiusTop:.08,radiusBottom:.08,radialSegments:20,heightSegments:1,height:1,openEnded:!1}))},o={pickable:new Jt(s,{diffuse:[1,1,0],alpha:0,alphaMode:"blend"}),red:new Jt(s,{diffuse:[1,0,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightRed:new Zt(s,{edges:!1,fill:!0,fillColor:[1,0,0],fillAlpha:.6}),green:new Jt(s,{diffuse:[0,1,0],emissive:[0,1,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightGreen:new Zt(s,{edges:!1,fill:!0,fillColor:[0,1,0],fillAlpha:.6}),blue:new Jt(s,{diffuse:[0,0,1],emissive:[0,0,1],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightBlue:new Zt(s,{edges:!1,fill:!0,fillColor:[0,0,1],fillAlpha:.2}),center:new Jt(s,{diffuse:[0,0,0],emissive:[0,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80}),highlightBall:new Zt(s,{edges:!1,fill:!0,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1}),highlightPlane:new Zt(s,{edges:!0,edgeWidth:3,fill:!1,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1})};this._displayMeshes={plane:s.addChild(new es(s,{geometry:new Gt(s,{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 Jt(s,{emissive:[0,0,0],diffuse:[0,0,0],backfaces:!0}),opacity:.6,ghosted:!0,ghostMaterial:new Zt(s,{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],isObject:!1}),e),planeFrame:s.addChild(new es(s,{geometry:new Gt(s,Qs({center:[0,0,0],radius:1.7,tube:.02,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new Jt(s,{emissive:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],shininess:0}),highlightMaterial:new Zt(s,{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],isObject:!1}),e),xCurve:s.addChild(new es(s,{geometry:r.curve,material:o.red,matrix:function(){const e=c.rotationMat4v(90*c.DEGTORAD,[0,1,0],c.identityMat4()),t=c.rotationMat4v(270*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xCurveHandle:s.addChild(new es(s,{geometry:r.curveHandle,material:o.pickable,matrix:function(){const e=c.rotationMat4v(90*c.DEGTORAD,[0,1,0],c.identityMat4()),t=c.rotationMat4v(270*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xCurveArrow1:s.addChild(new es(s,{geometry:r.arrowHead,material:o.red,matrix:function(){const e=c.translateMat4c(0,-.07,-.8,c.identityMat4()),t=c.scaleMat4v([.6,.6,.6],c.identityMat4()),i=c.rotationMat4v(0*c.DEGTORAD,[0,0,1],c.identityMat4());return c.mulMat4(c.mulMat4(e,t,c.identityMat4()),i,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xCurveArrow2:s.addChild(new es(s,{geometry:r.arrowHead,material:o.red,matrix:function(){const e=c.translateMat4c(0,-.8,-.07,c.identityMat4()),t=c.scaleMat4v([.6,.6,.6],c.identityMat4()),i=c.rotationMat4v(90*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(c.mulMat4(e,t,c.identityMat4()),i,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yCurve:s.addChild(new es(s,{geometry:r.curve,material:o.green,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),yCurveHandle:s.addChild(new es(s,{geometry:r.curveHandle,material:o.pickable,rotation:[-90,0,0],pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),yCurveArrow1:s.addChild(new es(s,{geometry:r.arrowHead,material:o.green,matrix:function(){const e=c.translateMat4c(.07,0,-.8,c.identityMat4()),t=c.scaleMat4v([.6,.6,.6],c.identityMat4()),i=c.rotationMat4v(90*c.DEGTORAD,[0,0,1],c.identityMat4());return c.mulMat4(c.mulMat4(e,t,c.identityMat4()),i,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yCurveArrow2:s.addChild(new es(s,{geometry:r.arrowHead,material:o.green,matrix:function(){const e=c.translateMat4c(.8,0,-.07,c.identityMat4()),t=c.scaleMat4v([.6,.6,.6],c.identityMat4()),i=c.rotationMat4v(90*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(c.mulMat4(e,t,c.identityMat4()),i,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurve:s.addChild(new es(s,{geometry:r.curve,material:o.blue,matrix:c.rotationMat4v(180*c.DEGTORAD,[1,0,0],c.identityMat4()),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveHandle:s.addChild(new es(s,{geometry:r.curveHandle,material:o.pickable,matrix:c.rotationMat4v(180*c.DEGTORAD,[1,0,0],c.identityMat4()),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveCurveArrow1:s.addChild(new es(s,{geometry:r.arrowHead,material:o.blue,matrix:function(){const e=c.translateMat4c(.8,-.07,0,c.identityMat4()),t=c.scaleMat4v([.6,.6,.6],c.identityMat4());return c.mulMat4(e,t,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveArrow2:s.addChild(new es(s,{geometry:r.arrowHead,material:o.blue,matrix:function(){const e=c.translateMat4c(.05,-.8,0,c.identityMat4()),t=c.scaleMat4v([.6,.6,.6],c.identityMat4()),i=c.rotationMat4v(90*c.DEGTORAD,[0,0,1],c.identityMat4());return c.mulMat4(c.mulMat4(e,t,c.identityMat4()),i,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),center:s.addChild(new es(s,{geometry:new Gt(s,ss({radius:.05})),material:o.center,pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisArrow:s.addChild(new es(s,{geometry:r.arrowHead,material:o.red,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[0,0,1],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisArrowHandle:s.addChild(new es(s,{geometry:r.arrowHeadHandle,material:o.pickable,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[0,0,1],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxis:s.addChild(new es(s,{geometry:r.axis,material:o.red,matrix:function(){const e=c.translateMat4c(0,.5,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[0,0,1],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisHandle:s.addChild(new es(s,{geometry:r.axisHandle,material:o.pickable,matrix:function(){const e=c.translateMat4c(0,.5,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[0,0,1],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrow:s.addChild(new es(s,{geometry:r.arrowHead,material:o.green,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(180*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrowHandle:s.addChild(new es(s,{geometry:r.arrowHeadHandle,material:o.pickable,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(180*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,opacity:.2,isObject:!1}),e),yShaft:s.addChild(new es(s,{geometry:r.axis,material:o.green,position:[0,-.5,0],pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yShaftHandle:s.addChild(new es(s,{geometry:r.axisHandle,material:o.pickable,position:[0,-.5,0],pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrow:s.addChild(new es(s,{geometry:r.arrowHead,material:o.blue,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[.8,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrowHandle:s.addChild(new es(s,{geometry:r.arrowHeadHandle,material:o.pickable,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[.8,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zShaft:s.addChild(new es(s,{geometry:r.axis,material:o.blue,matrix:function(){const e=c.translateMat4c(0,.5,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),clippable:!1,pickable:!1,collidable:!0,visible:!1,isObject:!1}),e),zAxisHandle:s.addChild(new es(s,{geometry:r.axisHandle,material:o.pickable,matrix:function(){const e=c.translateMat4c(0,.5,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),clippable:!1,pickable:!0,collidable:!0,visible:!1,isObject:!1}),e)},this._affordanceMeshes={planeFrame:s.addChild(new es(s,{geometry:new Gt(s,Qs({center:[0,0,0],radius:2,tube:i,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new Jt(s,{ambient:[1,1,1],diffuse:[0,0,0],emissive:[1,1,0]}),highlighted:!0,highlightMaterial:new Zt(s,{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],isObject:!1}),e),xHoop:s.addChild(new es(s,{geometry:r.hoop,material:o.red,highlighted:!0,highlightMaterial:o.highlightRed,matrix:function(){const e=c.rotationMat4v(90*c.DEGTORAD,[0,1,0],c.identityMat4()),t=c.rotationMat4v(270*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yHoop:s.addChild(new es(s,{geometry:r.hoop,material:o.green,highlighted:!0,highlightMaterial:o.highlightGreen,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zHoop:s.addChild(new es(s,{geometry:r.hoop,material:o.blue,highlighted:!0,highlightMaterial:o.highlightBlue,matrix:c.rotationMat4v(180*c.DEGTORAD,[1,0,0],c.identityMat4()),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xAxisArrow:s.addChild(new es(s,{geometry:r.arrowHeadBig,material:o.red,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[0,0,1],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrow:s.addChild(new es(s,{geometry:r.arrowHeadBig,material:o.green,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(180*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrow:s.addChild(new es(s,{geometry:r.arrowHeadBig,material:o.blue,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[.8,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e)}}_bindEvents(){const e=this;var t=!1;const i=-1,s=0,r=1,o=2,n=3,a=4,l=5,A=this._rootNode;var h=null,u=null;const d=c.vec2(),p=c.vec3([1,0,0]),f=c.vec3([0,1,0]),g=c.vec3([0,0,1]),m=this._viewer.scene.canvas.canvas,_=this._viewer.camera,v=this._viewer.scene;{const e=c.vec3([0,0,0]);let t=-1;this._onCameraViewMatrix=v.camera.on("viewMatrix",(()=>{})),this._onCameraProjMatrix=v.camera.on("projMatrix",(()=>{})),this._onSceneTick=v.on("tick",(()=>{const i=Math.abs(c.lenVec3(c.subVec3(v.camera.eye,this._pos,e)));if(i!==t&&"perspective"===_.projection){const e=.07*(Math.tan(_.perspective.fov*c.DEGTORAD)*i);A.scale=[e,e,e],t=i}if("ortho"===_.projection){const e=_.ortho.scale/10;A.scale=[e,e,e],t=i}}))}const b=function(){const e=new Float64Array(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}}(),y=function(){const t=c.mat4();return function(i,s){return c.quaternionToMat4(e._rootNode.quaternion,t),c.transformVec3(t,i,s),c.normalizeVec3(s),s}}();var x=function(){const e=c.vec3();return function(t){const i=Math.abs(t[0]);return i>Math.abs(t[1])&&i>Math.abs(t[2])?c.cross3Vec3(t,[0,1,0],e):c.cross3Vec3(t,[1,0,0],e),c.cross3Vec3(e,t,e),c.normalizeVec3(e),e}}();const B=function(){const t=c.vec3(),i=c.vec3(),s=c.vec4();return function(r,o,n){y(r,s);const a=x(s,o,n);P(o,a,t),P(n,a,i),c.subVec3(i,t);const l=c.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 w=function(){const t=c.vec4(),i=c.vec4(),s=c.vec4(),r=c.vec4();return function(o,n,a){y(o,r);if(!(P(n,r,t)&&P(a,r,i))){const e=x(r,n,a);P(n,e,t,1),P(a,e,i,1);var l=c.dotVec3(t,r);t[0]-=l*r[0],t[1]-=l*r[1],t[2]-=l*r[2],l=c.dotVec3(i,r),i[0]-=l*r[0],i[1]-=l*r[1],i[2]-=l*r[2]}c.normalizeVec3(t),c.normalizeVec3(i),l=c.dotVec3(t,i),l=c.clamp(l,-1,1);var A=Math.acos(l)*c.RADTODEG;c.cross3Vec3(t,i,s),c.dotVec3(s,r)<0&&(A=-A),e._rootNode.rotate(o,A),C()}}(),P=function(){const t=c.vec4([0,0,0,1]),i=c.mat4();return function(s,r,o,n){n=n||0,t[0]=s[0]/m.width*2-1,t[1]=-(s[1]/m.height*2-1),t[2]=0,t[3]=1,c.mulMat4(_.projMatrix,_.viewMatrix,i),c.inverseMat4(i),c.transformVec4(i,t,t),c.mulVec4Scalar(t,1/t[3]);var a=_.eye;c.subVec4(t,a,t);const l=e._sectionPlane.pos;var A=-c.dotVec3(l,r)-n,h=c.dotVec3(r,t);if(Math.abs(h)>.005){var u=-(c.dotVec3(r,a)+A)/h;return c.mulVec3Scalar(t,u,o),c.addVec3(o,a),c.subVec3(o,l,o),!0}return!1}}();const C=function(){const t=c.vec3(),i=c.mat4();return function(){e.sectionPlane&&(c.quaternionToMat4(A.quaternion,i),c.transformVec3(i,[0,0,1],t),e._setSectionPlaneDir(t))}}();var M,E=!1;this._onCameraControlHover=this._viewer.cameraControl.on("hoverEnter",(e=>{if(!this._visible)return;if(E)return;var A;t=!1,M&&(M.visible=!1);switch(e.entity.id){case this._displayMeshes.xAxisArrowHandle.id:case this._displayMeshes.xAxisHandle.id:A=this._affordanceMeshes.xAxisArrow,h=s;break;case this._displayMeshes.yAxisArrowHandle.id:case this._displayMeshes.yShaftHandle.id:A=this._affordanceMeshes.yAxisArrow,h=r;break;case this._displayMeshes.zAxisArrowHandle.id:case this._displayMeshes.zAxisHandle.id:A=this._affordanceMeshes.zAxisArrow,h=o;break;case this._displayMeshes.xCurveHandle.id:A=this._affordanceMeshes.xHoop,h=n;break;case this._displayMeshes.yCurveHandle.id:A=this._affordanceMeshes.yHoop,h=a;break;case this._displayMeshes.zCurveHandle.id:A=this._affordanceMeshes.zHoop,h=l;break;default:return void(h=i)}A&&(A.visible=!0),M=A,t=!0})),this._onCameraControlHoverLeave=this._viewer.cameraControl.on("hoverOutEntity",(e=>{this._visible&&(M&&(M.visible=!1),M=null,h=i)})),m.addEventListener("mousedown",this._canvasMouseDownListener=e=>{if(e.preventDefault(),this._visible&&t&&(this._viewer.cameraControl.pointerEnabled=!1,1===e.which)){E=!0;var i=b(e);u=h,d[0]=i[0],d[1]=i[1]}}),m.addEventListener("mousemove",this._canvasMouseMoveListener=e=>{if(!this._visible)return;if(!E)return;var t=b(e);const i=t[0],A=t[1];switch(u){case s:B(p,d,t);break;case r:B(f,d,t);break;case o:B(g,d,t);break;case n:w(p,d,t);break;case a:w(f,d,t);break;case l:w(g,d,t)}d[0]=i,d[1]=A}),m.addEventListener("mouseup",this._canvasMouseUpListener=e=>{this._visible&&(this._viewer.cameraControl.pointerEnabled=!0,E&&(e.which,E=!1,t=!1))}),m.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._setSectionPlane(null),this._rootNode.destroy(),this._displayMeshes={},this._affordanceMeshes={}}}class aw{constructor(e,t,i){this.id=i.id,this._sectionPlane=i,this._mesh=new es(t,{id:i.id,geometry:new Gt(t,zt({xSize:.5,ySize:.5,zSize:.001})),material:new Jt(t,{emissive:[1,1,1],diffuse:[0,0,0],backfaces:!1}),edgeMaterial:new $t(t,{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),highlightMaterial:new Zt(t,{fill:!0,fillColor:[.5,1,.5],fillAlpha:.7,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),selectedMaterial:new Zt(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=c.vec3([0,0,0]),t=c.vec3(),i=c.vec3([0,0,1]),s=c.vec4(4),r=c.vec3(),o=()=>{const o=this._sectionPlane.scene.center,n=[-this._sectionPlane.dir[0],-this._sectionPlane.dir[1],-this._sectionPlane.dir[2]];c.subVec3(o,this._sectionPlane.pos,e);const a=-c.dotVec3(n,e);c.normalizeVec3(n),c.mulVec3Scalar(n,a,t);const l=c.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 lw{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 Ai(this._viewer,{canvasId:this._canvas.id,transparent:!0}),this._scene.clearLights(),new Dt(this._scene,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new Dt(this._scene,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new Dt(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=c.rotationMat4c(-90*c.DEGTORAD,1,0,0),i=c.vec3(),s=c.vec3(),r=c.vec3();this._synchCamera=()=>{const o=this._viewer.camera.eye,n=this._viewer.camera.look,a=this._viewer.camera.up;c.mulVec3Scalar(c.normalizeVec3(c.subVec3(o,n,i)),7),this._zUp?(c.transformVec3(t,i,s),c.transformVec3(t,a,r),e.look=[0,0,0],e.eye=c.transformVec3(t,i,s),e.up=c.transformPoint3(t,a,r)):(e.look=[0,0,0],e.eye=i,e.up=a)}}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}));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 aw(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._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 Aw=c.AABB3(),hw=c.vec3();class cw{constructor(e,t,i,s,r,o){this.plugin=e,this.storeyId=r,this.modelId=s,this.storeyAABB=i.slice(),this.aabb=this.storeyAABB,this.modelAABB=t.slice(),this.numObjects=o}}class uw{constructor(e,t,i,s,r,o){this.storeyId=e,this.imageData=t,this.format=i,this.width=s,this.height=r}}const dw=c.vec3(),pw=c.mat4();const fw=new Float64Array([0,0,1]),gw=new Float64Array(4);class mw{constructor(e){this.id=null,this._viewer=e.viewer,this._plugin=e,this._visible=!1,this._pos=c.vec3(),this._origin=c.vec3(),this._rtcPos=c.vec3(),this._baseDir=c.vec3(),this._rootNode=null,this._displayMeshes=null,this._affordanceMeshes=null,this._ignoreNextSectionPlaneDirUpdate=!1,this._createNodes(),this._bindEvents()}_setSectionPlane(e){this._sectionPlane&&(this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._onSectionPlanePos=null,this._onSectionPlaneDir=null,this._sectionPlane=null),e&&(this.id=e.id,this._setPos(e.pos),this._setDir(e.dir),this._sectionPlane=e,this._onSectionPlanePos=e.on("pos",(()=>{this._setPos(this._sectionPlane.pos)})),this._onSectionPlaneDir=e.on("dir",(()=>{this._ignoreNextSectionPlaneDirUpdate?this._ignoreNextSectionPlaneDirUpdate=!1:this._setDir(this._sectionPlane.dir)})))}get sectionPlane(){return this._sectionPlane}_setPos(e){this._pos.set(e),W(this._pos,this._origin,this._rtcPos),this._rootNode.origin=this._origin,this._rootNode.position=this._rtcPos}_setDir(e){this._baseDir.set(e),this._rootNode.quaternion=c.vec3PairToQuaternion(fw,e,gw)}_setSectionPlaneDir(e){this._sectionPlane&&(this._ignoreNextSectionPlaneDirUpdate=!0,this._sectionPlane.dir=e)}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=!1,t=this._viewer.scene,i=.01;this._rootNode=new gs(t,{position:[0,0,0],scale:[5,5,5]});const s=this._rootNode,r={arrowHead:new Gt(s,is({radiusTop:.001,radiusBottom:.07,radialSegments:32,heightSegments:1,height:.2,openEnded:!1})),arrowHeadBig:new Gt(s,is({radiusTop:.001,radiusBottom:.09,radialSegments:32,heightSegments:1,height:.25,openEnded:!1})),axis:new Gt(s,is({radiusTop:i,radiusBottom:i,radialSegments:20,heightSegments:1,height:1,openEnded:!1}))},o={red:new Jt(s,{diffuse:[1,0,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),green:new Jt(s,{diffuse:[0,1,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),blue:new Jt(s,{diffuse:[0,0,1],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightRed:new Zt(s,{edges:!1,fill:!0,fillColor:[1,0,0],fillAlpha:.6})};this._displayMeshes={plane:s.addChild(new es(s,{geometry:new Gt(s,{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 Jt(s,{emissive:[0,0,0],diffuse:[0,0,0],backfaces:!0}),opacity:.6,ghosted:!0,pickable:!1,collidable:!0,clippable:!1,visible:!1,scale:[2.4,2.4,1]}),e),planeFrame:s.addChild(new es(s,{geometry:new Gt(s,Qs({center:[0,0,0],radius:1.7,tube:.02,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new Jt(s,{emissive:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],shininess:0}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,.1],rotation:[0,0,45]}),e),center:s.addChild(new es(s,{geometry:new Gt(s,ss({radius:.05})),material:o.center,pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),zAxisArrow:s.addChild(new es(s,{geometry:r.arrowHead,material:o.blue,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[.8,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),zShaft:s.addChild(new es(s,{geometry:r.axis,material:o.blue,matrix:function(){const e=c.translateMat4c(0,.5,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[1,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),clippable:!1,pickable:!1,collidable:!0,visible:!1}),e)},this._affordanceMeshes={planeFrame:s.addChild(new es(s,{geometry:new Gt(s,Qs({center:[0,0,0],radius:2,tube:i,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new Jt(s,{ambient:[1,1,1],diffuse:[0,0,0],emissive:[1,1,0]}),highlighted:!0,highlightMaterial:new Zt(s,{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]}),e),zAxisArrow:s.addChild(new es(s,{geometry:r.arrowHeadBig,material:o.blue,matrix:function(){const e=c.translateMat4c(0,1.1,0,c.identityMat4()),t=c.rotationMat4v(-90*c.DEGTORAD,[.8,0,0],c.identityMat4());return c.mulMat4(t,e,c.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e)}}_bindEvents(){const e=this._rootNode,t=c.vec2(),i=this._viewer.camera,s=this._viewer.scene;let r=0,o=!1;{const t=c.vec3([0,0,0]);let n=-1;this._onCameraViewMatrix=s.camera.on("viewMatrix",(()=>{})),this._onCameraProjMatrix=s.camera.on("projMatrix",(()=>{})),this._onSceneTick=s.on("tick",(()=>{o=!1;const l=Math.abs(c.lenVec3(c.subVec3(s.camera.eye,this._pos,t)));if(l!==n&&"perspective"===i.projection){const t=.07*(Math.tan(i.perspective.fov*c.DEGTORAD)*l);e.scale=[t,t,t],n=l}if("ortho"===i.projection){const t=i.ortho.scale/10;e.scale=[t,t,t],n=l}0!==r&&(a(r),r=0)}))}const n=function(){const e=new Float64Array(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}}(),a=e=>{const t=this._sectionPlane.pos,i=this._sectionPlane.dir;c.addVec3(t,c.mulVec3Scalar(i,.1*e*this._plugin.getDragSensitivity(),c.vec3())),this._sectionPlane.pos=t};{let e=!1;this._plugin._controlElement.addEventListener("mousedown",this._canvasMouseDownListener=i=>{if(i.preventDefault(),this._visible&&(this._viewer.cameraControl.pointerEnabled=!1,1===i.which)){e=!0;var s=n(i);t[0]=s[0],t[1]=s[1]}}),this._plugin._controlElement.addEventListener("mousemove",this._canvasMouseMoveListener=i=>{if(!this._visible)return;if(!e)return;if(o)return;var s=n(i);const r=s[0],l=s[1];a(l-t[1]),t[0]=r,t[1]=l}),this._plugin._controlElement.addEventListener("mouseup",this._canvasMouseUpListener=t=>{this._visible&&(this._viewer.cameraControl.pointerEnabled=!0,e&&(t.which,e=!1))}),this._plugin._controlElement.addEventListener("wheel",this._canvasWheelListener=e=>{this._visible&&(r+=Math.max(-1,Math.min(1,40*-e.deltaY)))})}{let e,t,i=null;this._plugin._controlElement.addEventListener("touchstart",this._handleTouchStart=t=>{t.stopPropagation(),t.preventDefault(),this._visible&&(e=t.touches[0].clientY,i=e,r=0)}),this._plugin._controlElement.addEventListener("touchmove",this._handleTouchMove=e=>{e.stopPropagation(),e.preventDefault(),this._visible&&(o||(o=!0,t=e.touches[0].clientY,null!==i&&(r+=t-i),i=t))}),this._plugin._controlElement.addEventListener("touchend",this._handleTouchEnd=i=>{i.stopPropagation(),i.preventDefault(),this._visible&&(e=null,t=null,r=0)})}}_destroy(){this._unbindEvents(),this._destroyNodes()}_unbindEvents(){const e=this._viewer,t=e.scene,i=t.canvas.canvas,s=e.camera,r=this._plugin._controlElement;t.off(this._onSceneTick),i.removeEventListener("mousedown",this._canvasMouseDownListener),i.removeEventListener("mousemove",this._canvasMouseMoveListener),i.removeEventListener("mouseup",this._canvasMouseUpListener),i.removeEventListener("wheel",this._canvasWheelListener),r.removeEventListener("touchstart",this._handleTouchStart),r.removeEventListener("touchmove",this._handleTouchMove),r.removeEventListener("touchend",this._handleTouchEnd),s.off(this._onCameraViewMatrix),s.off(this._onCameraProjMatrix)}_destroyNodes(){this._setSectionPlane(null),this._rootNode.destroy(),this._displayMeshes={},this._affordanceMeshes={}}}class _w{constructor(e,t,i){this.id=i.id,this._sectionPlane=i,this._mesh=new es(t,{id:i.id,geometry:new Gt(t,zt({xSize:.5,ySize:.5,zSize:.001})),material:new Jt(t,{emissive:[1,1,1],diffuse:[0,0,0],backfaces:!1}),edgeMaterial:new $t(t,{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),highlightMaterial:new Zt(t,{fill:!0,fillColor:[.5,1,.5],fillAlpha:.7,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),selectedMaterial:new Zt(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=c.vec3([0,0,0]),t=c.vec3(),i=c.vec3([0,0,1]),s=c.vec4(4),r=c.vec3(),o=()=>{const o=this._sectionPlane.scene.center,n=[-this._sectionPlane.dir[0],-this._sectionPlane.dir[1],-this._sectionPlane.dir[2]];c.subVec3(o,this._sectionPlane.pos,e);const a=-c.dotVec3(n,e);c.normalizeVec3(n),c.mulVec3Scalar(n,a,t);const l=c.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 vw{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 Ai(this._viewer,{canvasId:this._canvas.id,transparent:!0}),this._scene.clearLights(),new Dt(this._scene,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new Dt(this._scene,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new Dt(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=c.rotationMat4c(-90*c.DEGTORAD,1,0,0),i=c.vec3(),s=c.vec3(),r=c.vec3();this._synchCamera=()=>{const o=this._viewer.camera.eye,n=this._viewer.camera.look,a=this._viewer.camera.up;c.mulVec3Scalar(c.normalizeVec3(c.subVec3(o,n,i)),7),this._zUp?(c.transformVec3(t,i,s),c.transformVec3(t,a,r),e.look=[0,0,0],e.eye=c.transformVec3(t,i,s),e.up=c.transformPoint3(t,a,r)):(e.look=[0,0,0],e.eye=i,e.up=a)}}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}));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 _w(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._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 bw=c.AABB3(),yw=c.vec3();class xw{constructor(e={}){this.cacheBuster=!1!==e.cacheBuster}_cacheBusterURL(e){if(!this.cacheBuster)return e;const t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}getSTL(e,t,i){e=this._cacheBusterURL(e);const s=new XMLHttpRequest;s.overrideMimeType("application/json"),s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i(s.statusText))},s.send(null)}}const Bw=c.vec3();class ww{load(e,t,i,s,r,o){s=s||{};const n=e.viewer.scene.canvas.spinner;n.processes++,e.dataSource.getSTL(i,(function(i){!function(e,t,i,s){try{const r=Iw(i);Pw(r)?Cw(e,r,t,s):Mw(e,Fw(i),t,s)}catch(e){t.fire("error",e)}}(e,t,i,s);try{const o=Iw(i);Pw(o)?Cw(e,o,t,s):Mw(e,Fw(i),t,s),n.processes--,M.scheduleTask((function(){t.fire("loaded",!0,!1)})),r&&r()}catch(i){n.processes--,e.error(i),o&&o(i),t.fire("error",i)}}),(function(i){n.processes--,e.error(i),o&&o(i),t.fire("error",i)}))}parse(e,t,i,s){const r=e.viewer.scene.canvas.spinner;r.processes++;try{const o=Iw(i);Pw(o)?Cw(e,o,t,s):Mw(e,Fw(i),t,s),r.processes--,M.scheduleTask((function(){t.fire("loaded",!0,!1)}))}catch(e){r.processes--,t.fire("error",e)}}}function Pw(e){const t=new DataView(e);if(84+50*t.getUint32(80,!0)===t.byteLength)return!0;const i=[115,111,108,105,100];for(var s=0;s<5;s++)if(i[s]!==t.getUint8(s,!1))return!0;return!1}function Cw(e,t,i,s){const r=new DataView(t),o=r.getUint32(80,!0);let n,a,l,A,h,c,u,d=!1,p=null,f=null,g=null,m=!1;for(let e=0;e<70;e++)1129270351===r.getUint32(e,!1)&&82===r.getUint8(e+4)&&61===r.getUint8(e+5)&&(d=!0,A=[],h=r.getUint8(e+6)/255,c=r.getUint8(e+7)/255,u=r.getUint8(e+8)/255,r.getUint8(e+9));const _=new bs(i,{roughness:.5});let v=[],b=[],y=s.splitMeshes;for(let e=0;e>5&31)/31,l=(e>>10&31)/31):(n=h,a=c,l=u),(y&&n!==p||a!==f||l!==g)&&(null!==p&&(m=!0),p=n,f=a,g=l)}for(let e=1;e<=3;e++){let i=t+12*e;v.push(r.getFloat32(i,!0)),v.push(r.getFloat32(i+4,!0)),v.push(r.getFloat32(i+8,!0)),b.push(o,x,B),d&&A.push(n,a,l,1)}y&&m&&(Ew(i,v,b,A,_,s),v=[],b=[],A=A?[]:null,m=!1)}v.length>0&&Ew(i,v,b,A,_,s)}function Mw(e,t,i,s){const r=/facet([\s\S]*?)endfacet/g;let o=0;const n=/[\s]+([+-]?(?:\d+.\d+|\d+.|\d+|.\d+)(?:[eE][+-]?\d+)?)/.source,a=new RegExp("vertex"+n+n+n,"g"),l=new RegExp("normal"+n+n+n,"g"),A=[],h=[];let c,u,d,p,f,g,m;for(;null!==(p=r.exec(t));){for(f=0,g=0,m=p[0];null!==(p=l.exec(m));)c=parseFloat(p[1]),u=parseFloat(p[2]),d=parseFloat(p[3]),g++;for(;null!==(p=a.exec(m));)A.push(parseFloat(p[1]),parseFloat(p[2]),parseFloat(p[3])),h.push(c,u,d),f++;1!==g&&e.error("Error in normal of face "+o),3!==f&&e.error("Error in positions of face "+o),o++}Ew(i,A,h,null,new bs(i,{roughness:.5}),s)}function Ew(e,t,i,s,r,o){const n=new Int32Array(t.length/3);for(let e=0,t=n.length;e0?i:null,s=s&&s.length>0?s:null,o.smoothNormals&&c.faceToVertexNormals(t,i,o);const a=Bw;K(t,t,a);const l=new Gt(e,{primitive:"triangles",positions:t,normals:i,colors:s,indices:n}),A=new es(e,{origin:0!==a[0]||0!==a[1]||0!==a[2]?a:null,geometry:l,material:r,edges:o.edges});e.addChild(A)}function Fw(e){return"string"!=typeof e?function(e){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let i=0,s=e.length;i0){const i=document.createElement("a");i.href="#",i.id=`switch-${e.nodeId}`,i.textContent="+",i.classList.add("plus"),t&&i.addEventListener("click",t),o.appendChild(i)}const n=document.createElement("input");n.id=`checkbox-${e.nodeId}`,n.type="checkbox",n.checked=e.checked,n.style["pointer-events"]="all",i&&n.addEventListener("change",i),o.appendChild(n);const a=document.createElement("span");return a.textContent=e.title,o.appendChild(a),s&&(a.oncontextmenu=s),r&&(a.onclick=r),o}createDisabledNodeElement(e){const t=document.createElement("li"),i=document.createElement("a");i.href="#",i.textContent="!",i.classList.add("warn"),i.classList.add("warning"),t.appendChild(i);const s=document.createElement("span");return s.textContent=e,t.appendChild(s),t}addChildren(e,t){const i=document.createElement("ul");t.forEach((e=>{i.appendChild(e)})),e.parentElement.appendChild(i)}expand(e,t,i){e.classList.remove("plus"),e.classList.add("minus"),e.textContent="-",e.removeEventListener("click",t),e.addEventListener("click",i)}collapse(e,t,i){if(!e)return;const s=e.parentElement;if(!s)return;const r=s.querySelector("ul");r&&(s.removeChild(r),e.classList.remove("minus"),e.classList.add("plus"),e.textContent="+",e.removeEventListener("click",i),e.addEventListener("click",t))}isExpanded(e){return void 0!==e.parentElement.getElementsByTagName("li")[0]}getId(e){return e.parentElement.id}getIdFromCheckbox(e){return e.id.replace("checkbox-","")}getSwitchElement(e){return document.getElementById(`switch-${e}`)}isChecked(e){return e.checked}setCheckbox(e,t,i=!1){const s=document.getElementById(`checkbox-${e}`);s&&(t!==s.checked&&(s.checked=t),i!==s.indeterminate&&(s.indeterminate=i,i&&(s.checked=!1)))}setXRayed(e,t){const i=document.getElementById(e);i&&(t?i.classList.add("xrayed-node"):i.classList.remove("xrayed-node"))}setHighlighted(e,t){const i=document.getElementById(e);i&&(t?(i.scrollIntoView({block:"center"}),i.classList.add("highlighted-node")):i.classList.remove("highlighted-node"))}}const Sw=[];class Tw{constructor(e){this._scene=e,this._objects=[],this._objectsViewCulled=[],this._objectsDetailCulled=[],this._objectsChanged=[],this._objectsChangedList=[],this._modelInfos={},this._numObjects=0,this._lenObjectsChangedList=0,this._dirty=!0,this._onModelLoaded=e.on("modelLoaded",(t=>{const i=e.models[t];i&&this._addModel(i)})),this._onTick=e.on("tick",(()=>{this._dirty&&this._build(),this._applyChanges()}))}_addModel(e){const t={model:e,onDestroyed:e.on("destroyed",(()=>{this._removeModel(e)}))};this._modelInfos[e.id]=t,this._dirty=!0}_removeModel(e){const t=this._modelInfos[e.id];t&&(t.model.off(t.onDestroyed),delete this._modelInfos[e.id],this._dirty=!0)}_build(){if(!this._dirty)return;this._applyChanges();const e=this._scene.objects;for(let e=0;e0){for(let e=0;e-1?e+"&_="+t:e+"?_="+t}getManifest(e,t,i){_.loadJSON(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getMetaModel(e,t,i){_.loadJSON(this._cacheBusterURL(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),i=new Uint8Array(e);for(var n=0;n=0;)e[t]=0}const i=new Uint8Array([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]),s=new Uint8Array([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]),r=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),o=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),n=new Array(576);t(n);const a=new Array(60);t(a);const l=new Array(512);t(l);const A=new Array(256);t(A);const h=new Array(29);t(h);const c=new Array(30);function u(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}let d,p,f;function g(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}t(c);const m=e=>e<256?l[e]:l[256+(e>>>7)],_=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},v=(e,t,i)=>{e.bi_valid>16-i?(e.bi_buf|=t<>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<{v(e,i[2*t],i[2*t+1])},y=(e,t)=>{let i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1},x=(e,t,i)=>{const s=new Array(16);let r,o,n=0;for(r=1;r<=15;r++)n=n+i[r-1]<<1,s[r]=n;for(o=0;o<=t;o++){let t=e[2*o+1];0!==t&&(e[2*o]=y(s[t]++,t))}},B=e=>{let t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},w=e=>{e.bi_valid>8?_(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},P=(e,t,i,s)=>{const r=2*t,o=2*i;return e[r]{const s=e.heap[i];let r=i<<1;for(;r<=e.heap_len&&(r{let o,n,a,l,u=0;if(0!==e.sym_next)do{o=255&e.pending_buf[e.sym_buf+u++],o+=(255&e.pending_buf[e.sym_buf+u++])<<8,n=e.pending_buf[e.sym_buf+u++],0===o?b(e,n,t):(a=A[n],b(e,a+256+1,t),l=i[a],0!==l&&(n-=h[a],v(e,n,l)),o--,a=m(o),b(e,a,r),l=s[a],0!==l&&(o-=c[a],v(e,o,l)))}while(u{const i=t.dyn_tree,s=t.stat_desc.static_tree,r=t.stat_desc.has_stree,o=t.stat_desc.elems;let n,a,l,A=-1;for(e.heap_len=0,e.heap_max=573,n=0;n>1;n>=1;n--)C(e,i,n);l=o;do{n=e.heap[1],e.heap[1]=e.heap[e.heap_len--],C(e,i,1),a=e.heap[1],e.heap[--e.heap_max]=n,e.heap[--e.heap_max]=a,i[2*l]=i[2*n]+i[2*a],e.depth[l]=(e.depth[n]>=e.depth[a]?e.depth[n]:e.depth[a])+1,i[2*n+1]=i[2*a+1]=l,e.heap[1]=l++,C(e,i,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const i=t.dyn_tree,s=t.max_code,r=t.stat_desc.static_tree,o=t.stat_desc.has_stree,n=t.stat_desc.extra_bits,a=t.stat_desc.extra_base,l=t.stat_desc.max_length;let A,h,c,u,d,p,f=0;for(u=0;u<=15;u++)e.bl_count[u]=0;for(i[2*e.heap[e.heap_max]+1]=0,A=e.heap_max+1;A<573;A++)h=e.heap[A],u=i[2*i[2*h+1]+1]+1,u>l&&(u=l,f++),i[2*h+1]=u,h>s||(e.bl_count[u]++,d=0,h>=a&&(d=n[h-a]),p=i[2*h],e.opt_len+=p*(u+d),o&&(e.static_len+=p*(r[2*h+1]+d)));if(0!==f){do{for(u=l-1;0===e.bl_count[u];)u--;e.bl_count[u]--,e.bl_count[u+1]+=2,e.bl_count[l]--,f-=2}while(f>0);for(u=l;0!==u;u--)for(h=e.bl_count[u];0!==h;)c=e.heap[--A],c>s||(i[2*c+1]!==u&&(e.opt_len+=(u-i[2*c+1])*i[2*c],i[2*c+1]=u),h--)}})(e,t),x(i,A,e.bl_count)},F=(e,t,i)=>{let s,r,o=-1,n=t[1],a=0,l=7,A=4;for(0===n&&(l=138,A=3),t[2*(i+1)+1]=65535,s=0;s<=i;s++)r=n,n=t[2*(s+1)+1],++a{let s,r,o=-1,n=t[1],a=0,l=7,A=4;for(0===n&&(l=138,A=3),s=0;s<=i;s++)if(r=n,n=t[2*(s+1)+1],!(++a{v(e,0+(s?1:0),3),w(e),_(e,i),_(e,~i),i&&e.pending_buf.set(e.window.subarray(t,t+i),e.pending),e.pending+=i};var T={_tr_init:e=>{D||((()=>{let e,t,o,g,m;const _=new Array(16);for(o=0,g=0;g<28;g++)for(h[g]=o,e=0;e<1<>=7;g<30;g++)for(c[g]=m<<7,e=0;e<1<{let r,l,A=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0})(e)),E(e,e.l_desc),E(e,e.d_desc),A=(e=>{let t;for(F(e,e.dyn_ltree,e.l_desc.max_code),F(e,e.dyn_dtree,e.d_desc.max_code),E(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*o[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t})(e),r=e.opt_len+3+7>>>3,l=e.static_len+3+7>>>3,l<=r&&(r=l)):r=l=i+5,i+4<=r&&-1!==t?S(e,t,i,s):4===e.strategy||l===r?(v(e,2+(s?1:0),3),M(e,n,a)):(v(e,4+(s?1:0),3),((e,t,i,s)=>{let r;for(v(e,t-257,5),v(e,i-1,5),v(e,s-4,4),r=0;r(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(A[i]+256+1)]++,e.dyn_dtree[2*m(t)]++),e.sym_next===e.sym_end),_tr_align:e=>{v(e,2,3),b(e,256,n),(e=>{16===e.bi_valid?(_(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)}},R=(e,t,i,s)=>{let r=65535&e|0,o=e>>>16&65535|0,n=0;for(;0!==i;){n=i>2e3?2e3:i,i-=n;do{r=r+t[s++]|0,o=o+r|0}while(--n);r%=65521,o%=65521}return r|o<<16|0};const L=new Uint32Array((()=>{let e,t=[];for(var 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})());var U=(e,t,i,s)=>{const r=L,o=s+i;e^=-1;for(let i=s;i>>8^r[255&(e^t[i])];return-1^e},O={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"},k={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_MEM_ERROR:-4,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};const{_tr_init:N,_tr_stored_block:Q,_tr_flush_block:V,_tr_tally:H,_tr_align:j}=T,{Z_NO_FLUSH:G,Z_PARTIAL_FLUSH:z,Z_FULL_FLUSH:W,Z_FINISH:K,Z_BLOCK:X,Z_OK:J,Z_STREAM_END:Y,Z_STREAM_ERROR:Z,Z_DATA_ERROR:q,Z_BUF_ERROR:$,Z_DEFAULT_COMPRESSION:ee,Z_FILTERED:te,Z_HUFFMAN_ONLY:ie,Z_RLE:se,Z_FIXED:re,Z_DEFAULT_STRATEGY:oe,Z_UNKNOWN:ne,Z_DEFLATED:ae}=k,le=258,Ae=262,he=42,ce=113,ue=666,de=(e,t)=>(e.msg=O[t],t),pe=e=>2*e-(e>4?9:0),fe=e=>{let t=e.length;for(;--t>=0;)e[t]=0},ge=e=>{let t,i,s,r=e.w_size;t=e.hash_size,s=t;do{i=e.head[--s],e.head[s]=i>=r?i-r:0}while(--t);t=r,s=t;do{i=e.prev[--s],e.prev[s]=i>=r?i-r:0}while(--t)};let me=(e,t,i)=>(t<{const t=e.state;let i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,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))},ve=(e,t)=>{V(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,_e(e.strm)},be=(e,t)=>{e.pending_buf[e.pending++]=t},ye=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},xe=(e,t,i,s)=>{let r=e.avail_in;return r>s&&(r=s),0===r?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),i),1===e.state.wrap?e.adler=R(e.adler,t,r,i):2===e.state.wrap&&(e.adler=U(e.adler,t,r,i)),e.next_in+=r,e.total_in+=r,r)},Be=(e,t)=>{let i,s,r=e.max_chain_length,o=e.strstart,n=e.prev_length,a=e.nice_match;const l=e.strstart>e.w_size-Ae?e.strstart-(e.w_size-Ae):0,A=e.window,h=e.w_mask,c=e.prev,u=e.strstart+le;let d=A[o+n-1],p=A[o+n];e.prev_length>=e.good_match&&(r>>=2),a>e.lookahead&&(a=e.lookahead);do{if(i=t,A[i+n]===p&&A[i+n-1]===d&&A[i]===A[o]&&A[++i]===A[o+1]){o+=2,i++;do{}while(A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&on){if(e.match_start=t,n=s,s>=a)break;d=A[o+n-1],p=A[o+n]}}}while((t=c[t&h])>l&&0!=--r);return n<=e.lookahead?n:e.lookahead},we=e=>{const t=e.w_size;let i,s,r;do{if(s=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-Ae)&&(e.window.set(e.window.subarray(t,t+t-s),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),ge(e),s+=t),0===e.strm.avail_in)break;if(i=xe(e.strm,e.window,e.strstart+e.lookahead,s),e.lookahead+=i,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=me(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=me(e,e.ins_h,e.window[r+3-1]),e.prev[r&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=r,r++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead{let i,s,r,o=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,n=0,a=e.strm.avail_in;do{if(i=65535,r=e.bi_valid+42>>3,e.strm.avail_outs+e.strm.avail_in&&(i=s+e.strm.avail_in),i>r&&(i=r),i>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,_e(e.strm),s&&(s>i&&(s=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+s),e.strm.next_out),e.strm.next_out+=s,e.strm.avail_out-=s,e.strm.total_out+=s,e.block_start+=s,i-=s),i&&(xe(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i)}while(0===n);return a-=e.strm.avail_in,a&&(a>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=a&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-a,e.strm.next_in),e.strstart),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.block_start=e.strstart),e.high_waterr&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,r+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),r>e.strm.avail_in&&(r=e.strm.avail_in),r&&(xe(e.strm,e.window,e.strstart,r),e.strstart+=r,e.insert+=r>e.w_size-e.insert?e.w_size-e.insert:r),e.high_water>3,r=e.pending_buf_size-r>65535?65535:e.pending_buf_size-r,o=r>e.w_size?e.w_size:r,s=e.strstart-e.block_start,(s>=o||(s||t===K)&&t!==G&&0===e.strm.avail_in&&s<=r)&&(i=s>r?r:s,n=t===K&&0===e.strm.avail_in&&i===s?1:0,Q(e,e.block_start,i,n),e.block_start+=i,_e(e.strm)),n?3:1)},Ce=(e,t)=>{let i,s;for(;;){if(e.lookahead=3&&(e.ins_h=me(e,e.ins_h,e.window[e.strstart+3-1]),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-Ae&&(e.match_length=Be(e,i)),e.match_length>=3)if(s=H(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=me(e,e.ins_h,e.window[e.strstart+3-1]),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=me(e,e.ins_h,e.window[e.strstart+1]);else s=H(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(s&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===K?(ve(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(ve(e,!1),0===e.strm.avail_out)?1:2},Me=(e,t)=>{let i,s,r;for(;;){if(e.lookahead=3&&(e.ins_h=me(e,e.ins_h,e.window[e.strstart+3-1]),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=2,0!==i&&e.prev_length4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,s=H(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=me(e,e.ins_h,e.window[e.strstart+3-1]),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=2,e.strstart++,s&&(ve(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(s=H(e,0,e.window[e.strstart-1]),s&&ve(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(s=H(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===K?(ve(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(ve(e,!1),0===e.strm.avail_out)?1:2};function Ee(e,t,i,s,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=s,this.func=r}const Fe=[new Ee(0,0,0,0,Pe),new Ee(4,4,8,4,Ce),new Ee(4,5,16,8,Ce),new Ee(4,6,32,32,Ce),new Ee(4,4,16,16,Me),new Ee(8,16,32,32,Me),new Ee(8,16,128,128,Me),new Ee(8,32,128,256,Me),new Ee(32,128,258,1024,Me),new Ee(32,258,258,4096,Me)];function Ie(){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=ae,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 Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),fe(this.dyn_ltree),fe(this.dyn_dtree),fe(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),fe(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),fe(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const De=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==he&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==ce&&t.status!==ue?1:0},Se=e=>{if(De(e))return de(e,Z);e.total_in=e.total_out=0,e.data_type=ne;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?he:ce,e.adler=2===t.wrap?0:1,t.last_flush=-2,N(t),J},Te=e=>{const t=Se(e);var i;return t===J&&((i=e.state).window_size=2*i.w_size,fe(i.head),i.max_lazy_match=Fe[i.level].max_lazy,i.good_match=Fe[i.level].good_length,i.nice_match=Fe[i.level].nice_length,i.max_chain_length=Fe[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),t},Re=(e,t,i,s,r,o)=>{if(!e)return Z;let n=1;if(t===ee&&(t=6),s<0?(n=0,s=-s):s>15&&(n=2,s-=16),r<1||r>9||i!==ae||s<8||s>15||t<0||t>9||o<0||o>re||8===s&&1!==n)return de(e,Z);8===s&&(s=9);const a=new Ie;return e.state=a,a.strm=e,a.status=he,a.wrap=n,a.gzhead=null,a.w_bits=s,a.w_size=1<De(e)||2!==e.state.wrap?Z:(e.state.gzhead=t,J),Oe=(e,t)=>{if(De(e)||t>X||t<0)return e?de(e,Z):Z;const i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===ue&&t!==K)return de(e,0===e.avail_out?$:Z);const s=i.last_flush;if(i.last_flush=t,0!==i.pending){if(_e(e),0===e.avail_out)return i.last_flush=-1,J}else if(0===e.avail_in&&pe(t)<=pe(s)&&t!==K)return de(e,$);if(i.status===ue&&0!==e.avail_in)return de(e,$);if(i.status===he&&0===i.wrap&&(i.status=ce),i.status===he){let t=ae+(i.w_bits-8<<4)<<8,s=-1;if(s=i.strategy>=ie||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=s<<6,0!==i.strstart&&(t|=32),t+=31-t%31,ye(i,t),0!==i.strstart&&(ye(i,e.adler>>>16),ye(i,65535&e.adler)),e.adler=1,i.status=ce,_e(e),0!==i.pending)return i.last_flush=-1,J}if(57===i.status)if(e.adler=0,be(i,31),be(i,139),be(i,8),i.gzhead)be(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),be(i,255&i.gzhead.time),be(i,i.gzhead.time>>8&255),be(i,i.gzhead.time>>16&255),be(i,i.gzhead.time>>24&255),be(i,9===i.level?2:i.strategy>=ie||i.level<2?4:0),be(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(be(i,255&i.gzhead.extra.length),be(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=U(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(be(i,0),be(i,0),be(i,0),be(i,0),be(i,0),be(i,9===i.level?2:i.strategy>=ie||i.level<2?4:0),be(i,3),i.status=ce,_e(e),0!==i.pending)return i.last_flush=-1,J;if(69===i.status){if(i.gzhead.extra){let t=i.pending,s=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+s>i.pending_buf_size;){let r=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+r),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>t&&(e.adler=U(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex+=r,_e(e),0!==i.pending)return i.last_flush=-1,J;t=0,s-=r}let r=new Uint8Array(i.gzhead.extra);i.pending_buf.set(r.subarray(i.gzindex,i.gzindex+s),i.pending),i.pending+=s,i.gzhead.hcrc&&i.pending>t&&(e.adler=U(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let t,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(e.adler=U(e.adler,i.pending_buf,i.pending-s,s)),_e(e),0!==i.pending)return i.last_flush=-1,J;s=0}t=i.gzindexs&&(e.adler=U(e.adler,i.pending_buf,i.pending-s,s)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let t,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(e.adler=U(e.adler,i.pending_buf,i.pending-s,s)),_e(e),0!==i.pending)return i.last_flush=-1,J;s=0}t=i.gzindexs&&(e.adler=U(e.adler,i.pending_buf,i.pending-s,s))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(_e(e),0!==i.pending))return i.last_flush=-1,J;be(i,255&e.adler),be(i,e.adler>>8&255),e.adler=0}if(i.status=ce,_e(e),0!==i.pending)return i.last_flush=-1,J}if(0!==e.avail_in||0!==i.lookahead||t!==G&&i.status!==ue){let s=0===i.level?Pe(i,t):i.strategy===ie?((e,t)=>{let i;for(;;){if(0===e.lookahead&&(we(e),0===e.lookahead)){if(t===G)return 1;break}if(e.match_length=0,i=H(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===K?(ve(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(ve(e,!1),0===e.strm.avail_out)?1:2})(i,t):i.strategy===se?((e,t)=>{let i,s,r,o;const n=e.window;for(;;){if(e.lookahead<=le){if(we(e),e.lookahead<=le&&t===G)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=e.strstart-1,s=n[r],s===n[++r]&&s===n[++r]&&s===n[++r])){o=e.strstart+le;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]&&re.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=H(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=H(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===K?(ve(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(ve(e,!1),0===e.strm.avail_out)?1:2})(i,t):Fe[i.level].func(i,t);if(3!==s&&4!==s||(i.status=ue),1===s||3===s)return 0===e.avail_out&&(i.last_flush=-1),J;if(2===s&&(t===z?j(i):t!==X&&(Q(i,0,0,!1),t===W&&(fe(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),_e(e),0===e.avail_out))return i.last_flush=-1,J}return t!==K?J:i.wrap<=0?Y:(2===i.wrap?(be(i,255&e.adler),be(i,e.adler>>8&255),be(i,e.adler>>16&255),be(i,e.adler>>24&255),be(i,255&e.total_in),be(i,e.total_in>>8&255),be(i,e.total_in>>16&255),be(i,e.total_in>>24&255)):(ye(i,e.adler>>>16),ye(i,65535&e.adler)),_e(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?J:Y)},ke=e=>{if(De(e))return Z;const t=e.state.status;return e.state=null,t===ce?de(e,q):J},Ne=(e,t)=>{let i=t.length;if(De(e))return Z;const s=e.state,r=s.wrap;if(2===r||1===r&&s.status!==he||s.lookahead)return Z;if(1===r&&(e.adler=R(e.adler,t,i,0)),s.wrap=0,i>=s.w_size){0===r&&(fe(s.head),s.strstart=0,s.block_start=0,s.insert=0);let e=new Uint8Array(s.w_size);e.set(t.subarray(i-s.w_size,i),0),t=e,i=s.w_size}const o=e.avail_in,n=e.next_in,a=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,we(s);s.lookahead>=3;){let e=s.strstart,t=s.lookahead-2;do{s.ins_h=me(s,s.ins_h,s.window[e+3-1]),s.prev[e&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=e,e++}while(--t);s.strstart=e,s.lookahead=2,we(s)}return s.strstart+=s.lookahead,s.block_start=s.strstart,s.insert=s.lookahead,s.lookahead=0,s.match_length=s.prev_length=2,s.match_available=0,e.next_in=n,e.input=a,e.avail_in=o,s.wrap=r,J};const Qe=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var Ve=function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const t in i)Qe(i,t)&&(e[t]=i[t])}}return e},He=e=>{let t=0;for(let i=0,s=e.length;i=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;Ge[254]=Ge[254]=1;var ze=e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,i,s,r,o,n=e.length,a=0;for(r=0;r>>6,t[o++]=128|63&i):i<65536?(t[o++]=224|i>>>12,t[o++]=128|i>>>6&63,t[o++]=128|63&i):(t[o++]=240|i>>>18,t[o++]=128|i>>>12&63,t[o++]=128|i>>>6&63,t[o++]=128|63&i);return t},We=(e,t)=>{const i=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let s,r;const o=new Array(2*i);for(r=0,s=0;s4)o[r++]=65533,s+=n-1;else{for(t&=2===n?31:3===n?15:7;n>1&&s1?o[r++]=65533:t<65536?o[r++]=t:(t-=65536,o[r++]=55296|t>>10&1023,o[r++]=56320|1023&t)}}return((e,t)=>{if(t<65534&&e.subarray&&je)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let i="";for(let s=0;s{(t=t||e.length)>e.length&&(t=e.length);let i=t-1;for(;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+Ge[e[i]]>t?i:t},Xe=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};const Je=Object.prototype.toString,{Z_NO_FLUSH:Ye,Z_SYNC_FLUSH:Ze,Z_FULL_FLUSH:qe,Z_FINISH:$e,Z_OK:et,Z_STREAM_END:tt,Z_DEFAULT_COMPRESSION:it,Z_DEFAULT_STRATEGY:st,Z_DEFLATED:rt}=k;function ot(e){this.options=Ve({level:it,method:rt,chunkSize:16384,windowBits:15,memLevel:8,strategy:st},e||{});let 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 Xe,this.strm.avail_out=0;let i=Le(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==et)throw new Error(O[i]);if(t.header&&Ue(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?ze(t.dictionary):"[object ArrayBuffer]"===Je.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,i=Ne(this.strm,e),i!==et)throw new Error(O[i]);this._dict_set=!0}}function nt(e,t){const i=new ot(t);if(i.push(e,!0),i.err)throw i.msg||O[i.err];return i.result}ot.prototype.push=function(e,t){const i=this.strm,s=this.options.chunkSize;let r,o;if(this.ended)return!1;for(o=t===~~t?t:!0===t?$e:Ye,"string"==typeof e?i.input=ze(e):"[object ArrayBuffer]"===Je.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(s),i.next_out=0,i.avail_out=s),(o===Ze||o===qe)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(r=Oe(i,o),r===tt)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),r=ke(this.strm),this.onEnd(r),this.ended=!0,r===et;if(0!==i.avail_out){if(o>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},ot.prototype.onData=function(e){this.chunks.push(e)},ot.prototype.onEnd=function(e){e===et&&(this.result=He(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var at={Deflate:ot,deflate:nt,deflateRaw:function(e,t){return(t=t||{}).raw=!0,nt(e,t)},gzip:function(e,t){return(t=t||{}).gzip=!0,nt(e,t)},constants:k};const lt=16209;var At=function(e,t){let i,s,r,o,n,a,l,A,h,c,u,d,p,f,g,m,_,v,b,y,x,B,w,P;const C=e.state;i=e.next_in,w=e.input,s=i+(e.avail_in-5),r=e.next_out,P=e.output,o=r-(t-e.avail_out),n=r+(e.avail_out-257),a=C.dmax,l=C.wsize,A=C.whave,h=C.wnext,c=C.window,u=C.hold,d=C.bits,p=C.lencode,f=C.distcode,g=(1<>>24,u>>>=v,d-=v,v=_>>>16&255,0===v)P[r++]=65535&_;else{if(!(16&v)){if(0==(64&v)){_=p[(65535&_)+(u&(1<>>=v,d-=v),d<15&&(u+=w[i++]<>>24,u>>>=v,d-=v,v=_>>>16&255,!(16&v)){if(0==(64&v)){_=f[(65535&_)+(u&(1<a){e.msg="invalid distance too far back",C.mode=lt;break e}if(u>>>=v,d-=v,v=r-o,y>v){if(v=y-v,v>A&&C.sane){e.msg="invalid distance too far back",C.mode=lt;break e}if(x=0,B=c,0===h){if(x+=l-v,v2;)P[r++]=B[x++],P[r++]=B[x++],P[r++]=B[x++],b-=3;b&&(P[r++]=B[x++],b>1&&(P[r++]=B[x++]))}else{x=r-y;do{P[r++]=P[x++],P[r++]=P[x++],P[r++]=P[x++],b-=3}while(b>2);b&&(P[r++]=P[x++],b>1&&(P[r++]=P[x++]))}break}}break}}while(i>3,i-=b,d-=b<<3,u&=(1<{const l=a.bits;let A,h,c,u,d,p,f=0,g=0,m=0,_=0,v=0,b=0,y=0,x=0,B=0,w=0,P=null;const C=new Uint16Array(16),M=new Uint16Array(16);let E,F,I,D=null;for(f=0;f<=15;f++)C[f]=0;for(g=0;g=1&&0===C[_];_--);if(v>_&&(v=_),0===_)return r[o++]=20971520,r[o++]=20971520,a.bits=1,0;for(m=1;m<_&&0===C[m];m++);for(v0&&(0===e||1!==_))return-1;for(M[1]=0,f=1;f<15;f++)M[f+1]=M[f]+C[f];for(g=0;g852||2===e&&B>592)return 1;for(;;){E=f-y,n[g]+1=p?(F=D[n[g]-p],I=P[n[g]-p]):(F=96,I=0),A=1<>y)+h]=E<<24|F<<16|I|0}while(0!==h);for(A=1<>=1;if(0!==A?(w&=A-1,w+=A):w=0,g++,0==--C[f]){if(f===_)break;f=t[i+n[g]]}if(f>v&&(w&u)!==c){for(0===y&&(y=v),d+=m,b=f-y,x=1<852||2===e&&B>592)return 1;c=w&u,r[c]=v<<24|b<<16|d-o|0}}return 0!==w&&(r[d+w]=f-y<<24|64<<16|0),a.bits=v,0};const{Z_FINISH:ft,Z_BLOCK:gt,Z_TREES:mt,Z_OK:_t,Z_STREAM_END:vt,Z_NEED_DICT:bt,Z_STREAM_ERROR:yt,Z_DATA_ERROR:xt,Z_MEM_ERROR:Bt,Z_BUF_ERROR:wt,Z_DEFLATED:Pt}=k,Ct=16180,Mt=16190,Et=16191,Ft=16192,It=16194,Dt=16199,St=16200,Tt=16206,Rt=16209,Lt=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function Ut(){this.strm=null,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 Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const Ot=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode16211?1:0},kt=e=>{if(Ot(e))return yt;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=Ct,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,_t},Nt=e=>{if(Ot(e))return yt;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,kt(e)},Qt=(e,t)=>{let i;if(Ot(e))return yt;const s=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?yt:(null!==s.window&&s.wbits!==t&&(s.window=null),s.wrap=i,s.wbits=t,Nt(e))},Vt=(e,t)=>{if(!e)return yt;const i=new Ut;e.state=i,i.strm=e,i.window=null,i.mode=Ct;const s=Qt(e,t);return s!==_t&&(e.state=null),s};let Ht,jt,Gt=!0;const zt=e=>{if(Gt){Ht=new Int32Array(512),jt=new Int32Array(32);let t=0;for(;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(pt(1,e.lens,0,288,Ht,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;pt(2,e.lens,0,32,jt,0,e.work,{bits:5}),Gt=!1}e.lencode=Ht,e.lenbits=9,e.distcode=jt,e.distbits=5},Wt=(e,t,i,s)=>{let r;const o=e.state;return null===o.window&&(o.wsize=1<=o.wsize?(o.window.set(t.subarray(i-o.wsize,i),0),o.wnext=0,o.whave=o.wsize):(r=o.wsize-o.wnext,r>s&&(r=s),o.window.set(t.subarray(i-s,i-s+r),o.wnext),(s-=r)?(o.window.set(t.subarray(i-s,i),0),o.wnext=s,o.whave=o.wsize):(o.wnext+=r,o.wnext===o.wsize&&(o.wnext=0),o.whave{let i,s,r,o,n,a,l,A,h,c,u,d,p,f,g,m,_,v,b,y,x,B,w=0;const P=new Uint8Array(4);let C,M;const E=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(Ot(e)||!e.output||!e.input&&0!==e.avail_in)return yt;i=e.state,i.mode===Et&&(i.mode=Ft),n=e.next_out,r=e.output,l=e.avail_out,o=e.next_in,s=e.input,a=e.avail_in,A=i.hold,h=i.bits,c=a,u=l,B=_t;e:for(;;)switch(i.mode){case Ct:if(0===i.wrap){i.mode=Ft;break}for(;h<16;){if(0===a)break e;a--,A+=s[o++]<>>8&255,i.check=U(i.check,P,2,0),A=0,h=0,i.mode=16181;break}if(i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&A)<<8)+(A>>8))%31){e.msg="incorrect header check",i.mode=Rt;break}if((15&A)!==Pt){e.msg="unknown compression method",i.mode=Rt;break}if(A>>>=4,h-=4,x=8+(15&A),0===i.wbits&&(i.wbits=x),x>15||x>i.wbits){e.msg="invalid window size",i.mode=Rt;break}i.dmax=1<>8&1),512&i.flags&&4&i.wrap&&(P[0]=255&A,P[1]=A>>>8&255,i.check=U(i.check,P,2,0)),A=0,h=0,i.mode=16182;case 16182:for(;h<32;){if(0===a)break e;a--,A+=s[o++]<>>8&255,P[2]=A>>>16&255,P[3]=A>>>24&255,i.check=U(i.check,P,4,0)),A=0,h=0,i.mode=16183;case 16183:for(;h<16;){if(0===a)break e;a--,A+=s[o++]<>8),512&i.flags&&4&i.wrap&&(P[0]=255&A,P[1]=A>>>8&255,i.check=U(i.check,P,2,0)),A=0,h=0,i.mode=16184;case 16184:if(1024&i.flags){for(;h<16;){if(0===a)break e;a--,A+=s[o++]<>>8&255,i.check=U(i.check,P,2,0)),A=0,h=0}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&i.flags&&(d=i.length,d>a&&(d=a),d&&(i.head&&(x=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(s.subarray(o,o+d),x)),512&i.flags&&4&i.wrap&&(i.check=U(i.check,s,d,o)),a-=d,o+=d,i.length-=d),i.length))break e;i.length=0,i.mode=16186;case 16186:if(2048&i.flags){if(0===a)break e;d=0;do{x=s[o+d++],i.head&&x&&i.length<65536&&(i.head.name+=String.fromCharCode(x))}while(x&&d>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=Et;break;case 16189:for(;h<32;){if(0===a)break e;a--,A+=s[o++]<>>=7&h,h-=7&h,i.mode=Tt;break}for(;h<3;){if(0===a)break e;a--,A+=s[o++]<>>=1,h-=1,3&A){case 0:i.mode=16193;break;case 1:if(zt(i),i.mode=Dt,t===mt){A>>>=2,h-=2;break e}break;case 2:i.mode=16196;break;case 3:e.msg="invalid block type",i.mode=Rt}A>>>=2,h-=2;break;case 16193:for(A>>>=7&h,h-=7&h;h<32;){if(0===a)break e;a--,A+=s[o++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=Rt;break}if(i.length=65535&A,A=0,h=0,i.mode=It,t===mt)break e;case It:i.mode=16195;case 16195:if(d=i.length,d){if(d>a&&(d=a),d>l&&(d=l),0===d)break e;r.set(s.subarray(o,o+d),n),a-=d,o+=d,l-=d,n+=d,i.length-=d;break}i.mode=Et;break;case 16196:for(;h<14;){if(0===a)break e;a--,A+=s[o++]<>>=5,h-=5,i.ndist=1+(31&A),A>>>=5,h-=5,i.ncode=4+(15&A),A>>>=4,h-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=Rt;break}i.have=0,i.mode=16197;case 16197:for(;i.have>>=3,h-=3}for(;i.have<19;)i.lens[E[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,C={bits:i.lenbits},B=pt(0,i.lens,0,19,i.lencode,0,i.work,C),i.lenbits=C.bits,B){e.msg="invalid code lengths set",i.mode=Rt;break}i.have=0,i.mode=16198;case 16198:for(;i.have>>24,m=w>>>16&255,_=65535&w,!(g<=h);){if(0===a)break e;a--,A+=s[o++]<>>=g,h-=g,i.lens[i.have++]=_;else{if(16===_){for(M=g+2;h>>=g,h-=g,0===i.have){e.msg="invalid bit length repeat",i.mode=Rt;break}x=i.lens[i.have-1],d=3+(3&A),A>>>=2,h-=2}else if(17===_){for(M=g+3;h>>=g,h-=g,x=0,d=3+(7&A),A>>>=3,h-=3}else{for(M=g+7;h>>=g,h-=g,x=0,d=11+(127&A),A>>>=7,h-=7}if(i.have+d>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=Rt;break}for(;d--;)i.lens[i.have++]=x}}if(i.mode===Rt)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=Rt;break}if(i.lenbits=9,C={bits:i.lenbits},B=pt(1,i.lens,0,i.nlen,i.lencode,0,i.work,C),i.lenbits=C.bits,B){e.msg="invalid literal/lengths set",i.mode=Rt;break}if(i.distbits=6,i.distcode=i.distdyn,C={bits:i.distbits},B=pt(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,C),i.distbits=C.bits,B){e.msg="invalid distances set",i.mode=Rt;break}if(i.mode=Dt,t===mt)break e;case Dt:i.mode=St;case St:if(a>=6&&l>=258){e.next_out=n,e.avail_out=l,e.next_in=o,e.avail_in=a,i.hold=A,i.bits=h,At(e,u),n=e.next_out,r=e.output,l=e.avail_out,o=e.next_in,s=e.input,a=e.avail_in,A=i.hold,h=i.bits,i.mode===Et&&(i.back=-1);break}for(i.back=0;w=i.lencode[A&(1<>>24,m=w>>>16&255,_=65535&w,!(g<=h);){if(0===a)break e;a--,A+=s[o++]<>v)],g=w>>>24,m=w>>>16&255,_=65535&w,!(v+g<=h);){if(0===a)break e;a--,A+=s[o++]<>>=v,h-=v,i.back+=v}if(A>>>=g,h-=g,i.back+=g,i.length=_,0===m){i.mode=16205;break}if(32&m){i.back=-1,i.mode=Et;break}if(64&m){e.msg="invalid literal/length code",i.mode=Rt;break}i.extra=15&m,i.mode=16201;case 16201:if(i.extra){for(M=i.extra;h>>=i.extra,h-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=16202;case 16202:for(;w=i.distcode[A&(1<>>24,m=w>>>16&255,_=65535&w,!(g<=h);){if(0===a)break e;a--,A+=s[o++]<>v)],g=w>>>24,m=w>>>16&255,_=65535&w,!(v+g<=h);){if(0===a)break e;a--,A+=s[o++]<>>=v,h-=v,i.back+=v}if(A>>>=g,h-=g,i.back+=g,64&m){e.msg="invalid distance code",i.mode=Rt;break}i.offset=_,i.extra=15&m,i.mode=16203;case 16203:if(i.extra){for(M=i.extra;h>>=i.extra,h-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=Rt;break}i.mode=16204;case 16204:if(0===l)break e;if(d=u-l,i.offset>d){if(d=i.offset-d,d>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=Rt;break}d>i.wnext?(d-=i.wnext,p=i.wsize-d):p=i.wnext-d,d>i.length&&(d=i.length),f=i.window}else f=r,p=n-i.offset,d=i.length;d>l&&(d=l),l-=d,i.length-=d;do{r[n++]=f[p++]}while(--d);0===i.length&&(i.mode=St);break;case 16205:if(0===l)break e;r[n++]=i.length,l--,i.mode=St;break;case Tt:if(i.wrap){for(;h<32;){if(0===a)break e;a--,A|=s[o++]<{if(Ot(e))return yt;let t=e.state;return t.window&&(t.window=null),e.state=null,_t},Zt=(e,t)=>{if(Ot(e))return yt;const i=e.state;return 0==(2&i.wrap)?yt:(i.head=t,t.done=!1,_t)},qt=(e,t)=>{const i=t.length;let s,r,o;return Ot(e)?yt:(s=e.state,0!==s.wrap&&s.mode!==Mt?yt:s.mode===Mt&&(r=1,r=R(r,t,i,0),r!==s.check)?xt:(o=Wt(e,t,i,i),o?(s.mode=16210,Bt):(s.havedict=1,_t)))},$t=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};const ei=Object.prototype.toString,{Z_NO_FLUSH:ti,Z_FINISH:ii,Z_OK:si,Z_STREAM_END:ri,Z_NEED_DICT:oi,Z_STREAM_ERROR:ni,Z_DATA_ERROR:ai,Z_MEM_ERROR:li}=k;function Ai(e){this.options=Ve({chunkSize:65536,windowBits:15,to:""},e||{});const 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 Xe,this.strm.avail_out=0;let i=Xt(this.strm,t.windowBits);if(i!==si)throw new Error(O[i]);if(this.header=new $t,Zt(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=ze(t.dictionary):"[object ArrayBuffer]"===ei.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=qt(this.strm,t.dictionary),i!==si)))throw new Error(O[i])}function hi(e,t){const i=new Ai(t);if(i.push(e),i.err)throw i.msg||O[i.err];return i.result}Ai.prototype.push=function(e,t){const i=this.strm,s=this.options.chunkSize,r=this.options.dictionary;let o,n,a;if(this.ended)return!1;for(n=t===~~t?t:!0===t?ii:ti,"[object ArrayBuffer]"===ei.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(s),i.next_out=0,i.avail_out=s),o=Jt(i,n),o===oi&&r&&(o=qt(i,r),o===si?o=Jt(i,n):o===ai&&(o=oi));i.avail_in>0&&o===ri&&i.state.wrap>0&&0!==e[i.next_in];)Kt(i),o=Jt(i,n);switch(o){case ni:case ai:case oi:case li:return this.onEnd(o),this.ended=!0,!1}if(a=i.avail_out,i.next_out&&(0===i.avail_out||o===ri))if("string"===this.options.to){let e=Ke(i.output,i.next_out),t=i.next_out-e,r=We(i.output,e);i.next_out=t,i.avail_out=s-t,t&&i.output.set(i.output.subarray(e,e+t),0),this.onData(r)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(o!==si||0!==a){if(o===ri)return o=Yt(this.strm),this.onEnd(o),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},Ai.prototype.onData=function(e){this.chunks.push(e)},Ai.prototype.onEnd=function(e){e===si&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=He(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var ci={Inflate:Ai,inflate:hi,inflateRaw:function(e,t){return(t=t||{}).raw=!0,hi(e,t)},ungzip:hi,constants:k};const{Deflate:ui,deflate:di,deflateRaw:pi,gzip:fi}=at,{Inflate:gi,inflate:mi,inflateRaw:_i,ungzip:vi}=ci;var bi=ui,yi=di,xi=pi,Bi=fi,wi=gi,Pi=mi,Ci=_i,Mi=vi,Ei=k,Fi={Deflate:bi,deflate:yi,deflateRaw:xi,gzip:Bi,Inflate:wi,inflate:Pi,inflateRaw:Ci,ungzip:Mi,constants:Ei};e.Deflate=bi,e.Inflate=wi,e.constants=Ei,e.default=Fi,e.deflate=yi,e.deflateRaw=xi,e.gzip=Bi,e.inflate=Pi,e.inflateRaw=Ci,e.ungzip=Mi,Object.defineProperty(e,"__esModule",{value:!0})}));var Ow=Object.freeze({__proto__:null});let kw=window.pako||Ow;kw.inflate||(kw=kw.default);const Nw=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}}();const Qw={version:1,parse:function(e,t,i,s,r,o){const n=function(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]}}(i),a=function(e){return{positions:new Uint16Array(kw.inflate(e.positions).buffer),normals:new Int8Array(kw.inflate(e.normals).buffer),indices:new Uint32Array(kw.inflate(e.indices).buffer),edgeIndices:new Uint32Array(kw.inflate(e.edgeIndices).buffer),meshPositions:new Uint32Array(kw.inflate(e.meshPositions).buffer),meshIndices:new Uint32Array(kw.inflate(e.meshIndices).buffer),meshEdgesIndices:new Uint32Array(kw.inflate(e.meshEdgesIndices).buffer),meshColors:new Uint8Array(kw.inflate(e.meshColors).buffer),entityIDs:kw.inflate(e.entityIDs,{to:"string"}),entityMeshes:new Uint32Array(kw.inflate(e.entityMeshes).buffer),entityIsObjects:new Uint8Array(kw.inflate(e.entityIsObjects).buffer),positionsDecodeMatrix:new Float32Array(kw.inflate(e.positionsDecodeMatrix).buffer)}}(n);!function(e,t,i,s,r,o){o.getNextId(),s.positionsCompression="precompressed",s.normalsCompression="precompressed";const n=i.positions,a=i.normals,l=i.indices,A=i.edgeIndices,h=i.meshPositions,u=i.meshIndices,d=i.meshEdgesIndices,p=i.meshColors,f=JSON.parse(i.entityIDs),g=i.entityMeshes,m=i.entityIsObjects,v=h.length,b=g.length;for(let r=0;rg[e]g[t]?1:0));for(let e=0;e1||(E[i]=e)}}for(let e=0;e1,o=Xw(m.subarray(4*t,4*t+3)),u=m[4*t+3]/255,v=a.subarray(d[t],i?a.length:d[t+1]),y=l.subarray(d[t],i?l.length:d[t+1]),x=A.subarray(p[t],i?A.length:p[t+1]),w=h.subarray(f[t],i?h.length:f[t+1]),M=c.subarray(g[t],g[t]+16);if(r){const e=`${n}-geometry.${t}`;s.createGeometry({id:e,primitive:"triangles",positionsCompressed:v,normalsCompressed:y,indices:x,edgeIndices:w,positionsDecodeMatrix:M})}else{const e=`${n}-${t}`;b[E[t]];const i={};s.createMesh(_.apply(i,{id:e,primitive:"triangles",positionsCompressed:v,normalsCompressed:y,indices:x,edgeIndices:w,positionsDecodeMatrix:M,color:o,opacity:u}))}}let F=0;for(let e=0;e1){const t={},r=`${n}-instance.${F++}`,o=`${n}-geometry.${i}`,a=16*x[e],A=u.subarray(a,a+16);s.createMesh(_.apply(t,{id:r,geometryId:o,matrix:A})),l.push(r)}else l.push(i)}if(l.length>0){const e={};s.createEntity(_.apply(e,{id:r,isObject:!0,meshIds:l}))}}}(0,0,a,s,0,o)}};let Yw=window.pako||Ow;Yw.inflate||(Yw=Yw.default);const Zw=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}}();const qw={version:5,parse:function(e,t,i,s,r,o){const n=function(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]}}(i),a=function(e){return{positions:new Float32Array(Yw.inflate(e.positions).buffer),normals:new Int8Array(Yw.inflate(e.normals).buffer),indices:new Uint32Array(Yw.inflate(e.indices).buffer),edgeIndices:new Uint32Array(Yw.inflate(e.edgeIndices).buffer),matrices:new Float32Array(Yw.inflate(e.matrices).buffer),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(Yw.inflate(e.eachPrimitivePositionsAndNormalsPortion).buffer),eachPrimitiveIndicesPortion:new Uint32Array(Yw.inflate(e.eachPrimitiveIndicesPortion).buffer),eachPrimitiveEdgeIndicesPortion:new Uint32Array(Yw.inflate(e.eachPrimitiveEdgeIndicesPortion).buffer),eachPrimitiveColor:new Uint8Array(Yw.inflate(e.eachPrimitiveColor).buffer),primitiveInstances:new Uint32Array(Yw.inflate(e.primitiveInstances).buffer),eachEntityId:Yw.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(Yw.inflate(e.eachEntityPrimitiveInstancesPortion).buffer),eachEntityMatricesPortion:new Uint32Array(Yw.inflate(e.eachEntityMatricesPortion).buffer)}}(n);!function(e,t,i,s,r,o){const n=o.getNextId();s.positionsCompression="disabled",s.normalsCompression="precompressed";const a=i.positions,l=i.normals,A=i.indices,h=i.edgeIndices,c=i.matrices,u=i.eachPrimitivePositionsAndNormalsPortion,d=i.eachPrimitiveIndicesPortion,p=i.eachPrimitiveEdgeIndicesPortion,f=i.eachPrimitiveColor,g=i.primitiveInstances,m=JSON.parse(i.eachEntityId),v=i.eachEntityPrimitiveInstancesPortion,b=i.eachEntityMatricesPortion,y=u.length,x=g.length,B=new Uint8Array(y),w=m.length;for(let e=0;e1||(P[i]=e)}}for(let e=0;e1,r=Zw(f.subarray(4*e,4*e+3)),o=f[4*e+3]/255,c=a.subarray(u[e],t?a.length:u[e+1]),g=l.subarray(u[e],t?l.length:u[e+1]),v=A.subarray(d[e],t?A.length:d[e+1]),b=h.subarray(p[e],t?h.length:p[e+1]);if(i){const t=`${n}-geometry.${e}`;s.createGeometry({id:t,primitive:"triangles",positionsCompressed:c,normalsCompressed:g,indices:v,edgeIndices:b})}else{const t=e;m[P[e]];const i={};s.createMesh(_.apply(i,{id:t,primitive:"triangles",positionsCompressed:c,normalsCompressed:g,indices:v,edgeIndices:b,color:r,opacity:o}))}}let C=0;for(let e=0;e1){const t={},r="instance."+C++,o="geometry"+i,n=16*b[e],l=c.subarray(n,n+16);s.createMesh(_.apply(t,{id:r,geometryId:o,matrix:l})),a.push(r)}else a.push(i)}if(a.length>0){const e={};s.createEntity(_.apply(e,{id:r,isObject:!0,meshIds:a}))}}}(0,0,a,s,0,o)}};let $w=window.pako||Ow;$w.inflate||($w=$w.default);const eP=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}}();const tP={version:6,parse:function(e,t,i,s,r,o){const n=function(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],matrices:e[4],reusedPrimitivesDecodeMatrix:e[5],eachPrimitivePositionsAndNormalsPortion:e[6],eachPrimitiveIndicesPortion:e[7],eachPrimitiveEdgeIndicesPortion:e[8],eachPrimitiveColorAndOpacity:e[9],primitiveInstances:e[10],eachEntityId:e[11],eachEntityPrimitiveInstancesPortion:e[12],eachEntityMatricesPortion:e[13],eachTileAABB:e[14],eachTileEntitiesPortion:e[15]}}(i),a=function(e){function t(e,t){return 0===e.length?[]:$w.inflate(e,t).buffer}return{positions:new Uint16Array(t(e.positions)),normals:new Int8Array(t(e.normals)),indices:new Uint32Array(t(e.indices)),edgeIndices:new Uint32Array(t(e.edgeIndices)),matrices:new Float32Array(t(e.matrices)),reusedPrimitivesDecodeMatrix:new Float32Array(t(e.reusedPrimitivesDecodeMatrix)),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(t(e.eachPrimitivePositionsAndNormalsPortion)),eachPrimitiveIndicesPortion:new Uint32Array(t(e.eachPrimitiveIndicesPortion)),eachPrimitiveEdgeIndicesPortion:new Uint32Array(t(e.eachPrimitiveEdgeIndicesPortion)),eachPrimitiveColorAndOpacity:new Uint8Array(t(e.eachPrimitiveColorAndOpacity)),primitiveInstances:new Uint32Array(t(e.primitiveInstances)),eachEntityId:$w.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(t(e.eachEntityPrimitiveInstancesPortion)),eachEntityMatricesPortion:new Uint32Array(t(e.eachEntityMatricesPortion)),eachTileAABB:new Float64Array(t(e.eachTileAABB)),eachTileEntitiesPortion:new Uint32Array(t(e.eachTileEntitiesPortion))}}(n);!function(e,t,i,s,r,o){const n=o.getNextId(),a=i.positions,l=i.normals,A=i.indices,h=i.edgeIndices,u=i.matrices,d=i.reusedPrimitivesDecodeMatrix,p=i.eachPrimitivePositionsAndNormalsPortion,f=i.eachPrimitiveIndicesPortion,g=i.eachPrimitiveEdgeIndicesPortion,m=i.eachPrimitiveColorAndOpacity,v=i.primitiveInstances,b=JSON.parse(i.eachEntityId),y=i.eachEntityPrimitiveInstancesPortion,x=i.eachEntityMatricesPortion,B=i.eachTileAABB,w=i.eachTileEntitiesPortion,P=p.length,C=v.length,M=b.length,E=w.length,F=new Uint32Array(P);for(let e=0;e1,c=t===P-1,u=a.subarray(p[t],c?a.length:p[t+1]),b=l.subarray(p[t],c?l.length:p[t+1]),y=A.subarray(f[t],c?A.length:f[t+1]),x=h.subarray(g[t],c?h.length:g[t+1]),B=eP(m.subarray(4*t,4*t+3)),w=m[4*t+3]/255,C=o.getNextId();if(r){const e=`${n}-geometry.${i}.${t}`;U[e]||(s.createGeometry({id:e,primitive:"triangles",positionsCompressed:u,indices:y,edgeIndices:x,positionsDecodeMatrix:d}),U[e]=!0),s.createMesh(_.apply(N,{id:C,geometryId:e,origin:I,matrix:E,color:B,opacity:w})),R.push(C)}else s.createMesh(_.apply(N,{id:C,origin:I,primitive:"triangles",positionsCompressed:u,normalsCompressed:b,indices:y,edgeIndices:x,positionsDecodeMatrix:L,color:B,opacity:w})),R.push(C)}R.length>0&&s.createEntity(_.apply(k,{id:w,isObject:!0,meshIds:R}))}}}(e,t,a,s,0,o)}};let iP=window.pako||Ow;iP.inflate||(iP=iP.default);const sP=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 rP(e){const t=[];for(let i=0,s=e.length;i1,c=t===F-1,P=sP(w.subarray(6*e,6*e+3)),C=w[6*e+3]/255,M=w[6*e+4]/255,E=w[6*e+5]/255,I=o.getNextId();if(r){const r=B[e],o=d.slice(r,r+16),x=`${n}-geometry.${i}.${t}`;if(!Q[x]){let e,i,r,o,n,d;switch(f[t]){case 0:e="solid",i=a.subarray(g[t],c?a.length:g[t+1]),r=l.subarray(m[t],c?l.length:m[t+1]),n=h.subarray(b[t],c?h.length:b[t+1]),d=u.subarray(y[t],c?u.length:y[t+1]);break;case 1:e="surface",i=a.subarray(g[t],c?a.length:g[t+1]),r=l.subarray(m[t],c?l.length:m[t+1]),n=h.subarray(b[t],c?h.length:b[t+1]),d=u.subarray(y[t],c?u.length:y[t+1]);break;case 2:e="points",i=a.subarray(g[t],c?a.length:g[t+1]),o=rP(A.subarray(v[t],c?A.length:v[t+1]));break;case 3:e="lines",i=a.subarray(g[t],c?a.length:g[t+1]),n=h.subarray(b[t],c?h.length:b[t+1]);break;default:continue}s.createGeometry({id:x,primitive:e,positionsCompressed:i,normalsCompressed:r,colors:o,indices:n,edgeIndices:d,positionsDecodeMatrix:p}),Q[x]=!0}s.createMesh(_.apply(V,{id:I,geometryId:x,origin:R,matrix:o,color:P,metallic:M,roughness:E,opacity:C})),U.push(I)}else{let e,i,r,o,n,d;switch(f[t]){case 0:e="solid",i=a.subarray(g[t],c?a.length:g[t+1]),r=l.subarray(m[t],c?l.length:m[t+1]),n=h.subarray(b[t],c?h.length:b[t+1]),d=u.subarray(y[t],c?u.length:y[t+1]);break;case 1:e="surface",i=a.subarray(g[t],c?a.length:g[t+1]),r=l.subarray(m[t],c?l.length:m[t+1]),n=h.subarray(b[t],c?h.length:b[t+1]),d=u.subarray(y[t],c?u.length:y[t+1]);break;case 2:e="points",i=a.subarray(g[t],c?a.length:g[t+1]),o=rP(A.subarray(v[t],c?A.length:v[t+1]));break;case 3:e="lines",i=a.subarray(g[t],c?a.length:g[t+1]),n=h.subarray(b[t],c?h.length:b[t+1]);break;default:continue}s.createMesh(_.apply(V,{id:I,origin:R,primitive:e,positionsCompressed:i,normalsCompressed:r,colors:o,indices:n,edgeIndices:d,positionsDecodeMatrix:N,color:P,metallic:M,roughness:E,opacity:C})),U.push(I)}}U.length>0&&s.createEntity(_.apply(k,{id:E,isObject:!0,meshIds:U}))}}}(e,t,a,s,0,o)}};let nP=window.pako||Ow;nP.inflate||(nP=nP.default);const aP=c.vec4(),lP=c.vec4();const AP=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 hP(e){const t=[];for(let i=0,s=e.length;i1,l=r===L-1,A=AP(F.subarray(6*e,6*e+3)),h=F[6*e+3]/255,u=F[6*e+4]/255,I=F[6*e+5]/255,D=o.getNextId();if(a){const o=E[e],a=v.slice(o,o+16),M=`${n}-geometry.${i}.${r}`;let F=H[M];if(!F){F={batchThisMesh:!t.reuseGeometries};let e=!1;switch(y[r]){case 0:F.primitiveName="solid",F.geometryPositions=d.subarray(x[r],l?d.length:x[r+1]),F.geometryNormals=p.subarray(B[r],l?p.length:B[r+1]),F.geometryIndices=g.subarray(P[r],l?g.length:P[r+1]),F.geometryEdgeIndices=m.subarray(C[r],l?m.length:C[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 1:F.primitiveName="surface",F.geometryPositions=d.subarray(x[r],l?d.length:x[r+1]),F.geometryNormals=p.subarray(B[r],l?p.length:B[r+1]),F.geometryIndices=g.subarray(P[r],l?g.length:P[r+1]),F.geometryEdgeIndices=m.subarray(C[r],l?m.length:C[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 2:F.primitiveName="points",F.geometryPositions=d.subarray(x[r],l?d.length:x[r+1]),F.geometryColors=hP(f.subarray(w[r],l?f.length:w[r+1])),e=F.geometryPositions.length>0;break;case 3:F.primitiveName="lines",F.geometryPositions=d.subarray(x[r],l?d.length:x[r+1]),F.geometryIndices=g.subarray(P[r],l?g.length:P[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;default:continue}if(e||(F=null),F&&(F.geometryPositions.length,F.batchThisMesh)){F.decompressedPositions=new Float32Array(F.geometryPositions.length);const e=F.geometryPositions,t=F.decompressedPositions;for(let i=0,s=e.length;i0&&n.length>0;break;case 1:e="surface",t=d.subarray(x[r],l?d.length:x[r+1]),i=p.subarray(B[r],l?p.length:B[r+1]),n=g.subarray(P[r],l?g.length:P[r+1]),a=m.subarray(C[r],l?m.length:C[r+1]),c=t.length>0&&n.length>0;break;case 2:e="points",t=d.subarray(x[r],l?d.length:x[r+1]),o=hP(f.subarray(w[r],l?f.length:w[r+1])),c=t.length>0;break;case 3:e="lines",t=d.subarray(x[r],l?d.length:x[r+1]),n=g.subarray(P[r],l?g.length:P[r+1]),c=t.length>0&&n.length>0;break;default:continue}c&&(s.createMesh(_.apply(G,{id:D,origin:Q,primitive:e,positionsCompressed:t,normalsCompressed:i,colorsCompressed:o,indices:n,edgeIndices:a,positionsDecodeMatrix:R,color:A,metallic:u,roughness:I,opacity:h})),T.push(D))}}T.length>0&&s.createEntity(_.apply(j,{id:A,isObject:!0,meshIds:T}))}}}(e,t,a,s,r,o)}};let uP=window.pako||Ow;uP.inflate||(uP=uP.default);const dP=c.vec4(),pP=c.vec4();const fP=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}}();const gP={version:9,parse:function(e,t,i,s,r,o){const n=function(e){return{metadata:e[0],positions:e[1],normals:e[2],colors:e[3],indices:e[4],edgeIndices:e[5],matrices:e[6],reusedGeometriesDecodeMatrix:e[7],eachGeometryPrimitiveType:e[8],eachGeometryPositionsPortion:e[9],eachGeometryNormalsPortion:e[10],eachGeometryColorsPortion:e[11],eachGeometryIndicesPortion:e[12],eachGeometryEdgeIndicesPortion:e[13],eachMeshGeometriesPortion:e[14],eachMeshMatricesPortion:e[15],eachMeshMaterial:e[16],eachEntityId:e[17],eachEntityMeshesPortion:e[18],eachTileAABB:e[19],eachTileEntitiesPortion:e[20]}}(i),a=function(e){function t(e,t){return 0===e.length?[]:uP.inflate(e,t).buffer}return{metadata:JSON.parse(uP.inflate(e.metadata,{to:"string"})),positions:new Uint16Array(t(e.positions)),normals:new Int8Array(t(e.normals)),colors:new Uint8Array(t(e.colors)),indices:new Uint32Array(t(e.indices)),edgeIndices:new Uint32Array(t(e.edgeIndices)),matrices:new Float32Array(t(e.matrices)),reusedGeometriesDecodeMatrix:new Float32Array(t(e.reusedGeometriesDecodeMatrix)),eachGeometryPrimitiveType:new Uint8Array(t(e.eachGeometryPrimitiveType)),eachGeometryPositionsPortion:new Uint32Array(t(e.eachGeometryPositionsPortion)),eachGeometryNormalsPortion:new Uint32Array(t(e.eachGeometryNormalsPortion)),eachGeometryColorsPortion:new Uint32Array(t(e.eachGeometryColorsPortion)),eachGeometryIndicesPortion:new Uint32Array(t(e.eachGeometryIndicesPortion)),eachGeometryEdgeIndicesPortion:new Uint32Array(t(e.eachGeometryEdgeIndicesPortion)),eachMeshGeometriesPortion:new Uint32Array(t(e.eachMeshGeometriesPortion)),eachMeshMatricesPortion:new Uint32Array(t(e.eachMeshMatricesPortion)),eachMeshMaterial:new Uint8Array(t(e.eachMeshMaterial)),eachEntityId:JSON.parse(uP.inflate(e.eachEntityId,{to:"string"})),eachEntityMeshesPortion:new Uint32Array(t(e.eachEntityMeshesPortion)),eachTileAABB:new Float64Array(t(e.eachTileAABB)),eachTileEntitiesPortion:new Uint32Array(t(e.eachTileEntitiesPortion))}}(n);!function(e,t,i,s,r,o){const n=o.getNextId(),a=i.metadata,l=i.positions,A=i.normals,h=i.colors,u=i.indices,d=i.edgeIndices,p=i.matrices,f=i.reusedGeometriesDecodeMatrix,g=i.eachGeometryPrimitiveType,m=i.eachGeometryPositionsPortion,v=i.eachGeometryNormalsPortion,b=i.eachGeometryColorsPortion,y=i.eachGeometryIndicesPortion,x=i.eachGeometryEdgeIndicesPortion,B=i.eachMeshGeometriesPortion,w=i.eachMeshMatricesPortion,P=i.eachMeshMaterial,C=i.eachEntityId,M=i.eachEntityMeshesPortion,E=i.eachTileAABB,F=i.eachTileEntitiesPortion,I=m.length,D=B.length,S=M.length,T=F.length;r&&r.loadData(a,{includeTypes:t.includeTypes,excludeTypes:t.excludeTypes,globalizeObjectIds:t.globalizeObjectIds});const R=new Uint32Array(I);for(let e=0;e1,C=r===I-1,M=fP(P.subarray(6*e,6*e+3)),E=P[6*e+3]/255,F=P[6*e+4]/255,D=P[6*e+5]/255,S=o.getNextId();if(a){const o=w[e],a=p.slice(o,o+16),B=`${n}-geometry.${i}.${r}`;let P=O[B];if(!P){P={batchThisMesh:!t.reuseGeometries};let e=!1;switch(g[r]){case 0:P.primitiveName="solid",P.geometryPositions=l.subarray(m[r],C?l.length:m[r+1]),P.geometryNormals=A.subarray(v[r],C?A.length:v[r+1]),P.geometryIndices=u.subarray(y[r],C?u.length:y[r+1]),P.geometryEdgeIndices=d.subarray(x[r],C?d.length:x[r+1]),e=P.geometryPositions.length>0&&P.geometryIndices.length>0;break;case 1:P.primitiveName="surface",P.geometryPositions=l.subarray(m[r],C?l.length:m[r+1]),P.geometryNormals=A.subarray(v[r],C?A.length:v[r+1]),P.geometryIndices=u.subarray(y[r],C?u.length:y[r+1]),P.geometryEdgeIndices=d.subarray(x[r],C?d.length:x[r+1]),e=P.geometryPositions.length>0&&P.geometryIndices.length>0;break;case 2:P.primitiveName="points",P.geometryPositions=l.subarray(m[r],C?l.length:m[r+1]),P.geometryColors=h.subarray(b[r],C?h.length:b[r+1]),e=P.geometryPositions.length>0;break;case 3:P.primitiveName="lines",P.geometryPositions=l.subarray(m[r],C?l.length:m[r+1]),P.geometryIndices=u.subarray(y[r],C?u.length:y[r+1]),e=P.geometryPositions.length>0&&P.geometryIndices.length>0;break;default:continue}if(e||(P=null),P&&(P.geometryPositions.length,P.batchThisMesh)){P.decompressedPositions=new Float32Array(P.geometryPositions.length),P.transformedAndRecompressedPositions=new Uint16Array(P.geometryPositions.length);const e=P.geometryPositions,t=P.decompressedPositions;for(let i=0,s=e.length;i0&&n.length>0;break;case 1:e="surface",t=l.subarray(m[r],C?l.length:m[r+1]),i=A.subarray(v[r],C?A.length:v[r+1]),n=u.subarray(y[r],C?u.length:y[r+1]),a=d.subarray(x[r],C?d.length:x[r+1]),c=t.length>0&&n.length>0;break;case 2:e="points",t=l.subarray(m[r],C?l.length:m[r+1]),o=h.subarray(b[r],C?h.length:b[r+1]),c=t.length>0;break;case 3:e="lines",t=l.subarray(m[r],C?l.length:m[r+1]),n=u.subarray(y[r],C?u.length:y[r+1]),c=t.length>0&&n.length>0;break;default:continue}c&&(s.createMesh(_.apply(j,{id:S,origin:L,primitive:e,positionsCompressed:t,normalsCompressed:i,colorsCompressed:o,indices:n,edgeIndices:a,positionsDecodeMatrix:Q,color:M,metallic:F,roughness:D,opacity:E})),k.push(S))}}k.length>0&&s.createEntity(_.apply(H,{id:E,isObject:!0,meshIds:k}))}}}(e,t,a,s,r,o)}};let mP=window.pako||Ow;mP.inflate||(mP=mP.default);const _P=c.vec4(),vP=c.vec4();const bP=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 yP(e,t){const i=[];if(t.length>1)for(let e=0,s=t.length-1;e1)for(let t=0,s=e.length/3-1;t0,a=9*e,c=1===h[a+0],u=h[a+1];h[a+2],h[a+3];const d=h[a+4],p=h[a+5],f=h[a+6],g=h[a+7],m=h[a+8];if(o){const t=new Uint8Array(l.subarray(i,r)).buffer,o=`${n}-texture-${e}`;if(c)s.createTexture({id:o,buffers:[t],minFilter:d,magFilter:p,wrapS:f,wrapT:g,wrapR:m});else{const e=new Blob([t],{type:10001===u?"image/jpeg":10002===u?"image/png":"image/gif"}),i=(window.URL||window.webkitURL).createObjectURL(e),r=document.createElement("img");r.src=i,s.createTexture({id:o,image:r,minFilter:d,magFilter:p,wrapS:f,wrapT:g,wrapR:m})}}}for(let e=0;e=0?`${n}-texture-${r}`:null,normalsTextureId:a>=0?`${n}-texture-${a}`:null,metallicRoughnessTextureId:o>=0?`${n}-texture-${o}`:null,emissiveTextureId:l>=0?`${n}-texture-${l}`:null,occlusionTextureId:A>=0?`${n}-texture-${A}`:null})}const j=new Uint32Array(N);for(let e=0;e1,l=r===N-1,A=D[e],h=A>=0?`${n}-textureSet-${A}`:null,T=bP(S.subarray(6*e,6*e+3)),R=S[6*e+3]/255,L=S[6*e+4]/255,k=S[6*e+5]/255,Q=o.getNextId();if(a){const o=I[e],a=b.slice(o,o+16),A=`${n}-geometry.${i}.${r}`;let F=W[A];if(!F){F={batchThisMesh:!t.reuseGeometries};let e=!1;switch(x[r]){case 0:F.primitiveName="solid",F.geometryPositions=u.subarray(B[r],l?u.length:B[r+1]),F.geometryNormals=d.subarray(w[r],l?d.length:w[r+1]),F.geometryUVs=f.subarray(C[r],l?f.length:C[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),F.geometryEdgeIndices=m.subarray(E[r],l?m.length:E[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 1:F.primitiveName="surface",F.geometryPositions=u.subarray(B[r],l?u.length:B[r+1]),F.geometryNormals=d.subarray(w[r],l?d.length:w[r+1]),F.geometryUVs=f.subarray(C[r],l?f.length:C[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),F.geometryEdgeIndices=m.subarray(E[r],l?m.length:E[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 2:F.primitiveName="points",F.geometryPositions=u.subarray(B[r],l?u.length:B[r+1]),F.geometryColors=p.subarray(P[r],l?p.length:P[r+1]),e=F.geometryPositions.length>0;break;case 3:F.primitiveName="lines",F.geometryPositions=u.subarray(B[r],l?u.length:B[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 4:F.primitiveName="lines",F.geometryPositions=u.subarray(B[r],l?u.length:B[r+1]),F.geometryIndices=yP(F.geometryPositions,g.subarray(M[r],l?g.length:M[r+1])),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;default:continue}if(e||(F=null),F&&(F.geometryPositions.length,F.batchThisMesh)){F.decompressedPositions=new Float32Array(F.geometryPositions.length),F.transformedAndRecompressedPositions=new Uint16Array(F.geometryPositions.length);const e=F.geometryPositions,t=F.decompressedPositions;for(let i=0,s=e.length;i0&&a.length>0;break;case 1:e="surface",t=u.subarray(B[r],l?u.length:B[r+1]),i=d.subarray(w[r],l?d.length:w[r+1]),o=f.subarray(C[r],l?f.length:C[r+1]),a=g.subarray(M[r],l?g.length:M[r+1]),A=m.subarray(E[r],l?m.length:E[r+1]),c=t.length>0&&a.length>0;break;case 2:e="points",t=u.subarray(B[r],l?u.length:B[r+1]),n=p.subarray(P[r],l?p.length:P[r+1]),c=t.length>0;break;case 3:e="lines",t=u.subarray(B[r],l?u.length:B[r+1]),a=g.subarray(M[r],l?g.length:M[r+1]),c=t.length>0&&a.length>0;break;case 4:e="lines",t=u.subarray(B[r],l?u.length:B[r+1]),a=yP(t,g.subarray(M[r],l?g.length:M[r+1])),c=t.length>0&&a.length>0;break;default:continue}c&&(s.createMesh(_.apply(H,{id:Q,textureSetId:h,origin:G,primitive:e,positionsCompressed:t,normalsCompressed:i,uv:o&&o.length>0?o:null,colorsCompressed:n,indices:a,edgeIndices:A,positionsDecodeMatrix:v,color:T,metallic:L,roughness:k,opacity:R})),U.push(Q))}}U.length>0&&s.createEntity(_.apply(Q,{id:l,isObject:!0,meshIds:U}))}}}(e,t,a,s,r,o)}},BP=c.vec4(),wP=c.vec4();const PP=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 CP(e,t){const i=[];if(t.length>1)for(let e=0,s=t.length-1;e1)for(let t=0,s=e.length/3-1;t1){const t=new Uint8Array(e,n,a),i=l/2,s=t.length/l;for(let e=0;eJSON.parse(e.decode(i(Uint8Array)))}();return{metadata:s(),textureData:i(Uint8Array),eachTextureDataPortion:i(Uint32Array),eachTextureAttributes:i(Uint16Array),positions:i(Uint16Array),normals:i(Int8Array),colors:i(Uint8Array),uvs:i(Float32Array),indices:i(Uint32Array),edgeIndices:i(Uint32Array),eachTextureSetTextures:i(Int32Array),matrices:i(Float32Array),reusedGeometriesDecodeMatrix:i(Float32Array),eachGeometryPrimitiveType:i(Uint8Array),eachGeometryPositionsPortion:i(Uint32Array),eachGeometryNormalsPortion:i(Uint32Array),eachGeometryColorsPortion:i(Uint32Array),eachGeometryUVsPortion:i(Uint32Array),eachGeometryIndicesPortion:i(Uint32Array),eachGeometryEdgeIndicesPortion:i(Uint32Array),eachMeshGeometriesPortion:i(Uint32Array),eachMeshMatricesPortion:i(Uint32Array),eachMeshTextureSet:i(Int32Array),eachMeshMaterialAttributes:i(Uint8Array),eachEntityId:s(),eachEntityMeshesPortion:i(Uint32Array),eachTileAABB:i(Float64Array),eachTileEntitiesPortion:i(Uint32Array)}}(i);!function(e,t,i,s,r,o){const n=o.getNextId(),a=i.metadata,l=i.textureData,A=i.eachTextureDataPortion,h=i.eachTextureAttributes,u=i.positions,d=i.normals,p=i.colors,f=i.uvs,g=i.indices,m=i.edgeIndices,v=i.eachTextureSetTextures,b=i.matrices,y=i.reusedGeometriesDecodeMatrix,x=i.eachGeometryPrimitiveType,B=i.eachGeometryPositionsPortion,w=i.eachGeometryNormalsPortion,P=i.eachGeometryColorsPortion,C=i.eachGeometryUVsPortion,M=i.eachGeometryIndicesPortion,E=i.eachGeometryEdgeIndicesPortion,F=i.eachMeshGeometriesPortion,I=i.eachMeshMatricesPortion,D=i.eachMeshTextureSet,S=i.eachMeshMaterialAttributes,T=i.eachEntityId,R=i.eachEntityMeshesPortion,L=i.eachTileAABB,U=i.eachTileEntitiesPortion,O=A.length,k=v.length/5,N=B.length,Q=F.length,V=R.length,H=U.length;r&&r.loadData(a,{includeTypes:t.includeTypes,excludeTypes:t.excludeTypes,globalizeObjectIds:t.globalizeObjectIds});for(let e=0;e0,a=9*e,c=1===h[a+0],u=h[a+1];h[a+2],h[a+3];const d=h[a+4],p=h[a+5],f=h[a+6],g=h[a+7],m=h[a+8];if(o){const t=new Uint8Array(l.subarray(i,r)).buffer,o=`${n}-texture-${e}`;if(c)s.createTexture({id:o,buffers:[t],minFilter:d,magFilter:p,wrapS:f,wrapT:g,wrapR:m});else{const e=new Blob([t],{type:10001===u?"image/jpeg":10002===u?"image/png":"image/gif"}),i=(window.URL||window.webkitURL).createObjectURL(e),r=document.createElement("img");r.src=i,s.createTexture({id:o,image:r,minFilter:d,magFilter:p,wrapS:f,wrapT:g,wrapR:m})}}}for(let e=0;e=0?`${n}-texture-${r}`:null,normalsTextureId:a>=0?`${n}-texture-${a}`:null,metallicRoughnessTextureId:o>=0?`${n}-texture-${o}`:null,emissiveTextureId:l>=0?`${n}-texture-${l}`:null,occlusionTextureId:A>=0?`${n}-texture-${A}`:null})}const j=new Uint32Array(N);for(let e=0;e1,l=r===N-1,A=D[e],h=A>=0?`${n}-textureSet-${A}`:null,T=PP(S.subarray(6*e,6*e+3)),R=S[6*e+3]/255,L=S[6*e+4]/255,k=S[6*e+5]/255,Q=o.getNextId();if(a){const o=I[e],a=b.slice(o,o+16),A=`${n}-geometry.${i}.${r}`;let F=W[A];if(!F){F={batchThisMesh:!t.reuseGeometries};let e=!1;switch(x[r]){case 0:F.primitiveName="solid",F.geometryPositions=u.subarray(B[r],l?u.length:B[r+1]),F.geometryNormals=d.subarray(w[r],l?d.length:w[r+1]),F.geometryUVs=f.subarray(C[r],l?f.length:C[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),F.geometryEdgeIndices=m.subarray(E[r],l?m.length:E[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 1:F.primitiveName="surface",F.geometryPositions=u.subarray(B[r],l?u.length:B[r+1]),F.geometryNormals=d.subarray(w[r],l?d.length:w[r+1]),F.geometryUVs=f.subarray(C[r],l?f.length:C[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),F.geometryEdgeIndices=m.subarray(E[r],l?m.length:E[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 2:F.primitiveName="points",F.geometryPositions=u.subarray(B[r],l?u.length:B[r+1]),F.geometryColors=p.subarray(P[r],l?p.length:P[r+1]),e=F.geometryPositions.length>0;break;case 3:F.primitiveName="lines",F.geometryPositions=u.subarray(B[r],l?u.length:B[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 4:F.primitiveName="lines",F.geometryPositions=u.subarray(B[r],l?u.length:B[r+1]),F.geometryIndices=CP(F.geometryPositions,g.subarray(M[r],l?g.length:M[r+1])),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;default:continue}if(e||(F=null),F&&(F.geometryPositions.length,F.batchThisMesh)){F.decompressedPositions=new Float32Array(F.geometryPositions.length),F.transformedAndRecompressedPositions=new Uint16Array(F.geometryPositions.length);const e=F.geometryPositions,t=F.decompressedPositions;for(let i=0,s=e.length;i0&&a.length>0;break;case 1:e="surface",t=u.subarray(B[r],l?u.length:B[r+1]),i=d.subarray(w[r],l?d.length:w[r+1]),o=f.subarray(C[r],l?f.length:C[r+1]),a=g.subarray(M[r],l?g.length:M[r+1]),A=m.subarray(E[r],l?m.length:E[r+1]),c=t.length>0&&a.length>0;break;case 2:e="points",t=u.subarray(B[r],l?u.length:B[r+1]),n=p.subarray(P[r],l?p.length:P[r+1]),c=t.length>0;break;case 3:e="lines",t=u.subarray(B[r],l?u.length:B[r+1]),a=g.subarray(M[r],l?g.length:M[r+1]),c=t.length>0&&a.length>0;break;case 4:e="lines",t=u.subarray(B[r],l?u.length:B[r+1]),a=CP(t,g.subarray(M[r],l?g.length:M[r+1])),c=t.length>0&&a.length>0;break;default:continue}c&&(s.createMesh(_.apply(H,{id:Q,textureSetId:h,origin:G,primitive:e,positionsCompressed:t,normalsCompressed:i,uv:o&&o.length>0?o:null,colorsCompressed:n,indices:a,edgeIndices:A,positionsDecodeMatrix:v,color:T,metallic:L,roughness:k,opacity:R})),U.push(Q))}}U.length>0&&s.createEntity(_.apply(Q,{id:l,isObject:!0,meshIds:U}))}}}(e,t,n,s,r,o)}},EP={};EP[Qw.version]=Qw,EP[jw.version]=jw,EP[Ww.version]=Ww,EP[Jw.version]=Jw,EP[qw.version]=qw,EP[tP.version]=tP,EP[oP.version]=oP,EP[cP.version]=cP,EP[gP.version]=gP,EP[xP.version]=xP,EP[MP.version]=MP;var FP={};!function(e){var t,i="File format is not recognized.",s="Error while reading zip file.",r="Error while reading file data.",o=524288,n="text/plain";try{t=0===new Blob([new DataView(new ArrayBuffer(0))]).size}catch(e){}function a(){this.crc=-1}function l(){}function A(e,t){var i,s;return i=new ArrayBuffer(e),s=new Uint8Array(i),t&&s.set(t,0),{buffer:i,array:s,view:new DataView(i)}}function h(){}function c(e){var t,i=this;i.size=0,i.init=function(s,r){var o=new Blob([e],{type:n});(t=new d(o)).init((function(){i.size=t.size,s()}),r)},i.readUint8Array=function(e,i,s,r){t.readUint8Array(e,i,s,r)}}function u(t){var i,s=this;s.size=0,s.init=function(e){for(var r=t.length;"="==t.charAt(r-1);)r--;i=t.indexOf(",")+1,s.size=Math.floor(.75*(r-i)),e()},s.readUint8Array=function(s,r,o){var n,a=A(r),l=4*Math.floor(s/3),h=4*Math.ceil((s+r)/3),c=e.atob(t.substring(l+i,h+i)),u=s-3*Math.floor(l/4);for(n=u;ne.size)throw new RangeError("offset:"+t+", length:"+i+", size:"+e.size);return e.slice?e.slice(t,t+i):e.webkitSlice?e.webkitSlice(t,t+i):e.mozSlice?e.mozSlice(t,t+i):e.msSlice?e.msSlice(t,t+i):void 0}(e,t,i))}catch(e){r(e)}}}function p(){}function f(e){var i,s=this;s.init=function(e){i=new Blob([],{type:n}),e()},s.writeUint8Array=function(e,s){i=new Blob([i,t?e:e.buffer],{type:n}),s()},s.getData=function(t,s){var r=new FileReader;r.onload=function(e){t(e.target.result)},r.onerror=s,r.readAsText(i,e)}}function g(t){var i=this,s="",r="";i.init=function(e){s+="data:"+(t||"")+";base64,",e()},i.writeUint8Array=function(t,i){var o,n=r.length,a=r;for(r="",o=0;o<3*Math.floor((n+t.length)/3)-n;o++)a+=String.fromCharCode(t[o]);for(;o2?s+=e.btoa(a):r=a,i()},i.getData=function(t){t(s+e.btoa(r))}}function m(e){var i,s=this;s.init=function(t){i=new Blob([],{type:e}),t()},s.writeUint8Array=function(s,r){i=new Blob([i,t?s:s.buffer],{type:e}),r()},s.getData=function(e){e(i)}}function _(e,t,i,s,r,n,a,l,A,h){var c,u,d,p=0,f=t.sn;function g(){e.removeEventListener("message",m,!1),l(u,d)}function m(t){var i=t.data,r=i.data,o=i.error;if(o)return o.toString=function(){return"Error: "+this.message},void A(o);if(i.sn===f)switch("number"==typeof i.codecTime&&(e.codecTime+=i.codecTime),"number"==typeof i.crcTime&&(e.crcTime+=i.crcTime),i.type){case"append":r?(u+=r.length,s.writeUint8Array(r,(function(){_()}),h)):_();break;case"flush":d=i.crc,r?(u+=r.length,s.writeUint8Array(r,(function(){g()}),h)):g();break;case"progress":a&&a(c+i.loaded,n);break;case"importScripts":case"newTask":case"echo":break;default:console.warn("zip.js:launchWorkerProcess: unknown message: ",i)}}function _(){(c=p*o)<=n?i.readUint8Array(r+c,Math.min(o,n-c),(function(i){a&&a(c,n);var s=0===c?t:{sn:f};s.type="append",s.data=i;try{e.postMessage(s,[i.buffer])}catch(t){e.postMessage(s)}p++}),A):e.postMessage({sn:f,type:"flush"})}u=0,e.addEventListener("message",m,!1),_()}function v(e,t,i,s,r,n,l,A,h,c){var u,d=0,p=0,f="input"===n,g="output"===n,m=new a;!function n(){var a;if((u=d*o)127?r[i-128]:String.fromCharCode(i);return s}function x(e){return decodeURIComponent(escape(e))}function B(e){var t,i="";for(t=0;t>16,i=65535&e;try{return new Date(1980+((65024&t)>>9),((480&t)>>5)-1,31&t,(63488&i)>>11,(2016&i)>>5,2*(31&i),0)}catch(e){}}(e.lastModDateRaw),1!=(1&e.bitFlag)?((s||8!=(8&e.bitFlag))&&(e.crc32=t.view.getUint32(i+10,!0),e.compressedSize=t.view.getUint32(i+14,!0),e.uncompressedSize=t.view.getUint32(i+18,!0)),4294967295!==e.compressedSize&&4294967295!==e.uncompressedSize?(e.filenameLength=t.view.getUint16(i+22,!0),e.extraFieldLength=t.view.getUint16(i+24,!0)):r("File is using Zip64 (4gb+ file size).")):r("File contains encrypted entry.")}function P(t,o,n){var a=0;function l(){}l.prototype.getData=function(s,o,l,h){var c=this;function u(e,t){h&&!function(e){var t=A(4);return t.view.setUint32(0,e),c.crc32==t.view.getUint32(0)}(t)?n("CRC failed."):s.getData((function(e){o(e)}))}function d(e){n(e||r)}function p(e){n(e||"Error while writing file data.")}t.readUint8Array(c.offset,30,(function(r){var o,f=A(r.length,r);1347093252==f.view.getUint32(0)?(w(c,f,4,!1,n),o=c.offset+30+c.filenameLength+c.extraFieldLength,s.init((function(){0===c.compressionMethod?b(c._worker,a++,t,s,o,c.compressedSize,h,u,l,d,p):function(t,i,s,r,o,n,a,l,A,h,c){var u=a?"output":"none";e.zip.useWebWorkers?_(t,{sn:i,codecClass:"Inflater",crcType:u},s,r,o,n,A,l,h,c):v(new e.zip.Inflater,s,r,o,n,u,A,l,h,c)}(c._worker,a++,t,s,o,c.compressedSize,h,u,l,d,p)}),p)):n(i)}),d)};var h={getEntries:function(e){var r=this._worker;!function(e){t.size<22?n(i):r(22,(function(){r(Math.min(65558,t.size),(function(){n(i)}))}));function r(i,r){t.readUint8Array(t.size-i,i,(function(t){for(var i=t.length-22;i>=0;i--)if(80===t[i]&&75===t[i+1]&&5===t[i+2]&&6===t[i+3])return void e(new DataView(t.buffer,i,22));r()}),(function(){n(s)}))}}((function(o){var a,h;a=o.getUint32(16,!0),h=o.getUint16(8,!0),a<0||a>=t.size?n(i):t.readUint8Array(a,t.size-a,(function(t){var s,o,a,c,u=0,d=[],p=A(t.length,t);for(s=0;s>>8^i[255&(t^e[s])];this.crc=t},a.prototype.get=function(){return~this.crc},a.prototype.table=function(){var e,t,i,s=[];for(e=0;e<256;e++){for(i=e,t=0;t<8;t++)1&i?i=i>>>1^3988292384:i>>>=1;s[e]=i}return s}(),l.prototype.append=function(e,t){return e},l.prototype.flush=function(){},c.prototype=new h,c.prototype.constructor=c,u.prototype=new h,u.prototype.constructor=u,d.prototype=new h,d.prototype.constructor=d,p.prototype.getData=function(e){e(this.data)},f.prototype=new p,f.prototype.constructor=f,g.prototype=new p,g.prototype.constructor=g,m.prototype=new p,m.prototype.constructor=m;var F={deflater:["z-worker.js","deflate.js"],inflater:["z-worker.js","inflate.js"]};function I(t,i,s){if(null===e.zip.workerScripts||null===e.zip.workerScriptsPath){var r;if(e.zip.workerScripts){if(r=e.zip.workerScripts[t],!Array.isArray(r))return void s(new Error("zip.workerScripts."+t+" is not an array!"));r=function(e){var t=document.createElement("a");return e.map((function(e){return t.href=e,t.href}))}(r)}else(r=F[t].slice(0))[0]=(e.zip.workerScriptsPath||"")+r[0];var o=new Worker(r[0]);o.codecTime=o.crcTime=0,o.postMessage({type:"importScripts",scripts:r.slice(1)}),o.addEventListener("message",(function e(t){var r=t.data;if(r.error)return o.terminate(),void s(r.error);"importScripts"===r.type&&(o.removeEventListener("message",e),o.removeEventListener("error",n),i(o))})),o.addEventListener("error",n)}else s(new Error("Either zip.workerScripts or zip.workerScriptsPath may be set, not both."));function n(e){o.terminate(),s(e)}}function D(e){console.error(e)}e.zip={Reader:h,Writer:p,BlobReader:d,Data64URIReader:u,TextReader:c,BlobWriter:m,Data64URIWriter:g,TextWriter:f,createReader:function(e,t,i){i=i||D,e.init((function(){P(e,t,i)}),i)},createWriter:function(e,t,i,s){i=i||D,s=!!s,e.init((function(){E(e,t,i,s)}),i)},useWebWorkers:!0,workerScriptsPath:null,workerScripts:null}}(FP);const IP=FP.zip;!function(e){var t,i,s=e.Reader,r=e.Writer;try{i=0===new Blob([new DataView(new ArrayBuffer(0))]).size}catch(e){}function o(e){var t=this;function i(i,s){var r;t.data?i():((r=new XMLHttpRequest).addEventListener("load",(function(){t.size||(t.size=Number(r.getResponseHeader("Content-Length"))||Number(r.response.byteLength)),t.data=new Uint8Array(r.response),i()}),!1),r.addEventListener("error",s,!1),r.open("GET",e),r.responseType="arraybuffer",r.send())}t.size=0,t.init=function(s,r){if(function(e){var t=document.createElement("a");return t.href=e,"http:"===t.protocol||"https:"===t.protocol}(e)){var o=new XMLHttpRequest;o.addEventListener("load",(function(){t.size=Number(o.getResponseHeader("Content-Length")),t.size?s():i(s,r)}),!1),o.addEventListener("error",r,!1),o.open("HEAD",e),o.send()}else i(s,r)},t.readUint8Array=function(e,s,r,o){i((function(){r(new Uint8Array(t.data.subarray(e,e+s)))}),o)}}function n(e){var t=this;t.size=0,t.init=function(i,s){var r=new XMLHttpRequest;r.addEventListener("load",(function(){t.size=Number(r.getResponseHeader("Content-Length")),"bytes"==r.getResponseHeader("Accept-Ranges")?i():s("HTTP Range not supported.")}),!1),r.addEventListener("error",s,!1),r.open("HEAD",e),r.send()},t.readUint8Array=function(t,i,s,r){!function(t,i,s,r){var o=new XMLHttpRequest;o.open("GET",e),o.responseType="arraybuffer",o.setRequestHeader("Range","bytes="+t+"-"+(t+i-1)),o.addEventListener("load",(function(){s(o.response)}),!1),o.addEventListener("error",r,!1),o.send()}(t,i,(function(e){s(new Uint8Array(e))}),r)}}function a(e){var t=this;t.size=0,t.init=function(i,s){t.size=e.byteLength,i()},t.readUint8Array=function(t,i,s,r){s(new Uint8Array(e.slice(t,t+i)))}}function l(){var e,t=this;t.init=function(t,i){e=new Uint8Array,t()},t.writeUint8Array=function(t,i,s){var r=new Uint8Array(e.length+t.length);r.set(e),r.set(t,e.length),e=r,i()},t.getData=function(t){t(e.buffer)}}function A(e,t){var s,r=this;r.init=function(t,i){e.createWriter((function(e){s=e,t()}),i)},r.writeUint8Array=function(e,r,o){var n=new Blob([i?e:e.buffer],{type:t});s.onwrite=function(){s.onwrite=null,r()},s.onerror=o,s.write(n)},r.getData=function(t){e.file(t)}}o.prototype=new s,o.prototype.constructor=o,n.prototype=new s,n.prototype.constructor=n,a.prototype=new s,a.prototype.constructor=a,l.prototype=new r,l.prototype.constructor=l,A.prototype=new r,A.prototype.constructor=A,e.FileWriter=A,e.HttpReader=o,e.HttpRangeReader=n,e.ArrayBufferReader=a,e.ArrayBufferWriter=l,e.fs&&((t=e.fs.ZipDirectoryEntry).prototype.addHttpContent=function(i,s,r){return function(i,s,r,o){if(i.directory)return o?new t(i.fs,s,r,i):new e.fs.ZipFileEntry(i.fs,s,r,i);throw"Parent entry is not a directory."}(this,i,{data:s,Reader:r?n:o})},t.prototype.importHttpContent=function(e,t,i,s){this.importZip(t?new n(e):new o(e),i,s)},e.fs.FS.prototype.importHttpContent=function(e,i,s,r){this.entries=[],this.root=new t(this),this.root.importHttpContent(e,i,s,r)})}(IP);const DP=["4.2"];class SP{constructor(e,t={}){this.supportedSchemas=DP,this._xrayOpacity=.7,this._src=null,this._options=t,this.viewpoint=null,t.workerScriptsPath?(IP.workerScriptsPath=t.workerScriptsPath,this.src=t.src,this.xrayOpacity=.7,this.displayEffect=t.displayEffect,this.createMetaModel=t.createMetaModel):e.error("Config expected: workerScriptsPath")}load(e,t,i,s,r,o){switch(s.materialType){case"MetallicMaterial":t._defaultMaterial=new bs(t,{baseColor:[1,1,1],metallic:.6,roughness:.6});break;case"SpecularMaterial":t._defaultMaterial=new Bs(t,{diffuse:[1,1,1],specular:c.vec3([1,1,1]),glossiness:.5});break;default:t._defaultMaterial=new Jt(t,{reflectivity:.75,shiness:100,diffuse:[1,1,1]})}t._wireframeMaterial=new ms(t,{color:[0,0,0],lineWidth:2});var n=t.scene.canvas.spinner;n.processes++,TP(e,t,i,s,(function(){n.processes--,r&&r(),t.fire("loaded",!0,!1)}),(function(e){n.processes--,t.error(e),o&&o(e),t.fire("error",e)}),(function(e){console.log("Error, Will Robinson: "+e)}))}}var TP=function(e,t,i,s,r,o){!function(e,t,i){var s=new VP;s.load(e,(function(){t(s)}),(function(e){i("Error loading ZIP archive: "+e)}))}(i,(function(i){RP(e,i,s,t,r,o)}),o)},RP=function(){return function(t,i,s,r,o){var n={plugin:t,zip:i,edgeThreshold:30,materialType:s.materialType,scene:r.scene,modelNode:r,info:{references:{}},materials:{}};s.createMetaModel&&(n.metaModelData={modelId:r.id,metaObjects:[{name:r.id,type:"Default",id:r.id}]}),r.scene.loading++,function(t,i){t.zip.getFile("Manifest.xml",(function(s,r){for(var o=r.children,n=0,a=o.length;n0){for(var n=o.trim().split(" "),a=new Int16Array(n.length),l=0,A=0,h=n.length;A0){i.primitive="triangles";for(var o=[],n=0,a=r.length;n=t.length)i();else{var a=t[o].id,l=a.lastIndexOf(":");l>0&&(a=a.substring(l+1));var A=a.lastIndexOf("#");A>0&&(a=a.substring(0,A)),s[a]?r(o+1):function(e,t,i){e.zip.getFile(t,(function(t,s){!function(e,t,i){for(var s,r=t.children,o=0,n=r.length;o0)for(var s=0,r=t.length;s-1?e+"&_="+t:e+"?_="+t}getIFC(e,t,i){e=this._cacheBusterURL(e);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),i=new Uint8Array(e);for(var n=0;n-1?e+"&_="+t:e+"?_="+t}getLAS(e,t,i){e=this._cacheBusterURL(e);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),i=new Uint8Array(e);for(var n=0;n{let t=0,i=0,s=0;const r=new DataView(e),o=new Uint8Array(6e3),n=({item:s,format:o,size:n})=>{let a,l;switch(o){case"char":return l=new Uint8Array(e,t,n),t+=n,a=YP(l),[s,a];case"uShort":return a=r.getUint16(t,!0),t+=n,[s,a];case"uLong":return a=r.getUint32(t,!0),"NumberOfVariableLengthRecords"===s&&(i=a),t+=n,[s,a];case"uChar":return a=r.getUint8(t),t+=n,[s,a];case"double":return a=r.getFloat64(t,!0),t+=n,[s,a];default:t+=n}};return(()=>{const e={};WP.forEach((t=>{const i=n({...t});if(void 0!==i){if("FileSignature"===i[0]&&"LASF"!==i[1])throw new Error("Ivalid FileSignature. Is this a LAS/LAZ file");e[i[0]]=i[1]}}));const r=[];let a=i;for(;a--;){const e={};KP.forEach((i=>{const r=n({...i});e[r[0]]=r[1],"UserId"===r[0]&&"LASF_Projection"===r[1]&&(s=t-18+54)})),r.push(e)}const l=(e=>{if(void 0===e)return;const t=s+e.RecordLengthAfterHeader,i=o.slice(s,t),r=JP(i),n=new DataView(r);let a=6,l=Number(n.getUint16(a,!0));const A=[];for(;l--;){const e={};e.key=n.getUint16(a+=2,!0),e.tiffTagLocation=n.getUint16(a+=2,!0),e.count=n.getUint16(a+=2,!0),e.valueOffset=n.getUint16(a+=2,!0),A.push(e)}const h=A.find((e=>3072===e.key));if(h&&h.hasOwnProperty("valueOffset"))return h.valueOffset})(r.find((e=>"LASF_Projection"===e.UserId)));return l&&(e.epsg=l),e})()},JP=e=>{let t=new ArrayBuffer(e.length),i=new Uint8Array(t);for(let t=0;t{let t="";return e.forEach((e=>{let i=String.fromCharCode(e);"\0"!==i&&(t+=i)})),t.trim()};function ZP(e,t){if(t>=e.length)return[e];let i=[];for(let s=0;s-1?e+"&_="+t:e+"?_="+t}getCityJSON(e,t,i){_.loadJSON(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}}function $P(e,t,i){i=i||2;var s,r,o,n,a,l,A,h=t&&t.length,c=h?t[0]*i:e.length,u=eC(e,0,c,i,!0),d=[];if(!u||u.next===u.prev)return d;if(h&&(u=function(e,t,i,s){var r,o,n,a=[];for(r=0,o=t.length;r80*i){s=o=e[0],r=n=e[1];for(var p=i;po&&(o=a),l>n&&(n=l);A=0!==(A=Math.max(o-s,n-r))?1/A:0}return iC(u,d,i,s,r,A),d}function eC(e,t,i,s,r){var o,n;if(r===wC(e,t,i,s)>0)for(o=t;o=t;o-=s)n=yC(o,e[o],e[o+1],n);return n&&fC(n,n.next)&&(xC(n),n=n.next),n}function tC(e,t){if(!e)return e;t||(t=e);var i,s=e;do{if(i=!1,s.steiner||!fC(s,s.next)&&0!==pC(s.prev,s,s.next))s=s.next;else{if(xC(s),(s=t=s.prev)===s.next)break;i=!0}}while(i||s!==t);return t}function iC(e,t,i,s,r,o,n){if(e){!n&&o&&function(e,t,i,s){var r=e;do{null===r.z&&(r.z=hC(r.x,r.y,t,i,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==e);r.prevZ.nextZ=null,r.prevZ=null,function(e){var t,i,s,r,o,n,a,l,A=1;do{for(i=e,e=null,o=null,n=0;i;){for(n++,s=i,a=0,t=0;t0||l>0&&s;)0!==a&&(0===l||!s||i.z<=s.z)?(r=i,i=i.nextZ,a--):(r=s,s=s.nextZ,l--),o?o.nextZ=r:e=r,r.prevZ=o,o=r;i=s}o.nextZ=null,A*=2}while(n>1)}(r)}(e,s,r,o);for(var a,l,A=e;e.prev!==e.next;)if(a=e.prev,l=e.next,o?rC(e,s,r,o):sC(e))t.push(a.i/i),t.push(e.i/i),t.push(l.i/i),xC(e),e=l.next,A=l.next;else if((e=l)===A){n?1===n?iC(e=oC(tC(e),t,i),t,i,s,r,o,2):2===n&&nC(e,t,i,s,r,o):iC(tC(e),t,i,s,r,o,1);break}}}function sC(e){var t=e.prev,i=e,s=e.next;if(pC(t,i,s)>=0)return!1;for(var r=e.next.next;r!==e.prev;){if(uC(t.x,t.y,i.x,i.y,s.x,s.y,r.x,r.y)&&pC(r.prev,r,r.next)>=0)return!1;r=r.next}return!0}function rC(e,t,i,s){var r=e.prev,o=e,n=e.next;if(pC(r,o,n)>=0)return!1;for(var a=r.xo.x?r.x>n.x?r.x:n.x:o.x>n.x?o.x:n.x,h=r.y>o.y?r.y>n.y?r.y:n.y:o.y>n.y?o.y:n.y,c=hC(a,l,t,i,s),u=hC(A,h,t,i,s),d=e.prevZ,p=e.nextZ;d&&d.z>=c&&p&&p.z<=u;){if(d!==e.prev&&d!==e.next&&uC(r.x,r.y,o.x,o.y,n.x,n.y,d.x,d.y)&&pC(d.prev,d,d.next)>=0)return!1;if(d=d.prevZ,p!==e.prev&&p!==e.next&&uC(r.x,r.y,o.x,o.y,n.x,n.y,p.x,p.y)&&pC(p.prev,p,p.next)>=0)return!1;p=p.nextZ}for(;d&&d.z>=c;){if(d!==e.prev&&d!==e.next&&uC(r.x,r.y,o.x,o.y,n.x,n.y,d.x,d.y)&&pC(d.prev,d,d.next)>=0)return!1;d=d.prevZ}for(;p&&p.z<=u;){if(p!==e.prev&&p!==e.next&&uC(r.x,r.y,o.x,o.y,n.x,n.y,p.x,p.y)&&pC(p.prev,p,p.next)>=0)return!1;p=p.nextZ}return!0}function oC(e,t,i){var s=e;do{var r=s.prev,o=s.next.next;!fC(r,o)&&gC(r,s,s.next,o)&&vC(r,o)&&vC(o,r)&&(t.push(r.i/i),t.push(s.i/i),t.push(o.i/i),xC(s),xC(s.next),s=e=o),s=s.next}while(s!==e);return tC(s)}function nC(e,t,i,s,r,o){var n=e;do{for(var a=n.next.next;a!==n.prev;){if(n.i!==a.i&&dC(n,a)){var l=bC(n,a);return n=tC(n,n.next),l=tC(l,l.next),iC(n,t,i,s,r,o),void iC(l,t,i,s,r,o)}a=a.next}n=n.next}while(n!==e)}function aC(e,t){return e.x-t.x}function lC(e,t){if(t=function(e,t){var i,s=t,r=e.x,o=e.y,n=-1/0;do{if(o<=s.y&&o>=s.next.y&&s.next.y!==s.y){var a=s.x+(o-s.y)*(s.next.x-s.x)/(s.next.y-s.y);if(a<=r&&a>n){if(n=a,a===r){if(o===s.y)return s;if(o===s.next.y)return s.next}i=s.x=s.x&&s.x>=h&&r!==s.x&&uC(oi.x||s.x===i.x&&AC(i,s)))&&(i=s,u=l)),s=s.next}while(s!==A);return i}(e,t),t){var i=bC(t,e);tC(t,t.next),tC(i,i.next)}}function AC(e,t){return pC(e.prev,e,t.prev)<0&&pC(t.next,e,e.next)<0}function hC(e,t,i,s,r){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-i)*r)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-s)*r)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function cC(e){var t=e,i=e;do{(t.x=0&&(e-n)*(s-a)-(i-n)*(t-a)>=0&&(i-n)*(o-a)-(r-n)*(s-a)>=0}function dC(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){var i=e;do{if(i.i!==e.i&&i.next.i!==e.i&&i.i!==t.i&&i.next.i!==t.i&&gC(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}(e,t)&&(vC(e,t)&&vC(t,e)&&function(e,t){var i=e,s=!1,r=(e.x+t.x)/2,o=(e.y+t.y)/2;do{i.y>o!=i.next.y>o&&i.next.y!==i.y&&r<(i.next.x-i.x)*(o-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==e);return s}(e,t)&&(pC(e.prev,e,t.prev)||pC(e,t.prev,t))||fC(e,t)&&pC(e.prev,e,e.next)>0&&pC(t.prev,t,t.next)>0)}function pC(e,t,i){return(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y)}function fC(e,t){return e.x===t.x&&e.y===t.y}function gC(e,t,i,s){var r=_C(pC(e,t,i)),o=_C(pC(e,t,s)),n=_C(pC(i,s,e)),a=_C(pC(i,s,t));return r!==o&&n!==a||(!(0!==r||!mC(e,i,t))||(!(0!==o||!mC(e,s,t))||(!(0!==n||!mC(i,e,s))||!(0!==a||!mC(i,t,s)))))}function mC(e,t,i){return t.x<=Math.max(e.x,i.x)&&t.x>=Math.min(e.x,i.x)&&t.y<=Math.max(e.y,i.y)&&t.y>=Math.min(e.y,i.y)}function _C(e){return e>0?1:e<0?-1:0}function vC(e,t){return pC(e.prev,e,e.next)<0?pC(e,t,e.next)>=0&&pC(e,e.prev,t)>=0:pC(e,t,e.prev)<0||pC(e,e.next,t)<0}function bC(e,t){var i=new BC(e.i,e.x,e.y),s=new BC(t.i,t.x,t.y),r=e.next,o=t.prev;return e.next=t,t.prev=e,i.next=r,r.prev=i,s.next=i,i.prev=s,o.next=s,s.prev=o,s}function yC(e,t,i,s){var r=new BC(e,t,i);return s?(r.next=s.next,r.prev=s,s.next.prev=r,s.next=r):(r.prev=r,r.next=r),r}function xC(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function BC(e,t,i){this.i=e,this.x=t,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function wC(e,t,i,s){for(var r=0,o=t,n=i-s;o0&&(s+=e[r-1].length,i.holes.push(s))}return i};const PC=c.vec2(),CC=c.vec3(),MC=c.vec3(),EC=c.vec3();class FC{constructor(e={}){this.cacheBuster=!1!==e.cacheBuster}_cacheBusterURL(e){if(!this.cacheBuster)return e;const t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}getDotBIM(e,t,i){_.loadJSON(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}}const IC=function(e){const t=t=>parseInt(e.substr(t+1,2),16)/255;return[t(0),t(2),t(4)]},DC=function(e){const t=[];for(let i=0;i=0?h:2*Math.PI-h}return r(e[0]-i[0])*(t[1]-i[1])-(t[0]-i[0])*(e[1]-i[1]);return(t,i,s,r)=>{const o=e(t,i,s),n=e(t,s,r),a=e(t,r,i);return!((o<0||n<0||a<0)&&(o>0||n>0||a>0))}}(),r=[],o=(i?t:t.slice(0).reverse()).map((e=>({idx:e})));o.forEach(((e,t)=>{e.prev=o[(t-1+o.length)%o.length],e.next=o[(t+1)%o.length]}));const n=c.vec2(),a=c.vec2();for(;o.length>2;){let t=0;for(;;){if(t>=o.length)throw`isCCW = ${i}; earIdx = ${t}; len = ${o.length}`;const r=o[t],l=e[r.prev.idx],A=e[r.idx],h=e[r.next.idx];if(c.subVec2(l,A,n),c.subVec2(h,A,a),n[0]*a[1]-n[1]*a[0]>=0&&o.every((t=>t===r||t===r.prev||t===r.next||!s(e[t.idx],l,A,h))))break;++t}const l=o[t];o.splice(t,1),r.push([l.idx,l.next.idx,l.prev.idx]);l.prev.next=l.next;l.next.prev=l.prev}return[e,r,i]},SC=function(e,t){const i=e.canvas.canvas,s=i.parentNode,r=document.createElement("div");s.insertBefore(r,i);let o=5;r.style.background=t,r.style.border="2px solid white",r.style.margin="0 0",r.style.zIndex="100",r.style.position="absolute",r.style.pointerEvents="none",r.style.display="none";const n=new Ae(e,{}),a=e=>e+"px",l=function(){const e=n.canvasPos.slice();ce(i,s,e),r.style.left=a(e[0]-3-o/2),r.style.top=a(e[1]-3-o/2),r.style.borderRadius=a(2*o),r.style.width=a(o),r.style.height=a(o)},A=e.camera.on("viewMatrix",l),h=e.camera.on("projMatrix",l);return{update:function(e){e&&(n.worldPos=e,l()),r.style.display=e?"":"none"},setHighlighted:function(e){o=e?10:5,l()},getCanvasPos:()=>n.canvasPos,getWorldPos:()=>n.worldPos,destroy:function(){r.parentNode.removeChild(r),e.camera.off(A),e.camera.off(h),n.destroy()}}},TC=function(e,t,i){let s=null;const r=r=>{if(r){s&&s.destroy();try{const[o,n]=DC(r.map((e=>[e[0],e[2]]))),a=[].concat(...o.map((e=>[e[0],r[0][1],e[1]]))),l=[].concat(...n);s=new es(e,{pickable:!1,geometry:new Gt(e,{positions:a,indices:l,normals:c.buildNormals(a,l)}),material:new Jt(e,{alpha:void 0!==i?i:.5,backfaces:!0,diffuse:IC(t)})})}catch(e){s=null}}s&&(s.visible=!!r)};return r(null),{updateBase:r,destroy:()=>s&&s.destroy()}},RC=function(e,t){return function(i,s,r){const o=e.scene,n=o.canvas.canvas,a=(e,t)=>(t[0]=e.clientX,t[1]=e.clientY,ce(n.ownerDocument.documentElement,n,t),t),l=e=>{const i=c.vec3(),s=c.vec3();return c.canvasPosToWorldRay(n,o.camera.viewMatrix,o.camera.projMatrix,o.camera.projection,e,i,s),t(i,s)};let A=!1;const h=function(){A=!1},u=function(){h(),n.removeEventListener("mousedown",p),n.removeEventListener("mousemove",f),e.cameraControl.off(g),n.removeEventListener("mouseup",m)},d=c.vec2(),p=function(e){1===e.which&&(a(e,d),A=!0)};n.addEventListener("mousedown",p);const f=function(e){const t=a(e,c.vec2());A&&c.distVec2(d,t)>20&&(h(),i())};n.addEventListener("mousemove",f);const g=e.cameraControl.on("rayMove",(e=>{const t=e.canvasPos;s(t,l(t))})),m=function(e){if(1===e.which&&A){u();const t=a(e,c.vec2());r(t,l(t))}};return n.addEventListener("mouseup",m),u}},LC=function(e,t,i,s){const r=-(c.dotVec3(i,t)-e)/c.dotVec3(s,t);{const e=c.vec3();return c.mulVec3Scalar(s,r,e),c.addVec3(i,e,e),e}};class UC extends D{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={},this.plugin.viewer.scene,this._geometry=t.geometry,t.onMouseOver,t.onMouseLeave,t.onContextMenu,this._alpha="alpha"in t&&void 0!==t.alpha?t.alpha:.5,this.color=t.color,this._visible=!0,this._rebuildMesh()}_rebuildMesh(){const e=this.plugin.viewer.scene,t=this._geometry.planeCoordinates.slice(),i=this._geometry.height<0,s=this._geometry.altitude+(i?this._geometry.height:0),r=this._geometry.height*(i?-1:1),[o,n,a]=DC(t),l=[],A=[],h=e=>{const t=l.length;for(let t of o)l.push([t[0],s+(e?r:0),t[1]]);for(let i of n)A.push(...(e?i:i.slice(0).reverse()).map((e=>e+t)))};h(!1),h(!0);for(let e=0;ee+c)))}this._zoneMesh&&this._zoneMesh.destroy();const u=[].concat(...l);this._zoneMesh=new es(e,{edges:this._edges,geometry:new Gt(e,{positions:u,indices:A,normals:c.buildNormals(u,A)}),material:new Jt(e,{alpha:this._alpha,backfaces:!0,diffuse:IC(this._color)}),visible:this._visible}),this._zoneMesh.highlighted=this._highlighted,this._zoneMesh.zone=this;{const e=c.vec2(),t=c.vec2();let i=0;for(let s of n){const r=o[s[0]],n=o[s[1]],a=o[s[2]];c.subVec2(n,r,e),c.subVec2(a,r,t),i+=Math.abs(e[0]*t[1]-e[1]*t[0])}this._baseArea=i/2}this._metrics=null;const d=e=>Math.min(...l.map((t=>t[e]))),p=e=>Math.max(...l.map((t=>t[e]))),f=d(0),g=d(1),m=d(2),_=p(0),v=p(1),b=p(2);this._center=c.vec3([(f+_)/2,(g+v)/2,(m+b)/2])}get baseArea(){return this._baseArea}get area(){return this._getMetrics().area}get volume(){return this._getMetrics().volume}_getMetrics(){if(null===this._metrics){let e=0,t=0;const i=this._zoneMesh.geometry,s=[c.vec3(),c.vec3(),c.vec3()],r=c.vec3();for(let o=0;o{const s=t.map((t=>[t[0],e?r:o,t[1]]));i.push(e?s:s.slice(0).reverse())};n(!0),n(!1);const a=(e,i)=>[t[e][0],i,t[e][1]];for(let e=0;ei?a:n;h|=A,u.push(A)}switch(h){case n:case a:o.push(t);break;case l:break;case A:const i=[];for(let o=0;o=3&&o.push(i)}}i=o}if(0===i.length)return null;{const e=c.vec3([0,0,0]),t=new Set;for(const s of i)for(const i of s){const s=i.map((e=>e.toFixed(3))).join(":");t.has(s)||(t.add(s),c.addVec3(e,i,e))}return c.mulVec3Scalar(e,1/t.size,e),e}}get center(){return this._center}get altitude(){return this._geometry.altitude}set altitude(e){this._geometry.altitude=e,this._rebuildMesh()}get height(){return this._geometry.height}set height(e){this._geometry.height=e,this._rebuildMesh()}get highlighted(){return this._highlighted}set highlighted(e){this._highlighted=e,this._zoneMesh&&(this._zoneMesh.highlighted=e)}set color(e){this._color=e,this._zoneMesh&&(this._zoneMesh.material.diffuse=IC(this._color))}get color(){return this._color}set alpha(e){this._alpha=e,this._zoneMesh&&(this._zoneMesh.material.alpha=this._alpha)}get alpha(){return this._alpha}get edges(){return this._edges}set edges(e){this._edges=e,this._zoneMesh&&(this._zoneMesh.edges=this._edges)}set visible(e){this._visible=!!e,this._zoneMesh.visible=this._visible,this._needUpdate()}get visible(){return this._visible}getJSON(){return{id:this.id,geometry:this._geometry,alpha:this._alpha,color:this._color}}duplicate(){return this.plugin.createZone({id:c.createUUID(),geometry:{planeCoordinates:this._geometry.planeCoordinates.map((e=>e.slice())),altitude:this._geometry.altitude,height:this._geometry.height},alpha:this._alpha,color:this._color})}destroy(){this._zoneMesh.destroy(),super.destroy()}}class OC extends D{constructor(e,t,i){super(e.viewer.scene),this.zonesPlugin=e,this.pointerLens=t.pointerLens,this.createSelect3dPoint=i,this._deactivate=null}get active(){return!!this._deactivate}activate(e,t,i,s){if(this._deactivate)return;if("object"==typeof e&&null!==e){const r=e,o=(e,t)=>{if(e in r)return r[e];if(void 0!==t)return t;throw"config missing: "+e};e=o("altitude"),t=o("height"),i=o("color","#008000"),s=o("alpha",.5)}const r=this.zonesPlugin,o=r.viewer,n=o.scene,a=this,l=this.createSelect3dPoint(o,((t,i)=>LC(e,c.vec3([0,1,0]),t,i)));!function o(){const A=TC(n,i,s),h=function(e,t,i,s,r,o){const n=SC(e,t),a=SC(e,t),l=i?function(e){i.visible=!!e,e&&(i.canvasPos=e)}:()=>{};let A=s((()=>{l(null),n.update(null)}),((e,t)=>{l(e),n.update(t)}),(function(e,t){n.update(t),A=s((function(){l(null),a.update(null),r(null)}),(function(e,i){l(e),a.update(i),r(c.distVec3(t,i)>.01&&[t,i])}),(function(e,i){a.update(i),n.destroy(),a.destroy(),l(null),o([t,i])}))}));return{deactivate:function(){A(),n.destroy(),a.destroy(),l(null)}}}(n,i,a.pointerLens,l,(e=>{if(e){const t=e[0],i=e[1],s=e=>Math.min(t[e],i[e]),r=e=>Math.max(t[e],i[e]),o=s(0),n=s(1),a=s(2),l=r(0);r(1);const h=r(2);A.updateBase([[o,n,h],[l,n,h],[l,n,a],[o,n,a]])}else A.updateBase(null)}),(n=>{A.destroy();const l=function(e,t,i,s,r,o,n){const a=i=>Math.min(e[i],t[i]),l=i=>Math.max(e[i],t[i]),A=a(0),h=a(2),u=l(0),d=l(2);return n.createZone({id:c.createUUID(),geometry:{planeCoordinates:[[A,d],[u,d],[u,h],[A,h]],altitude:i,height:s},alpha:o,color:r})}(n[0],n[1],e,t,i,s,r);let h=!0;a._deactivate=()=>{h=!1},a.fire("zoneEnd",l),h&&o()})).deactivate;a._deactivate=()=>{h(),A.destroy()}}()}deactivate(){this._deactivate&&(this._deactivate(),this._deactivate=null)}destroy(){this.deactivate(),super.destroy()}}const kC=function(e,t,i,s,r,o,n,a,l){const A=o?function(e){o.visible=!!e,e&&(o.canvasPos=e)}:()=>{};let h;const u=[()=>A(null)],d=TC(e,s,r);return u.push((()=>d.destroy())),function o(p){const f=SC(e,s),g=p.length>0&&function(e,t,i){const s=e.canvas.canvas,r=new Ae(e,{});r.worldPos=i;const o=new Ae(e,{}),n=s.ownerDocument.body,a=new ge(n,{color:t,thickness:1,thicknessClickable:6});a.setVisible(!1);const l=function(){const e=r.canvasPos.slice(),t=o.canvasPos.slice();ce(s,n,e),ce(s,n,t),a.setStartAndEnd(e[0],e[1],t[0],t[1])},A=e.camera.on("viewMatrix",l),h=e.camera.on("projMatrix",l);return{update:function(e){e&&(o.worldPos=e,l()),a.setVisible(!!e)},destroy:function(){e.camera.off(A),e.camera.off(h),r.destroy(),o.destroy(),a.destroy()}}}(e,s,p[p.length-1].getWorldPos());u.push((()=>{f.destroy(),g&&g.destroy()}));const m=p.length>0&&p[0],_=function(e){const t=m&&m.getCanvasPos();return t&&c.distVec2(t,e)<10&&{canvasPos:t,worldPos:m.getWorldPos()}},v=function(){const e=(e,t,i)=>t[0]<=Math.max(e[0],i[0])&&t[0]>=Math.min(e[0],i[0])&&t[1]<=Math.max(e[1],i[1])&&t[1]>=Math.min(e[1],i[1]),t=(e,t,i)=>{const s=(t[1]-e[1])*(i[0]-t[0])-(t[0]-e[0])*(i[1]-t[1]);return 0===s?0:s>0?1:2};return function(i,s){const r=i[i.length-2],o=i[i.length-1];for(let n=s?1:0;n{A(null),f.update(null),g&&g.update(null),d.updateBase(p.length>2?p.map((e=>e.getWorldPos())):null)}),((e,t)=>{const i=p.length>2&&_(e);if(m&&m.setHighlighted(!!i),A(i?i.canvasPos:e),f.update(!i&&t),g&&g.update(i?i.worldPos:t),p.length>=2){const e=p.map((e=>e.getWorldPos())).concat(i?[]:[t]),s=v(e.map((e=>[e[0],e[2]])),i);d.updateBase(s?null:e)}else d.updateBase(null)}),(function(e,a){const A=p.length>2&&_(e),h=p.map((e=>e.getWorldPos())).concat(A?[]:[a]);d.updateBase(h);const m=h.map((e=>[e[0],e[2]]));p.length>2&&v(m,A)?(u.pop()(),o(p)):A?(f.update(a),u.forEach((e=>e())),l(n.createZone({id:c.createUUID(),geometry:{planeCoordinates:m,altitude:t,height:i},alpha:r,color:s}))):(f.update(a),g&&g.update(a),o(p.concat(f)))}))}([]),{closeSurface:function(){throw"TODO"},deactivate:function(){h(),u.forEach((e=>e()))}}};class NC extends D{constructor(e,t,i,s){const r=e.plugin.viewer,o=r.scene;super(o);const n=e._geometry.altitude,a=e._geometry.planeCoordinates.map((t=>{const i=o.canvas.canvas.ownerDocument.body,s=new ue(o,{},i,{fillColor:e._color});return s.worldPos=c.vec3([t[0],n,t[1]]),s.on("worldPos",(function(){t[0]=s.worldPos[0],t[1]=s.worldPos[2];try{e._rebuildMesh()}catch(t){e._zoneMesh&&(e._zoneMesh.destroy(),e._zoneMesh=null)}})),s})),l=pe({viewer:r,handleMouseEvents:i,handleTouchEvents:s,pointerLens:t&&t.pointerLens,dots:a,ray2WorldPos:(e,t)=>LC(n,c.vec3([0,1,0]),e,t),onEnd:(t,i)=>(e._zoneMesh&&this.fire("edited"),!!e._zoneMesh)}),A=function(){l(),a.forEach((e=>e.destroy()))},h=e.on("destroyed",A);this._deactivate=function(){e.off("destroyed",h),A()}}deactivate(){this._deactivate(),super.destroy()}}class QC extends D{constructor(e,t,i,s){const r=e.plugin.viewer,o=r.scene,n=o.canvas.canvas;super(o);const a=this,l=e._geometry.altitude,A=t&&t.pointerLens,h=A?function(e){A.visible=!!e,e&&(A.canvasPos=e)}:()=>{},u=e=>{const t=c.vec3(),i=c.vec3();return c.canvasPosToWorldRay(n,o.camera.viewMatrix,o.camera.projMatrix,o.camera.projection,e,t,i),s=t,r=i,LC(l,c.vec3([0,1,0]),s,r);var s,r},d=(e,t)=>(t[0]=e.clientX,t[1]=e.clientY,ce(n.ownerDocument.documentElement,n,t),t),p=function(e,t){const i=e=>{e.preventDefault(),t(e)};return n.addEventListener(e,i),()=>n.removeEventListener(e,i)};let f=()=>{};const g=function(t,i,s,o){const l=o(t),A=d(l,c.vec2()),g=r.scene.pick({canvasPos:A,includeEntities:[e._zoneMesh.id]});if((g&&g.entity&&g.entity.zone)===e){f(),n.style.cursor="move",r.cameraControl.active=!1;const t=function(){const t=e._geometry.planeCoordinates.map((e=>e.slice())),i=u(A),s=c.vec2([i[0],i[2]]),r=c.vec2();return function(i){const o=u(i);r[0]=o[0],r[1]=o[2],c.subVec2(s,r,r),e._geometry.planeCoordinates.forEach(((e,i)=>{c.subVec2(t[i],r,e)}));try{e._rebuildMesh()}catch(t){e._zoneMesh&&(e._zoneMesh.destroy(),e._zoneMesh=null)}}}(),l=p(i,(function(e){const i=o(e);if(i){const e=d(i,c.vec2());t(e),h(e)}})),g=p(s,(function(e){const i=o(e);if(i){const e=d(i,c.vec2());t(e),h(null),f(),a.fire("translated")}}));f=function(){f=()=>{},n.style.cursor="default",r.cameraControl.active=!0,l(),g()}}},m=[];i&&m.push(p("mousedown",(e=>{1===e.which&&g(e,"mousemove","mouseup",(e=>1===e.which&&e))}))),s&&m.push(p("touchstart",(e=>{if(1===e.touches.length){const t=e.touches[0].identifier;g(e,"touchmove","touchend",(e=>[...e.changedTouches].find((e=>e.identifier===t))))}})));const _=function(){f(),m.forEach((e=>e())),h(null)},v=e.on("destroyed",_);this._deactivate=function(){e.off("destroyed",v),_()}}deactivate(){this._deactivate(),super.destroy()}}exports.AlphaFormat=1021,exports.AmbientLight=St,exports.AngleMeasurementEditMouseControl=class extends Be{constructor(e,t){super(e,t,!0,!1)}},exports.AngleMeasurementEditTouchControl=class extends Be{constructor(e,t){super(e,t,!1,!0)}},exports.AngleMeasurementsControl=ye,exports.AngleMeasurementsMouseControl=xe,exports.AngleMeasurementsPlugin=class extends V{constructor(e,t={}){super("AngleMeasurements",e),this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.zIndex=t.zIndex||1e4,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,angleMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get control(){return this._defaultControl||(this._defaultControl=new xe(this,{})),this._defaultControl}get measurements(){return this._measurements}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,i=e.corner,s=e.target,r=new be(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},corner:{entity:i.entity,worldPos:i.worldPos},target:{entity:s.entity,worldPos:s.worldPos},visible:e.visible,originVisible:!0,originWireVisible:!0,cornerVisible:!0,targetWireVisible:!0,targetVisible:!0,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[r.id]=r,r.on("destroyed",(()=>{delete this._measurements[r.id]})),r.clickable=!0,this.fire("measurementCreated",r),r}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("AngleMeasurement not found: "+e)}setLabelsShown(e){for(const[t,i]of Object.entries(this.measurements))i.labelShown=e}clear(){const e=Object.keys(this._measurements);for(var t=0,i=e.length;t{this.plugin.viewer.cameraControl.active=!1},u=()=>{this.plugin.viewer.cameraControl.active=!0},d=()=>{o&&(clearTimeout(o),o=null),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),u(),this._touchState=0};i.addEventListener("touchstart",this._onCanvasTouchStart=i=>{const l=i.touches.length;if(1!==l)return void(o&&(clearTimeout(o),o=null));const u=i.touches[0],p=u.clientX,f=u.clientY;switch(n.set([p,f]),a.set([p,f]),this._touchState){case 0:if(1!==l&&null!==o)return void d();const i=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping});if(i&&i.snapped)s.set(i.worldPos),this.pointerCircle.start(i.snappedCanvasPos);else{const e=t.pick({canvasPos:a,pickSurface:!0});if(!e||!e.worldPos)return;s.set(e.worldPos),this.pointerCircle.start(e.canvasPos)}o=setTimeout((()=>{1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{if(o=null,1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{if(o=null,1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{this.pointerCircle.stop();const i=e.touches.length;if(1!==i||1!==e.changedTouches.length)return void(o&&(clearTimeout(o),o=null));const r=e.touches[0],n=r.clientX,l=r.clientY;if(r.identifier!==A)return;let h,c;switch(a.set([n,l]),this._touchState){case 2:this.pointerLens&&(this.pointerLens.canvasPos=a),h=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),h&&h.snapped?(this.pointerLens&&(this.pointerLens.snappedCanvasPos=h.snappedCanvasPos,this.pointerLens.snapped=!0),s.set(h.worldPos),this._currentAngleMeasurement.origin.worldPos=h.worldPos):(c=t.pick({canvasPos:a,pickSurface:!0}),c&&c.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=c.canvasPos,this.pointerLens.snapped=!1),s.set(c.worldPos),this._currentAngleMeasurement.origin.worldPos=c.worldPos):this.pointerLens&&(this.pointerLens.cursorPos=null,this.pointerLens.snapped=!1)),this._touchState=2;break;case 5:if(1!==i&&null!==o)return clearTimeout(o),o=null,this.pointerLens&&(this.pointerLens.visible=!1),void(this._touchState=7);this.pointerLens&&(this.pointerLens.canvasPos=a),h=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),h&&h.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=h.snappedCanvasPos,this.pointerLens.snapped=!0),this._currentAngleMeasurement.corner.worldPos=h.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1):(c=t.pick({canvasPos:a,pickSurface:!0}),c&&c.worldPos&&(this.pointerLens&&(this.pointerLens.cursorPos=c.canvasPos,this.pointerLens.snapped=!1),this._currentAngleMeasurement.corner.worldPos=c.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1)),this._touchState=5;break;case 8:if(1!==i&&null!==o)return clearTimeout(o),o=null,this.pointerLens&&(this.pointerLens.visible=!1),void(this._touchState=7);this.pointerLens&&(this.pointerLens.canvasPos=a),h=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),h&&h.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=h.snappedCanvasPos,this.pointerLens.snapped=!0),this._currentAngleMeasurement.target.worldPos=h.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.angleVisible=!0):(c=t.pick({canvasPos:a,pickSurface:!0}),c&&c.worldPos&&(this.pointerLens&&(this.pointerLens.cursorPos=c.canvasPos,this.pointerLens.snapped=!1),this._currentAngleMeasurement.target.worldPos=c.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.angleVisible=!0)),this._touchState=8}}),{passive:!0}),i.addEventListener("touchend",this._onCanvasTouchEnd=i=>{this.pointerCircle.stop();const s=i.changedTouches.length;if(1!==s)return;const h=i.changedTouches[0],d=h.clientX,p=h.clientY;if(h.identifier===A)switch(o&&(clearTimeout(o),o=null),l.set([d,p]),this._touchState){case 1:{if(1!==s||d>n[0]+r||dn[1]+r||pn[0]+r||dn[1]+r||pn[0]+r||dn[1]+r||p",this._markerHTML=t.markerHTML||"
",this._container=t.container||document.body,this._values=t.values||{},this.annotations={},this.surfaceOffset=t.surfaceOffset}getContainerElement(){return this._container}send(e,t){if("clearAnnotations"===e)this.clear()}set surfaceOffset(e){null==e&&(e=.3),this._surfaceOffset=e}get surfaceOffset(){return this._surfaceOffset}createAnnotation(e){this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id);var t=null;e.markerElementId&&((t=document.getElementById(e.markerElementId))||this.error("Can't find DOM element for 'markerElementId' value '"+e.markerElementId+"' - defaulting to internally-generated empty DIV"));var i=null;e.labelElementId&&((i=document.getElementById(e.labelElementId))||this.error("Can't find DOM element for 'labelElementId' value '"+e.labelElementId+"' - defaulting to internally-generated empty DIV"));const s=new Me(this.viewer.scene,{id:e.id,plugin:this,container:this._container,markerElement:t,labelElement:i,markerHTML:e.markerHTML||this._markerHTML,labelHTML:e.labelHTML||this._labelHTML,occludable:e.occludable,values:_.apply(e.values,_.apply(this._values,{})),markerShown:e.markerShown,labelShown:e.labelShown,eye:e.eye,look:e.look,up:e.up,projection:e.projection,visible:!1!==e.visible});return e.pickResult=e.pickResult||e.pickRecord,e.pickResult?s.setFromPickResult(e.pickResult):(s.entity=e.entity,s.worldPos=e.worldPos),this.annotations[s.id]=s,s.on("destroyed",(()=>{delete this.annotations[s.id],this.fire("annotationDestroyed",s.id)})),this.fire("annotationCreated",s.id),s}destroyAnnotation(e){var t=this.annotations[e];t?t.destroy():this.log("Annotation not found: "+e)}clear(){const e=Object.keys(this.annotations);for(var t=0,i=e.length;tp.has(e.id)||g.has(e.id)||f.has(e.id))).reduce(((e,i)=>{let s,r=function(e){let t="";return t+=Math.round(255*e[0]).toString(16).padStart(2,"0"),t+=Math.round(255*e[1]).toString(16).padStart(2,"0"),t+=Math.round(255*e[2]).toString(16).padStart(2,"0"),t}(i.colorize);i.xrayed?(s=0===t.xrayMaterial.fillAlpha&&0!==t.xrayMaterial.edgeAlpha?.1:t.xrayMaterial.fillAlpha,s=Math.round(255*s).toString(16).padStart(2,"0"),r=s+r):p.has(i.id)&&(s=Math.round(255*i.opacity).toString(16).padStart(2,"0"),r=s+r),e[r]||(e[r]=[]);const o=i.id,n=i.originalSystemId,a={ifc_guid:n,originating_system:this.originatingSystem};return n!==o&&(a.authoring_tool_id=o),e[r].push(a),e}),{}),_=Object.entries(m).map((([e,t])=>({color:e,components:t})));o.components.coloring=_;const v=t.objectIds,b=t.visibleObjects,y=t.visibleObjectIds,x=v.filter((e=>!b[e])),B=t.selectedObjectIds;return e.defaultInvisible||y.length0&&e.clipping_planes.forEach((function(e){let t=yh(e.location,gh),i=yh(e.direction,gh);A&&c.negateVec3(i),c.subVec3(t,l),r.yUp&&(t=Bh(t),i=Bh(i)),new ns(s,{pos:t,dir:i})})),s.clearLines(),e.lines&&e.lines.length>0){const t=[],i=[];let r=0;e.lines.forEach((e=>{e.start_point&&e.end_point&&(t.push(e.start_point.x),t.push(e.start_point.y),t.push(e.start_point.z),t.push(e.end_point.x),t.push(e.end_point.y),t.push(e.end_point.z),i.push(r++),i.push(r++))})),new fh(s,{positions:t,indices:i,clippable:!1,collidable:!0})}if(s.clearBitmaps(),e.bitmaps&&e.bitmaps.length>0&&e.bitmaps.forEach((function(e){const t=e.bitmap_type||"jpg",i=e.bitmap_data;let o=yh(e.location,mh),n=yh(e.normal,_h),a=yh(e.up,vh),l=e.height||1;t&&i&&o&&n&&a&&(r.yUp&&(o=Bh(o),n=Bh(n),a=Bh(a)),new Hs(s,{src:i,type:t,pos:o,normal:n,up:a,clippable:!1,collidable:!0,height:l}))})),a&&(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=>this._withBCFComponent(t,e,(e=>e.visible=!1))))):(s.setObjectsVisible(s.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!0)))));const r=e.components.visibility.view_setup_hints;r&&(!1===r.spaces_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcSpace"),!1),void 0!==r.spaces_translucent&&s.setObjectsXRayed(i.metaScene.getObjectIDsByType("IfcSpace"),!0),r.space_boundaries_visible,!1===r.openings_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcOpening"),!0),r.space_boundaries_translucent,void 0!==r.openings_translucent&&s.setObjectsXRayed(i.metaScene.getObjectIDsByType("IfcOpening"),!0))}e.components.selection&&(s.setObjectsSelected(s.selectedObjectIds,!1),e.components.selection.forEach((e=>this._withBCFComponent(t,e,(e=>e.selected=!0))))),e.components.translucency&&(s.setObjectsXRayed(s.xrayedObjectIds,!1),e.components.translucency.forEach((e=>this._withBCFComponent(t,e,(e=>e.xrayed=!0))))),e.components.coloring&&e.components.coloring.forEach((e=>{let i=e.color,s=0,r=!1;8===i.length&&(s=parseInt(i.substring(0,2),16)/256,s<=1&&s>=.95&&(s=1),i=i.substring(2),r=!0);const o=[parseInt(i.substring(0,2),16)/256,parseInt(i.substring(2,4),16)/256,parseInt(i.substring(4,6),16)/256];e.components.map((e=>this._withBCFComponent(t,e,(e=>{e.colorize=o,r&&(e.opacity=s)}))))}))}if(e.perspective_camera||e.orthogonal_camera){let a,A,h,u;if(e.perspective_camera?(a=yh(e.perspective_camera.camera_view_point,gh),A=yh(e.perspective_camera.camera_direction,gh),h=yh(e.perspective_camera.camera_up_vector,gh),r.perspective.fov=e.perspective_camera.field_of_view,u="perspective"):(a=yh(e.orthogonal_camera.camera_view_point,gh),A=yh(e.orthogonal_camera.camera_direction,gh),h=yh(e.orthogonal_camera.camera_up_vector,gh),r.ortho.scale=e.orthogonal_camera.view_to_world_scale,u="ortho"),c.subVec3(a,l),r.yUp&&(a=Bh(a),A=Bh(A),h=Bh(h)),o){const e=s.pick({pickSurface:!0,origin:a,direction:A});A=e?e.worldPos:c.addVec3(a,A,gh)}else A=c.addVec3(a,A,gh);n?(r.eye=a,r.look=A,r.up=h,r.projection=u):i.cameraFlight.flyTo({eye:a,look:A,up:h,duration:t.duration,projection:u})}}_withBCFComponent(e,t,i){const s=this.viewer,r=s.scene;if(t.authoring_tool_id&&t.originating_system===this.originatingSystem){const o=t.authoring_tool_id,n=r.objects[o];if(n)return void i(n);if(e.updateCompositeObjects){if(s.metaScene.metaObjects[o])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(o),i)}}if(t.ifc_guid){const o=t.ifc_guid,n=r.objects[o];if(n)return void i(n);if(e.updateCompositeObjects){if(s.metaScene.metaObjects[o])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(o),i)}Object.keys(r.models).forEach((t=>{const n=c.globalizeObjectId(t,o),a=r.objects[n];if(a)i(a);else if(e.updateCompositeObjects){s.metaScene.metaObjects[n]&&r.withObjects(s.metaScene.getObjectIDsInSubtree(n),i)}}))}}destroy(){super.destroy()}},exports.Bitmap=Hs,exports.ByteType=1010,exports.CameraMemento=$h,exports.CameraPath=class extends D{get type(){return"CameraPath"}constructor(e,t={}){super(e,t),this._frames=[],this._eyeCurve=new Uh(this),this._lookCurve=new Uh(this),this._upCurve=new Uh(this),t.frames&&(this.addFrames(t.frames),this.smoothFrameTimes(1))}get frames(){return this._frames}get eyeCurve(){return this._eyeCurve}get lookCurve(){return this._lookCurve}get upCurve(){return this._upCurve}saveFrame(e){const t=this.scene.camera;this.addFrame(e,t.eye,t.look,t.up)}addFrame(e,t,i,s){const r={t:e,eye:t.slice(0),look:i.slice(0),up:s.slice(0)};this._frames.push(r),this._eyeCurve.points.push(r.eye),this._lookCurve.points.push(r.look),this._upCurve.points.push(r.up)}addFrames(e){let t;for(let i=0,s=e.length;i1?1:e,t.eye=this._eyeCurve.getPoint(e,Oh),t.look=this._lookCurve.getPoint(e,Oh),t.up=this._upCurve.getPoint(e,Oh)}sampleFrame(e,t,i,s){e=e<0?0:e>1?1:e,this._eyeCurve.getPoint(e,t),this._lookCurve.getPoint(e,i),this._upCurve.getPoint(e,s)}smoothFrameTimes(e){if(0===this._frames.length)return;const t=c.vec3();var i=0;this._frames[0].t=0;const s=[];for(let e=1,o=this._frames.length;e{this._parseModel(e,t,i,s),r.processes--}),(e=>{r.processes--,this.error(e),s.fire("error",e)}))}_parseModel(e,t,i,s){if(s.destroyed)return;const r=e.transform?this._transformVertices(e.vertices,e.transform,i.rotateX):e.vertices,o=t.stats||{};o.sourceFormat=e.type||"CityJSON",o.schemaVersion=e.version||"",o.title="",o.author="",o.created="",o.numMetaObjects=0,o.numPropertySets=0,o.numObjects=0,o.numGeometries=0,o.numTriangles=0,o.numVertices=0;const n=!1!==t.loadMetadata,a=n?{id:c.createUUID(),name:"Model",type:"Model"}:null,l=n?{id:"",projectId:"",author:"",createdAt:"",schema:e.version||"",creatingApplication:"",metaObjects:[a],propertySets:[]}:null,A={data:e,vertices:r,sceneModel:s,loadMetadata:n,metadata:l,rootMetaObject:a,nextId:0,stats:o};if(this._parseCityJSON(A),s.finalize(),n){const e=s.id;this.viewer.metaScene.createMetaModel(e,A.metadata,i)}s.scene.once("tick",(()=>{s.destroyed||(s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1))}))}_transformVertices(e,t,i){const s=[],r=t.scale||c.vec3([1,1,1]),o=t.translate||c.vec3([0,0,0]);for(let t=0,n=0;t0))return;const o=[];for(let i=0,s=t.geometry.length;i0){const r=t[s[0]];if(void 0!==r.value)n=e[r.value];else{const t=r.values;if(t){a=[];for(let s=0,r=t.length;s0&&(s.createEntity({id:i,meshIds:o,isObject:!0}),e.stats.numObjects++)}_parseGeometrySurfacesWithOwnMaterials(e,t,i,s){switch(t.type){case"MultiPoint":case"MultiLineString":break;case"MultiSurface":case"CompositeSurface":const r=t.boundaries;this._parseSurfacesWithOwnMaterials(e,i,r,s);break;case"Solid":const o=t.boundaries;for(let t=0;t0&&h.push(A.length);const i=this._extractLocalIndices(e,a[t],u,d);A.push(...i)}if(3===A.length)d.indices.push(A[0]),d.indices.push(A[1]),d.indices.push(A[2]);else if(A.length>3){const e=[];for(let t=0;t0&&n.indices.length>0){const t=""+e.nextId++;r.createMesh({id:t,primitive:"triangles",positions:n.positions,indices:n.indices,color:i&&i.diffuseColor?i.diffuseColor:[.8,.8,.8],opacity:1}),s.push(t),e.stats.numGeometries++,e.stats.numVertices+=n.positions.length/3,e.stats.numTriangles+=n.indices.length/3}}_parseSurfacesWithSharedMaterial(e,t,i,s){const r=e.vertices;for(let o=0;o0&&a.push(n.length);const l=this._extractLocalIndices(e,t[o][r],i,s);n.push(...l)}if(3===n.length)s.indices.push(n[0]),s.indices.push(n[1]),s.indices.push(n[2]);else if(n.length>3){let e=[];for(let t=0;t{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),document.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),e.items&&(this.items=e.items),this._hideOnAction=!1!==e.hideOnAction,this.context=e.context,this.enabled=!1!==e.enabled,this.hide()}on(e,t){let 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{const o=this._getNextId(),n=new i(o);for(let i=0,o=e.length;i0,A=this._getNextId(),h=i.getTitle||(()=>i.title||""),c=i.doAction||i.callback||(()=>{}),u=i.getEnabled||(()=>!0),d=i.getShown||(()=>!0),p=new r(A,h,c,u,d);if(p.parentMenu=n,a.items.push(p),l){const e=t(s);p.subMenu=e,e.parentItem=p}this._itemList.push(p),this._itemMap[p.id]=p}}return this._menuList.push(n),this._menuMap[n.id]=n,n};this._rootMenu=t(e)}_getNextId(){return"ContextMenu_"+this._id+"_"+this._nextId++}_createUI(){const e=t=>{this._createMenuUI(t);const i=t.groups;for(let t=0,s=i.length;t'),i.push("
    "),t)for(let e=0,s=t.length;e'+l+""),r===o-1||e')):(i.push('
  • '+l+"
  • "),r===o-1||e'))}}i.push("
"),i.push("");const s=i.join("");document.body.insertAdjacentHTML("beforeend",s);const r=document.querySelector("."+e.id);e.menuElement=r,r.style["border-radius"]="4px",r.style.display="none",r.style["z-index"]=3e5,r.style.background="white",r.style.border="1px solid black",r.style["box-shadow"]="0 4px 5px 0 gray",r.oncontextmenu=e=>{e.preventDefault()};const o=this;let n=null;if(t)for(let e=0,i=t.length;e{e.preventDefault();const i=t.subMenu;if(!i)return void(n&&(o._hideMenu(n.id),n=null));if(n&&n.id!==i.id&&(o._hideMenu(n.id),n=null),!1===t.enabled)return;const s=t.itemElement,r=i.menuElement,a=s.getBoundingClientRect();r.getBoundingClientRect();a.right+200>window.innerWidth?o._showMenu(i.id,a.left-200,a.top-1):o._showMenu(i.id,a.right-5,a.top-1),n=i})),s||(t.itemElement.addEventListener("click",(e=>{e.preventDefault(),o._context&&!1!==t.enabled&&(t.doAction&&t.doAction(o._context),this._hideOnAction?o.hide():(o._updateItemsTitles(),o._updateItemsEnabledStatus()))})),t.itemElement.addEventListener("mouseup",(e=>{3===e.which&&(e.preventDefault(),o._context&&!1!==t.enabled&&(t.doAction&&t.doAction(o._context),this._hideOnAction?o.hide():(o._updateItemsTitles(),o._updateItemsEnabledStatus())))})),t.itemElement.addEventListener("mouseenter",(e=>{e.preventDefault(),!1!==t.enabled&&t.doHover&&t.doHover(o._context)})))):console.error("ContextMenu item element not found: "+t.id)}}}_updateItemsTitles(){if(this._context)for(let e=0,t=this._itemList.length;e{n.subMenu&&(e=n.itemElement,t=e.getBoundingClientRect(),i=n.subMenu.menuElement,s={visibility:i.style.visibility,display:i.style.display},i.style.display="block",i.style.visibility="hidden",o=n.subMenu.menuElement.getBoundingClientRect().width,i.style.visibility=s.visibility,i.style.display=s.display,r=t.right+o>window.innerWidth,e.setAttribute("data-submenuposition",r?"left":"right"))}))}_showMenu(e,t,i){const s=this._menuMap[e];if(!s)return void console.error("Menu not found: "+e);if(s.shown)return;const r=s.menuElement;r&&(this._showMenuElement(r,t,i),s.shown=!0)}_hideMenu(e){const t=this._menuMap[e];if(!t)return void console.error("Menu not found: "+e);if(!t.shown)return;const i=t.menuElement;i&&(this._hideMenuElement(i),t.shown=!1)}_hideAllMenus(){for(let e=0,t=this._menuList.length;ewindow.innerHeight&&(i=window.innerHeight-s),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=i+"px"}_hideMenuElement(e){e.style.display="none"}},exports.CubicBezierCurve=class extends Lh{constructor(e,t={}){super(e,t),this.v0=t.v0,this.v1=t.v1,this.v2=t.v2,this.v3=t.v3,this.t=t.t}set v0(e){this._v0=e||c.vec3([0,0,0])}get v0(){return this._v0}set v1(e){this._v1=e||c.vec3([0,0,0])}get v1(){return this._v1}set v2(e){this._v2=e||c.vec3([0,0,0])}get v2(){return this._v2}set v3(e){this.fire("v3",this._v3=e||c.vec3([0,0,0]))}get v3(){return this._v3}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=c.vec3();return t[0]=c.b3(e,this._v0[0],this._v1[0],this._v2[0],this._v3[0]),t[1]=c.b3(e,this._v0[1],this._v1[1],this._v2[1],this._v3[1]),t[2]=c.b3(e,this._v0[2],this._v1[2],this._v2[2],this._v3[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,v3:this._v3,t:this._t}}},exports.Curve=Lh,exports.DefaultLoadingManager=TA,exports.DepthFormat=1026,exports.DepthStencilFormat=1027,exports.DirLight=Dt,exports.DistanceMeasurementEditControl=Ih,exports.DistanceMeasurementEditMouseControl=class extends Ih{constructor(e,t){super(e,t,!0,!1)}},exports.DistanceMeasurementEditTouchControl=class extends Ih{constructor(e,t){super(e,t,!1,!0)}},exports.DistanceMeasurementsControl=Eh,exports.DistanceMeasurementsMouseControl=Fh,exports.DistanceMeasurementsPlugin=class extends V{constructor(e,t={}){super("DistanceMeasurements",e),this._pointerLens=t.pointerLens,this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.labelMinAxisLength=t.labelMinAxisLength,this.defaultVisible=!1!==t.defaultVisible,this.defaultOriginVisible=!1!==t.defaultOriginVisible,this.defaultTargetVisible=!1!==t.defaultTargetVisible,this.defaultWireVisible=!1!==t.defaultWireVisible,this.defaultXLabelEnabled=!1!==t.defaultXLabelEnabled,this.defaultYLabelEnabled=!1!==t.defaultYLabelEnabled,this.defaultZLabelEnabled=!1!==t.defaultZLabelEnabled,this.defaultLengthLabelEnabled=!1!==t.defaultLengthLabelEnabled,this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.defaultAxisVisible=!1!==t.defaultAxisVisible,this.defaultXAxisVisible=!1!==t.defaultXAxisVisible,this.defaultYAxisVisible=!1!==t.defaultYAxisVisible,this.defaultZAxisVisible=!1!==t.defaultZAxisVisible,this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.zIndex=t.zIndex||1e4,this.defaultLabelsOnWires=!1!==t.defaultLabelsOnWires,this.useRotationAdjustment=void 0!==t.useRotationAdjustment&&!1!==t.useRotationAdjustment,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,distanceMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get pointerLens(){return this._pointerLens}get control(){return this._defaultControl||(this._defaultControl=new Fh(this,{})),this._defaultControl}get measurements(){return this._measurements}set labelMinAxisLength(e){e<1&&(this.error("labelMinAxisLength must be >= 1; defaulting to 25"),e=25),this._labelMinAxisLength=e||25}get labelMinAxisLength(){return this._labelMinAxisLength}set useRotationAdjustment(e){e=void 0!==e&&Boolean(e),this._useRotationAdjustment=e}get useRotationAdjustment(){return this._useRotationAdjustment}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,i=e.target,s=new Mh(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},target:{entity:i.entity,worldPos:i.worldPos},visible:e.visible,wireVisible:e.wireVisible,axisVisible:!1!==e.axisVisible&&!1!==this.defaultAxisVisible,xAxisVisible:!1!==e.xAxisVisible&&!1!==this.defaultXAxisVisible,yAxisVisible:!1!==e.yAxisVisible&&!1!==this.defaultYAxisVisible,zAxisVisible:!1!==e.zAxisVisible&&!1!==this.defaultZAxisVisible,xLabelEnabled:!1!==e.xLabelEnabled&&!1!==this.defaultXLabelEnabled,yLabelEnabled:!1!==e.yLabelEnabled&&!1!==this.defaultYLabelEnabled,zLabelEnabled:!1!==e.zLabelEnabled&&!1!==this.defaultZLabelEnabled,lengthLabelEnabled:!1!==e.lengthLabelEnabled&&!1!==this.defaultLengthLabelEnabled,labelsVisible:!1!==e.labelsVisible&&!1!==this.defaultLabelsVisible,useRotationAdjustment:this.useRotationAdjustment,originVisible:e.originVisible,targetVisible:e.targetVisible,color:e.color,labelsOnWires:!1!==e.labelsOnWires&&!1!==this.defaultLabelsOnWires,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[s.id]=s,s.clickable=!0,s.on("destroyed",(()=>{delete this._measurements[s.id]})),this.fire("measurementCreated",s),s}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("DistanceMeasurement not found: "+e)}setLabelsShown(e){for(const[t,i]of Object.entries(this.measurements))i.labelShown=e}setAxisVisible(e){for(const[t,i]of Object.entries(this.measurements))i.axisVisible=e;this.defaultAxisVisible=e}getAxisVisible(){return this.defaultAxisVisible}clear(){const e=Object.keys(this._measurements);for(var t=0,i=e.length;t{this.plugin.viewer.cameraControl.active=!1},u=()=>{this.plugin.viewer.cameraControl.active=!0},d=()=>{o&&(clearTimeout(o),o=null),this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),u(),this._touchState=0};i.addEventListener("touchstart",this._onCanvasTouchStart=l=>{const u=l.touches.length;if(1!==u)return void(o&&(clearTimeout(o),o=null));const p=l.touches[0],f=i.getBoundingClientRect(),g=p.clientX-f.left,m=p.clientY-f.top;switch(n.set([g,m]),a.set([g,m]),this._touchState){case 0:if(1!==u&&null!==o)return void d();const i=t.pick({canvasPos:a,snapping:this._snapping,snapToEdge:this._snapping});if(i&&i.snapped)s.set(i.worldPos),this.pointerCircle.start(i.snappedCanvasPos);else{const e=t.pick({canvasPos:a,pickSurface:!0});if(!e||!e.worldPos)return;s.set(e.worldPos),this.pointerCircle.start(e.canvasPos)}o=setTimeout((()=>{1!==u||a[0]>n[0]+r||a[0]n[1]+r||a[1]{if(o=null,1!==u||a[0]>n[0]+r||a[0]n[1]+r||a[1]{this.pointerCircle.stop();const n=r.touches.length;if(1!==n||1!==r.changedTouches.length)return void(o&&(clearTimeout(o),o=null));const l=r.touches[0],h=i.getBoundingClientRect(),u=l.clientX-h.left,d=l.clientY-h.top;if(l.identifier!==A)return;let p,f;switch(a.set([u,d]),this._touchState){case 2:this.pointerLens&&(this.pointerLens.canvasPos=a),p=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),p&&p.snapped?(this.pointerLens&&(this.pointerLens.snappedCanvasPos=p.snappedCanvasPos,this.pointerLens.snapped=!0),s.set(p.worldPos),this._currentDistanceMeasurement?this._currentDistanceMeasurement.origin.worldPos=p.worldPos:(this._currentDistanceMeasurement=e.createMeasurement({id:c.createUUID(),origin:{worldPos:p.worldPos,entity:p.entity},target:{worldPos:p.worldPos,entity:p.entity}}),this._currentDistanceMeasurement.labelsVisible=!1,this._currentDistanceMeasurement.xAxisVisible=!1,this._currentDistanceMeasurement.yAxisVisible=!1,this._currentDistanceMeasurement.zAxisVisible=!1,this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.originVisible=!0,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.clickable=!1),this.distanceMeasurementsPlugin.fire("measurementStart",this._currentDistanceMeasurement)):(f=t.pick({canvasPos:a,pickSurface:!0}),f&&f.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=f.canvasPos,this.pointerLens.snapped=!1),s.set(f.worldPos),this._currentDistanceMeasurement?this._currentDistanceMeasurement.origin.worldPos=f.worldPos:(this._currentDistanceMeasurement=e.createMeasurement({id:c.createUUID(),origin:{worldPos:f.worldPos,entity:f.entity},target:{worldPos:f.worldPos,entity:f.entity}}),this._currentDistanceMeasurement.labelsVisible=!1,this._currentDistanceMeasurement.xAxisVisible=!1,this._currentDistanceMeasurement.yAxisVisible=!1,this._currentDistanceMeasurement.zAxisVisible=!1,this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.originVisible=!0,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.clickable=!1),this.distanceMeasurementsPlugin.fire("measurementStart",this._currentDistanceMeasurement)):this.pointerLens&&(this.pointerLens.cursorPos=null,this.pointerLens.snapped=!1)),this._touchState=2;break;case 5:if(1!==n&&null!==o)return clearTimeout(o),o=null,this.pointerLens&&(this.pointerLens.visible=!1),void(this._touchState=7);this.pointerLens&&(this.pointerLens.canvasPos=a),p=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),p&&p.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=p.snappedCanvasPos,this.pointerLens.snapped=!0),this._currentDistanceMeasurement.target.worldPos=p.worldPos,this._currentDistanceMeasurement.target.entity=p.entity,this._currentDistanceMeasurement.targetVisible=!0,this._currentDistanceMeasurement.wireVisible=!0,this._currentDistanceMeasurement.labelsVisible=!0):(f=t.pick({canvasPos:a,pickSurface:!0}),f&&f.worldPos&&(this.pointerLens&&(this.pointerLens.cursorPos=f.canvasPos,this.pointerLens.snapped=!1),this._currentDistanceMeasurement.target.worldPos=f.worldPos,this._currentDistanceMeasurement.target.entity=f.entity,this._currentDistanceMeasurement.targetVisible=!0,this._currentDistanceMeasurement.wireVisible=!0,this._currentDistanceMeasurement.labelsVisible=!0)),this._touchState=5}}),{passive:!0}),i.addEventListener("touchend",this._onCanvasTouchEnd=s=>{this.pointerCircle.stop();const h=s.changedTouches.length;if(1!==h)return;const d=s.changedTouches[0],p=i.getBoundingClientRect(),f=d.clientX-p.left,g=d.clientY-p.top;if(d.identifier===A)switch(o&&(clearTimeout(o),o=null),l.set([f,g]),this._touchState){case 1:{if(1!==h||f>n[0]+r||fn[1]+r||gn[0]+r||fn[1]+r||g{const t=e.fileData,n=e.sceneModel,a={},l=c.createUUID(),A=c.createUUID(),h=c.createUUID(),u=c.createUUID(),d={metaObjects:[{id:l,name:"Project",type:"Project",parent:null},{id:A,name:"Site",type:"Site",parent:l},{id:h,name:"Building",type:"Building",parent:A},{id:u,name:"BuildingStorey",type:"BuildingStorey",parent:h}],propertySets:[]},p=(e,i)=>{if(a[e])return;const s=t.meshes.find((e=>e.mesh_id===i.mesh_id));n.createGeometry({id:e,primitive:"triangles",positions:s.coordinates,indices:s.indices}),a[e]=!0},f=t.elements;for(let e=0,i=f.length;ee.mesh_id===i.mesh_id));for(let t=0,i=e.length;t{n.destroyed||(n.scene.fire("modelLoaded",n.id),n.fire("loaded",!0,!1))}))};if(e.src){const i=e.src;this.viewer.scene.canvas.spinner.processes++,this._dataSource.getDotBIM(i,(e=>{n({fileData:e,sceneModel:t,nextId:0,error:function(e){}}),this.viewer.scene.canvas.spinner.processes--}),(e=>{this.viewer.scene.canvas.spinner.processes--,this.error(e)}))}else if(e.dotBIM){const i={fileData:e.dotBIM,sceneModel:t,nextId:0,error:function(e){}};n(i)}return t.once("destroyed",(()=>{this.viewer.metaScene.destroyMetaModel(i)})),t}destroy(){super.destroy()}},exports.EdgeMaterial=$t,exports.EmphasisMaterial=Zt,exports.FaceAlignedSectionPlanesPlugin=class extends V{constructor(e,t={}){if(super("FaceAlignedSectionPlanesPlugin",e),this._freeControls=[],this._sectionPlanes=e.scene.sectionPlanes,this._controls={},this._shownControlId=null,this._dragSensitivity=t.dragSensitivity||1,null!==t.overviewCanvasId&&void 0!==t.overviewCanvasId){const e=document.getElementById(t.overviewCanvasId);e?this._overview=new vw(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;bw.set(this.viewer.scene.aabb),c.getAABB3Center(bw,yw),bw[0]+=t[0]-yw[0],bw[1]+=t[1]-yw[1],bw[2]+=t[2]-yw[2],bw[3]+=t[0]-yw[0],bw[4]+=t[1]-yw[1],bw[5]+=t[2]-yw[2],this.viewer.cameraFlight.flyTo({aabb:bw,fitFOV:65})},onClickedNothing:()=>{this.hideControl()}}):this.warn("Can't find overview canvas: '"+t.overviewCanvasId+"' - will create plugin without overview")}null===t.controlElementId||void 0===t.controlElementId?this.error("Parameter expected: controlElementId"):(this._controlElement=document.getElementById(t.controlElementId),this._controlElement||this.warn("Can't find control element: '"+t.controlElementId+"' - will create plugin without control element")),this._onSceneSectionPlaneCreated=e.scene.on("sectionPlaneCreated",(e=>{this._sectionPlaneCreated(e)}))}setDragSensitivity(e){this._dragSensitivity=e||1}getDragSensitivity(){return this._dragSensitivity}setOverviewVisible(e){this._overview&&this._overview.setVisible(e)}getOverviewVisible(){if(this._overview)return this._overview.getVisible()}get sectionPlanes(){return this._sectionPlanes}createSectionPlane(e={}){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);return new ns(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 mw(this);t._setSectionPlane(e),t.setVisible(!1),this._controls[e.id]=t,this._overview&&this._overview.addSectionPlane(e),e.once("destroyed",(()=>{this._sectionPlaneDestroyed(e)}))}flipSectionPlanes(){const e=this.viewer.scene.sectionPlanes;for(let t in e){e[t].flipDir()}}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(let 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){let 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(let t=0,i=e.length;t{i=1e3*this._delayBeforeRestoreSeconds,s||(e.scene._renderer.setColorTextureEnabled(!this._hideColorTexture),e.scene._renderer.setPBREnabled(!this._hidePBR),e.scene._renderer.setSAOEnabled(!this._hideSAO),e.scene._renderer.setTransparentEnabled(!this._hideTransparentObjects),e.scene._renderer.setEdgesEnabled(!this._hideEdges),this._scaleCanvasResolution?e.scene.canvas.resolutionScale=this._scaleCanvasResolutionFactor:e.scene.canvas.resolutionScale=this._defaultScaleCanvasResolutionFactor,s=!0)},o=()=>{e.scene.canvas.resolutionScale=this._defaultScaleCanvasResolutionFactor,e.scene._renderer.setEdgesEnabled(!0),e.scene._renderer.setColorTextureEnabled(!0),e.scene._renderer.setPBREnabled(!0),e.scene._renderer.setSAOEnabled(!0),e.scene._renderer.setTransparentEnabled(!0),s=!1};this._onCanvasBoundary=e.scene.canvas.on("boundary",r),this._onCameraMatrix=e.scene.camera.on("matrix",r),this._onSceneTick=e.scene.on("tick",(e=>{s&&(i-=e.deltaTime,(!this._delayBeforeRestore||i<=0)&&o())}));let n=!1;this._onSceneMouseDown=e.scene.input.on("mousedown",(()=>{n=!0})),this._onSceneMouseUp=e.scene.input.on("mouseup",(()=>{n=!1})),this._onSceneMouseMove=e.scene.input.on("mousemove",(()=>{n&&r()}))}get hideColorTexture(){return this._hideColorTexture}set hideColorTexture(e){this._hideColorTexture=e}get hidePBR(){return this._hidePBR}set hidePBR(e){this._hidePBR=e}get hideSAO(){return this._hideSAO}set hideSAO(e){this._hideSAO=e}get hideEdges(){return this._hideEdges}set hideEdges(e){this._hideEdges=e}get hideTransparentObjects(){return this._hideTransparentObjects}set hideTransparentObjects(e){this._hideTransparentObjects=!1!==e}get scaleCanvasResolution(){return this._scaleCanvasResolution}set scaleCanvasResolution(e){this._scaleCanvasResolution=e}get defaultScaleCanvasResolutionFactor(){return this._defaultScaleCanvasResolutionFactor}set defaultScaleCanvasResolutionFactor(e){this._defaultScaleCanvasResolutionFactor=e||1}get scaleCanvasResolutionFactor(){return this._scaleCanvasResolutionFactor}set scaleCanvasResolutionFactor(e){this._scaleCanvasResolutionFactor=e||.6}get delayBeforeRestore(){return this._delayBeforeRestore}set delayBeforeRestore(e){this._delayBeforeRestore=e}get delayBeforeRestoreSeconds(){return this._delayBeforeRestoreSeconds}set delayBeforeRestoreSeconds(e){this._delayBeforeRestoreSeconds=null!=e?e:.5}send(e,t){}destroy(){this.viewer.scene.camera.off(this._onCameraMatrix),this.viewer.scene.canvas.off(this._onCanvasBoundary),this.viewer.scene.input.off(this._onSceneMouseDown),this.viewer.scene.input.off(this._onSceneMouseUp),this.viewer.scene.input.off(this._onSceneMouseMove),this.viewer.scene.off(this._onSceneTick),super.destroy()}},exports.FloatType=1015,exports.Fresnel=class extends D{get type(){return"Fresnel"}constructor(e,t={}){super(e,t),this._state=new lt({edgeColor:c.vec3([0,0,0]),centerColor:c.vec3([1,1,1]),edgeBias:0,centerBias:1,power:1}),this.edgeColor=t.edgeColor,this.centerColor=t.centerColor,this.edgeBias=t.edgeBias,this.centerBias=t.centerBias,this.power=t.power}set edgeColor(e){this._state.edgeColor.set(e||[0,0,0]),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set centerColor(e){this._state.centerColor.set(e||[1,1,1]),this.glRedraw()}get centerColor(){return this._state.centerColor}set edgeBias(e){this._state.edgeBias=e||0,this.glRedraw()}get edgeBias(){return this._state.edgeBias}set centerBias(e){this._state.centerBias=null!=e?e:1,this.glRedraw()}get centerBias(){return this._state.centerBias}set power(e){this._state.power=null!=e?e:1,this.glRedraw()}get power(){return this._state.power}destroy(){super.destroy(),this._state.destroy()}},exports.Frustum=U,exports.FrustumPlane=L,exports.GIFMediaType=1e4,exports.GLTFDefaultDataSource=Dh,exports.GLTFLoaderPlugin=class extends V{constructor(e,t={}){super("GLTFLoader",e,t),this._sceneModelLoader=new QB(this,t),this.dataSource=t.dataSource,this.objectDefaults=t.objectDefaults}set dataSource(e){this._dataSource=e||new Dh}get dataSource(){return this._dataSource}set objectDefaults(e){this._objectDefaults=e||WB}get objectDefaults(){return this._objectDefaults}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 dh(this.viewer.scene,_.apply(e,{isModel:!0,dtxEnabled:e.dtxEnabled})),i=t.id;if(!e.src&&!e.gltf)return this.error("load() param expected: src or gltf"),t;if(e.metaModelSrc||e.metaModelJSON){const s=s=>{this.viewer.metaScene.createMetaModel(i,s,{}),this.viewer.scene.canvas.spinner.processes--,e.src?this._sceneModelLoader.load(this,e.src,s,e,t):this._sceneModelLoader.parse(this,e.gltf,s,e,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--,s(e)}),(e=>{this.error(`load(): Failed to load model metadata for model '${i} from '${t}' - ${e}`),this.viewer.scene.canvas.spinner.processes--}))}else e.metaModelJSON&&s(e.metaModelJSON)}else e.src?this._sceneModelLoader.load(this,e.src,null,e,t):this._sceneModelLoader.parse(this,e.gltf,null,e,t);return t.once("destroyed",(()=>{this.viewer.metaScene.destroyMetaModel(i)})),t}destroy(){super.destroy()}},exports.HalfFloatType=1016,exports.ImagePlane=class extends D{constructor(e,t={}){super(e,t),this._src=null,this._image=null,this._pos=c.vec3(),this._origin=c.vec3(),this._rtcPos=c.vec3(),this._dir=c.vec3(),this._size=1,this._imageSize=c.vec2(),this._texture=new Ss(this),this._plane=new es(this,{geometry:new Gt(this,Ns({center:[0,0,0],xSize:1,zSize:1,xSegments:10,zSegments:10})),material:new Jt(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0}),clippable:t.clippable}),this._grid=new es(this,{geometry:new Gt(this,ks({size:1,divisions:10})),material:new Jt(this,{diffuse:[0,0,0],ambient:[0,0,0],emissive:[.2,.8,.2]}),position:[0,.001,0],clippable:t.clippable}),this._node=new gs(this,{rotation:[0,0,0],position:[0,0,0],scale:[1,1,1],clippable:!1,children:[this._plane,this._grid]}),this._gridVisible=!1,this.visible=!0,this.gridVisible=t.gridVisible,this.position=t.position,this.rotation=t.rotation,this.dir=t.dir,this.size=t.size,this.collidable=t.collidable,this.clippable=t.clippable,this.pickable=t.pickable,this.opacity=t.opacity,t.image?this.image=t.image:this.src=t.src}set visible(e){this._plane.visible=e,this._grid.visible=this._gridVisible&&e}get visible(){return this._plane.visible}set gridVisible(e){e=!1!==e,this._gridVisible=e,this._grid.visible=this._gridVisible&&this.visible}get gridVisible(){return this._gridVisible}set image(e){this._image=e,this._image&&(this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}get image(){return this._image}set src(e){if(this._src=e,this._src){this._image=null;const e=new Image;e.onload=()=>{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set position(e){this._pos.set(e||[0,0,0]),W(this._pos,this._origin,this._rtcPos),this._node.origin=this._origin,this._node.position=this._rtcPos}get position(){return this._pos}set rotation(e){this._node.rotation=e}get rotation(){return this._node.rotation}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set dir(e){if(this._dir.set(e||[0,0,-1]),e){const t=this.scene.center,i=[-this._dir[0],-this._dir[1],-this._dir[2]];c.subVec3(t,this.position,zh);const s=-c.dotVec3(i,zh);c.normalizeVec3(i),c.mulVec3Scalar(i,s,Wh),c.vec3PairToQuaternion(Kh,e,Xh),this._node.quaternion=Xh}}get dir(){return this._dir}set collidable(e){this._node.collidable=!1!==e}get collidable(){return this._node.collidable}set clippable(e){this._node.clippable=!1!==e}get clippable(){return this._node.clippable}set pickable(e){this._node.pickable=!1!==e}get pickable(){return this._node.pickable}set opacity(e){this._node.opacity=e}get opacity(){return this._node.opacity}destroy(){super.destroy()}_updatePlaneSizeFromImage(){const e=this._size,t=this._imageSize[0],i=this._imageSize[1];if(t>i){const s=i/t;this._node.scale=[e,1,e*s]}else{const s=t/i;this._node.scale=[e*s,1,e]}}},exports.IntType=1013,exports.JPEGMediaType=10001,exports.KTX2TextureTranscoder=NA,exports.LASLoaderPlugin=class extends V{constructor(e,t={}){super("lasLoader",e,t),this.dataSource=t.dataSource,this.skip=t.skip,this.fp64=t.fp64,this.colorDepth=t.colorDepth}get dataSource(){return this._dataSource}set dataSource(e){this._dataSource=e||new GP}get skip(){return this._skip}set skip(e){this._skip=e||1}get fp64(){return this._fp64}set fp64(e){this._fp64=!!e}get colorDepth(){return this._colorDepth}set colorDepth(e){this._colorDepth=e||"auto"}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 dh(this.viewer.scene,_.apply(e,{maxGeometryBatchSize:5e5,isModel:!0}));if(!e.src&&!e.las)return this.error("load() param expected: src or las"),t;const i={las:{skip:this._skip,fp64:this._fp64,colorDepth:this._colorDepth}};if(e.src)this._loadModel(e.src,e,i,t);else{const s=this.viewer.scene.canvas.spinner;s.processes++,this._parseModel(e.las,e,i,t).then((()=>{s.processes--}),(e=>{s.processes--,this.error(e),t.fire("error",e)}))}return t}_loadModel(e,t,i,s){const r=this.viewer.scene.canvas.spinner;r.processes++,this._dataSource.getLAS(t.src,(e=>{this._parseModel(e,t,i,s).then((()=>{r.processes--}),(e=>{r.processes--,this.error(e),s.fire("error",e)}))}),(e=>{r.processes--,this.error(e),s.fire("error",e)}))}_parseModel(e,t,i,s){function r(e){const i=e.value;if(t.rotateX&&i)for(let e=0,t=i.length;e{if(s.destroyed)return void l();const A=t.stats||{};A.sourceFormat="LAS",A.schemaVersion="",A.title="",A.author="",A.created="",A.numMetaObjects=0,A.numPropertySets=0,A.numObjects=0,A.numGeometries=0,A.numTriangles=0,A.numVertices=0;try{const A=XP(e);ry(e,zP,i).then((e=>{const h=e.attributes,u=e.loaderData,d=void 0!==u.pointsFormatId?u.pointsFormatId:-1;if(!h.POSITION)return s.finalize(),void l("No positions found in file");let p,f;switch(d){case 0:p=r(h.POSITION),f=n(h.intensity);break;case 1:if(!h.intensity)return s.finalize(),void l("No positions found in file");p=r(h.POSITION),f=n(h.intensity);break;case 2:case 3:if(!h.intensity)return s.finalize(),void l("No positions found in file");p=r(h.POSITION),f=o(h.COLOR_0,h.intensity)}const g=ZP(p,15e5),m=ZP(f,2e6),_=[];for(let e=0,t=g.length;e{s.destroyed||(s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1))})),a()}))}catch(e){s.finalize(),l(e)}}))}},exports.LambertMaterial=ms,exports.LightMap=class extends qh{get type(){return"LightMap"}constructor(e,t={}){super(e,t),this.scene._lightMapCreated(this)}destroy(){super.destroy(),this.scene._lightMapDestroyed(this)}},exports.LineSet=fh,exports.LinearEncoding=3e3,exports.LinearFilter=1006,exports.LinearMipMapLinearFilter=1008,exports.LinearMipMapNearestFilter=1007,exports.LinearMipmapLinearFilter=1008,exports.LinearMipmapNearestFilter=1007,exports.Loader=RA,exports.LoadingManager=SA,exports.LocaleService=Sh,exports.LuminanceAlphaFormat=1025,exports.LuminanceFormat=1024,exports.Map=e,exports.Marker=Ae,exports.MarqueePicker=N,exports.MarqueePickerMouseControl=class extends D{constructor(e){super(e.marqueePicker,e);const t=e.marqueePicker,i=t.viewer.scene.canvas.canvas;let s,r,o,n,a,l,A,h=!1,c=!1,u=!1;i.addEventListener("mousedown",(e=>{this.getActive()&&0===e.button&&(A=setTimeout((function(){const o=t.viewer.scene.input;o.keyDown[o.KEY_CTRL]||t.clear(),s=e.pageX,r=e.pageY,a=e.offsetX,t.setMarqueeCorner1([s,r]),h=!0,t.viewer.cameraControl.pointerEnabled=!1,t.setMarqueeVisible(!0),i.style.cursor="crosshair"}),400),c=!0)})),i.addEventListener("mouseup",(e=>{if(!this.getActive())return;if(!h&&!u)return;if(0!==e.button)return;clearTimeout(A),o=e.pageX,n=e.pageY;const i=Math.abs(o-s),a=Math.abs(n-r);h=!1,t.viewer.cameraControl.pointerEnabled=!0,u&&(u=!1),(i>3||a>3)&&t.pick()})),document.addEventListener("mouseup",(e=>{this.getActive()&&0===e.button&&(clearTimeout(A),h&&(t.setMarqueeVisible(!1),h=!1,c=!1,u=!0,t.viewer.cameraControl.pointerEnabled=!0))}),!0),i.addEventListener("mousemove",(e=>{this.getActive()&&0===e.button&&c&&(clearTimeout(A),h&&(o=e.pageX,n=e.pageY,l=e.offsetX,t.setMarqueeVisible(!0),t.setMarqueeCorner2([o,n]),t.setPickMode(a{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="ortho"===e||"perspective"===e?e:"perspective")}));var o=-1;function n(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 a,l,A=null,h=null,u=!1,d=!1,p=.5;s._navCubeCanvas.addEventListener("mouseenter",s._onMouseEnter=function(e){d=!0}),s._navCubeCanvas.addEventListener("mouseleave",s._onMouseLeave=function(e){d=!1}),s._navCubeCanvas.addEventListener("mousedown",s._onMouseDown=function(e){if(1===e.which){A=e.x,h=e.y,a=e.clientX,l=e.clientY;var t=n(e),s=i.pick({canvasPos:t});u=!!s}}),document.addEventListener("mouseup",s._onMouseUp=function(e){if(1===e.which&&(u=!1,null!==A)){var t=n(e),a=i.pick({canvasPos:t,pickSurface:!0});if(a&&a.uv){var l=s._cubeTextureCanvas.getArea(a.uv);if(l>=0&&(document.body.style.cursor="pointer",o>=0&&(s._cubeTextureCanvas.setAreaHighlighted(o,!1),s._repaint(),o=-1),l>=0)){if(s._cubeTextureCanvas.setAreaHighlighted(l,!0),o=l,s._repaint(),e.xA+3||e.yh+3)return;var c=s._cubeTextureCanvas.getAreaDir(l);if(c){var d=s._cubeTextureCanvas.getAreaUp(l);s._isProjectNorth&&s._projectNorthOffsetAngle&&(c=r(1,c,XB),d=r(1,d,JB)),f(c,d,(function(){o>=0&&(s._cubeTextureCanvas.setAreaHighlighted(o,!1),s._repaint(),o=-1),document.body.style.cursor="pointer",o>=0&&(s._cubeTextureCanvas.setAreaHighlighted(o,!1),s._repaint(),o=-1),l>=0&&(s._cubeTextureCanvas.setAreaHighlighted(l,!1),o=-1,s._repaint())}))}}}}}),document.addEventListener("mousemove",s._onMouseMove=function(t){if(o>=0&&(s._cubeTextureCanvas.setAreaHighlighted(o,!1),s._repaint(),o=-1),1!==t.buttons||u){if(u){var r=t.clientX,A=t.clientY;return document.body.style.cursor="move",void function(t,i){var s=(t-a)*-p,r=(i-l)*-p;e.camera.orbitYaw(s),e.camera.orbitPitch(-r),a=t,l=i}(r,A)}if(d){var h=n(t),c=i.pick({canvasPos:h,pickSurface:!0});if(c){if(c.uv){document.body.style.cursor="pointer";var f=s._cubeTextureCanvas.getArea(c.uv);if(f===o)return;o>=0&&s._cubeTextureCanvas.setAreaHighlighted(o,!1),f>=0&&(s._cubeTextureCanvas.setAreaHighlighted(f,!0),s._repaint(),o=f)}}else document.body.style.cursor="default",o>=0&&(s._cubeTextureCanvas.setAreaHighlighted(o,!1),s._repaint(),o=-1)}}});var f=function(){var t=c.vec3();return function(i,r,o){var n=s._fitVisible?e.scene.getAABB(e.scene.visibleObjectIds):e.scene.aabb,a=c.getAABB3Diag(n);c.getAABB3Center(n,t);var l=Math.abs(a/Math.tan(s._cameraFitFOV*c.DEGTORAD));e.cameraControl.pivotPos=t,s._cameraFly?e.cameraFlight.flyTo({look:t,eye:[t[0]-l*i[0],t[1]-l*i[1],t[2]-l*i[2]],up:r||[0,1,0],orthoScale:1.1*a,fitFOV:s._cameraFitFOV,duration:s._cameraFlyDuration},o):e.cameraFlight.jumpTo({look:t,eye:[t[0]-l*i[0],t[1]-l*i[1],t[2]-l*i[2]],up:r||[0,1,0],orthoScale:1.1*a,fitFOV:s._cameraFitFOV},o)}}();this._onUpdated=e.localeService.on("updated",(()=>{this._cubeTextureCanvas.clear(),this._repaint()})),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){if("language"===e)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&&(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}setIsProjectNorth(e=!1){this._isProjectNorth=e}getIsProjectNorth(){return this._isProjectNorth}setProjectNorthOffsetAngle(e){this._projectNorthOffsetAngle=e}getProjectNorthOffsetAngle(){return this._projectNorthOffsetAngle}destroy(){this._navCubeCanvas&&(this.viewer.localeService.off(this._onUpdated),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()}},exports.NearestFilter=1003,exports.NearestMipMapLinearFilter=1005,exports.NearestMipMapNearestFilter=1004,exports.NearestMipmapLinearFilter=1005,exports.NearestMipmapNearestFilter=1004,exports.Node=gs,exports.OBJLoaderPlugin=class extends V{constructor(e,t){super("OBJLoader",e,t),this._sceneGraphLoader=new ZB}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);var t=new gs(this.viewer.scene,_.apply(e,{isModel:!0}));const i=t.id,s=e.src;if(!s)return this.error("load() param expected: src"),t;if(e.metaModelSrc){const r=e.metaModelSrc;_.loadJSON(r,(r=>{this.viewer.metaScene.createMetaModel(i,r),this._sceneGraphLoader.load(t,s,e)}),(e=>{this.error(`load(): Failed to load model modelMetadata for model '${i} from '${r}' - ${e}`)}))}else this._sceneGraphLoader.load(t,s,e);return t.once("destroyed",(()=>{this.viewer.metaScene.destroyMetaModel(i)})),t}destroy(){super.destroy()}},exports.ObjectsKdTree3=class{constructor(e){if(!e)throw"Parameter expected: cfg";if(!e.viewer)throw"Parameter expected: cfg.viewer";this.viewer=e.viewer,this._maxTreeDepth=e.maxTreeDepth||15,this._root=null,this._needsRebuild=!0,this._onModelLoaded=this.viewer.scene.on("modelLoaded",(e=>{this._needsRebuild=!0})),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",(e=>{this._needsRebuild=!0}))}get root(){return this._needsRebuild&&this._rebuild(),this._root}_rebuild(){const e=this.viewer.scene;this._root={aabb:e.getAABB()};for(let t in e.objects){const i=e.objects[t];this._insertEntity(this._root,i,1)}this._needsRebuild=!1}_insertEntity(e,t,i){const s=t.aabb;if(i>=this._maxTreeDepth)return e.entities=e.entities||[],void e.entities.push(t);if(e.left&&c.containsAABB3(e.left.aabb,s))return void this._insertEntity(e.left,t,i+1);if(e.right&&c.containsAABB3(e.right.aabb,s))return void this._insertEntity(e.right,t,i+1);const r=e.aabb;u[0]=r[3]-r[0],u[1]=r[4]-r[1],u[2]=r[5]-r[2];let o=0;if(u[1]>u[o]&&(o=1),u[2]>u[o]&&(o=2),!e.left){const n=r.slice();if(n[o+3]=(r[o]+r[o+3])/2,e.left={aabb:n},c.containsAABB3(n,s))return void this._insertEntity(e.left,t,i+1)}if(!e.right){const n=r.slice();if(n[o]=(r[o]+r[o+3])/2,e.right={aabb:n},c.containsAABB3(n,s))return void this._insertEntity(e.right,t,i+1)}e.entities=e.entities||[],e.entities.push(t)}destroy(){const e=this.viewer.scene;e.off(this._onModelLoaded),e.off(this._onModelUnloaded),this._root=null,this._needsRebuild=!0}},exports.ObjectsMemento=ic,exports.PNGMediaType=10002,exports.Path=class extends Lh{constructor(e,t={}){super(e,t),this._cachedLengths=[],this._dirty=!0,this._curves=[],this._t=0,this._dirtySubs=[],this._destroyedSubs=[],this.curves=t.curves||[],this.t=t.t}addCurve(e){this._curves.push(e),this._dirty=!0}set curves(e){var t,i,s;for(e=e||[],i=0,s=this._curves.length;i1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}get length(){var e=this._getCurveLengths();return e[e.length-1]}getPoint(e){for(var t,i=e*this.length,s=this._getCurveLengths(),r=0;r=i){var o=1-(s[r]-i)/(t=this._curves[r]).length;return t.getPointAt(o)}r++}return null}_getCurveLengths(){if(!this._dirty)return this._cachedLengths;var e,t=[],i=0,s=this._curves.length;for(e=0;e{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=s.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=r.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new lt({type:"point",pos:c.vec3([1,1,1]),color:c.vec3([.7,.7,.8]),intensity:1,attenuation:[0,0,0],space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(i._shadowViewMatrixDirty){i._shadowViewMatrix||(i._shadowViewMatrix=c.identityMat4());const e=i._state.pos,t=s.look,r=s.up;c.lookAtMat4v(e,t,r,i._shadowViewMatrix),i._shadowViewMatrixDirty=!1}return i._shadowViewMatrix},getShadowProjMatrix:()=>{if(i._shadowProjMatrixDirty){i._shadowProjMatrix||(i._shadowProjMatrix=c.identityMat4());const e=i.scene.canvas.canvas;c.perspectiveMat4(Math.PI/180*70,e.clientWidth/e.clientHeight,.1,500,i._shadowProjMatrix),i._shadowProjMatrixDirty=!1}return i._shadowProjMatrix},getShadowRenderBuf:()=>(i._shadowRenderBuf||(i._shadowRenderBuf=new it(i.scene.canvas.canvas,i.scene.canvas.gl,{size:[1024,1024]})),i._shadowRenderBuf)}),this.pos=t.pos,this.color=t.color,this.intensity=t.intensity,this.constantAttenuation=t.constantAttenuation,this.linearAttenuation=t.linearAttenuation,this.quadraticAttenuation=t.quadraticAttenuation,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set pos(e){this._state.pos.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get pos(){return this._state.pos}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set constantAttenuation(e){this._state.attenuation[0]=e||0,this.glRedraw()}get constantAttenuation(){return this._state.attenuation[0]}set linearAttenuation(e){this._state.attenuation[1]=e||0,this.glRedraw()}get linearAttenuation(){return this._state.attenuation[1]}set quadraticAttenuation(e){this._state.attenuation[2]=e||0,this.glRedraw()}get quadraticAttenuation(){return this._state.attenuation[2]}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}},exports.PointerCircle=Q,exports.PointerLens=class{constructor(e,t={}){this.viewer=e,this.scene=this.viewer.scene,this._lensCursorDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._lensCursorDiv,this.viewer.scene.canvas.canvas),this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red",this._lensCursorDiv.style.borderRadius="20px",this._lensCursorDiv.style.width="10px",this._lensCursorDiv.style.height="10px",this._lensCursorDiv.style.margin="-200px -200px",this._lensCursorDiv.style.zIndex="100000",this._lensCursorDiv.style.position="absolute",this._lensCursorDiv.style.pointerEvents="none",this._lensContainer=document.createElement("div"),this._lensContainerId=t.containerId||"xeokit-lens",this._lensContainer.setAttribute("id",this._lensContainerId),this._lensContainer.style.border="1px solid black",this._lensContainer.style.background="white",this._lensContainer.style.borderRadius="50%",this._lensContainer.style.width="300px",this._lensContainer.style.height="300px",this._lensContainer.style.zIndex="15000",this._lensContainer.style.position="absolute",this._lensContainer.style.pointerEvents="none",this._lensContainer.style.visibility="hidden",this._lensCanvas=document.createElement("canvas"),this._lensCanvas.id=`${this._lensContainerId}-canvas`,this._lensCanvas.style.borderRadius="50%",this._lensCanvas.style.width="300px",this._lensCanvas.style.height="300px",this._lensCanvas.style.zIndex="15000",this._lensCanvas.style.pointerEvents="none",document.body.appendChild(this._lensContainer),this._lensContainer.appendChild(this._lensCanvas),this._lensCanvasContext=this._lensCanvas.getContext("2d"),this._canvasElement=this.viewer.scene.canvas.canvas,this._canvasPos=null,this._snappedCanvasPos=null,this._lensPosToggle=t.lensPosToggle||!0,this._lensPosToggleAmount=t.lensPosToggleAmount||85,this._lensPosMarginLeft=t.lensPosMarginLeft||85,this._lensPosMarginTop=t.lensPosMarginTop||25,this._lensContainer.style.marginTop=`${this._lensPosMarginTop}px`,this._lensContainer.style.marginLeft=`${this._lensPosMarginLeft}px`,this._zoomLevel=t.zoomLevel||2,this._active=!1!==t.active,this._visible=!1,this._snapped=!1,this._onViewerRendering=this.viewer.scene.on("rendering",(()=>{this._active&&this._visible&&this.update()}))}update(){if(!this._active||!this._visible)return;if(!this._canvasPos)return;const e=this._lensContainer.getBoundingClientRect(),t=this._canvasElement.getBoundingClientRect(),i=this._canvasPos[0]e.left&&this._canvasPos[1]e.top;this._lensContainer.style.marginLeft=`${this._lensPosMarginLeft}px`,i&&(this._lensPosToggle?this._lensContainer.style.marginTop=t.bottom-t.top-this._lensCanvas.height-this._lensPosToggleAmount+"px":this._lensContainer.style.marginTop=`${this._lensPosMarginTop}px`,this._lensPosToggle=!this._lensPosToggle),this._lensCanvasContext.clearRect(0,0,this._lensCanvas.width,this._lensCanvas.height);const s=Math.max(this._lensCanvas.width,this._lensCanvas.height)/this._zoomLevel;this._lensCanvasContext.drawImage(this._canvasElement,this._canvasPos[0]-s/2,this._canvasPos[1]-s/2,s,s,0,0,this._lensCanvas.width,this._lensCanvas.height);const r=[(e.left+e.right)/2-t.left,(e.top+e.bottom)/2-t.top];if(this._snappedCanvasPos){const e=this._snappedCanvasPos[0]-this._canvasPos[0],t=this._snappedCanvasPos[1]-this._canvasPos[1];this._lensCursorDiv.style.marginLeft=r[0]+e*this._zoomLevel-10+"px",this._lensCursorDiv.style.marginTop=r[1]+t*this._zoomLevel-10+"px"}else this._lensCursorDiv.style.marginLeft=r[0]-10+"px",this._lensCursorDiv.style.marginTop=r[1]-10+"px"}set zoomFactor(e){this._zoomFactor=e,this.update()}get zoomFactor(){return this._zoomFactor}set canvasPos(e){this._canvasPos=e,this.update()}get canvasPos(){return this._canvasPos}set snappedCanvasPos(e){this._snappedCanvasPos=e,this.update()}get snappedCanvasPos(){return this._snappedCanvasPos}set snapped(e){this._snapped=e,e?(this._lensCursorDiv.style.background="greenyellow",this._lensCursorDiv.style.border="2px solid green"):(this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red")}get snapped(){return this._snapped}set active(e){this._active=e,this._lensContainer.style.visibility=e&&this._visible?"visible":"hidden",e&&this._visible||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}get active(){return this._active}set visible(e){this._visible=e,this._lensContainer.style.visibility=e&&this._active?"visible":"hidden",e&&this._active||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}get visible(){return this._visible}destroy(){this._destroyed||(this.viewer.scene.off(this._onViewerRendering),this._lensContainer.removeChild(this._lensCanvas),document.body.removeChild(this._lensContainer),this._destroyed=!0)}},exports.QuadraticBezierCurve=class extends Lh{constructor(e,t={}){super(e,t),this.v0=t.v0,this.v1=t.v1,this.v2=t.v2,this.t=t.t}set v0(e){this._v0=e||c.vec3([0,0,0])}get v0(){return this._v0}set v1(e){this._v1=e||c.vec3([0,0,0])}get v1(){return this._v1}set v2(e){this._v2=e||c.vec3([0,0,0])}get v2(){return this._v2}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=c.vec3();return t[0]=c.b2(e,this._v0[0],this._v1[0],this._v2[0]),t[1]=c.b2(e,this._v0[1],this._v1[1],this._v2[1]),t[2]=c.b2(e,this._v0[2],this._v1[2],this._v2[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,t:this._t}}},exports.Queue=d,exports.RGBAFormat=1023,exports.RGBAIntegerFormat=1033,exports.RGBA_ASTC_10x10_Format=37819,exports.RGBA_ASTC_10x5_Format=37816,exports.RGBA_ASTC_10x6_Format=37817,exports.RGBA_ASTC_10x8_Format=37818,exports.RGBA_ASTC_12x10_Format=37820,exports.RGBA_ASTC_12x12_Format=37821,exports.RGBA_ASTC_4x4_Format=37808,exports.RGBA_ASTC_5x4_Format=37809,exports.RGBA_ASTC_5x5_Format=37810,exports.RGBA_ASTC_6x5_Format=37811,exports.RGBA_ASTC_6x6_Format=37812,exports.RGBA_ASTC_8x5_Format=37813,exports.RGBA_ASTC_8x6_Format=37814,exports.RGBA_ASTC_8x8_Format=37815,exports.RGBA_BPTC_Format=36492,exports.RGBA_ETC2_EAC_Format=37496,exports.RGBA_PVRTC_2BPPV1_Format=35843,exports.RGBA_PVRTC_4BPPV1_Format=35842,exports.RGBA_S3TC_DXT1_Format=33777,exports.RGBA_S3TC_DXT3_Format=33778,exports.RGBA_S3TC_DXT5_Format=33779,exports.RGBFormat=1022,exports.RGB_ETC1_Format=36196,exports.RGB_ETC2_Format=37492,exports.RGB_PVRTC_2BPPV1_Format=35841,exports.RGB_PVRTC_4BPPV1_Format=35840,exports.RGB_S3TC_DXT1_Format=33776,exports.RGFormat=1030,exports.RGIntegerFormat=1031,exports.ReadableGeometry=Gt,exports.RedFormat=1028,exports.RedIntegerFormat=1029,exports.ReflectionMap=class extends qh{get type(){return"ReflectionMap"}constructor(e,t={}){super(e,t),this.scene._lightsState.addReflectionMap(this._state),this.scene._reflectionMapCreated(this)}destroy(){super.destroy(),this.scene._reflectionMapDestroyed(this)}},exports.RepeatWrapping=1e3,exports.STLDefaultDataSource=xw,exports.STLLoaderPlugin=class extends V{constructor(e,t={}){super("STLLoader",e,t),this._sceneGraphLoader=new ww,this.dataSource=t.dataSource}set dataSource(e){this._dataSource=e||new xw}get dataSource(){return this._dataSource}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 gs(this.viewer.scene,_.apply(e,{isModel:!0})),i=e.src,s=e.stl;return i||s?(i?this._sceneGraphLoader.load(this,t,i,e):this._sceneGraphLoader.parse(this,t,s,e),t):(this.error("load() param expected: either 'src' or 'stl'"),t)}},exports.SceneModel=dh,exports.SceneModelMesh=nr,exports.SceneModelTransform=rh,exports.SectionPlane=ns,exports.SectionPlanesPlugin=class extends V{constructor(e,t={}){if(super("SectionPlanes",e),this._freeControls=[],this._sectionPlanes=e.scene.sectionPlanes,this._controls={},this._shownControlId=null,null!==t.overviewCanvasId&&void 0!==t.overviewCanvasId){const e=document.getElementById(t.overviewCanvasId);e?this._overview=new lw(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;Aw.set(this.viewer.scene.aabb),c.getAABB3Center(Aw,hw),Aw[0]+=t[0]-hw[0],Aw[1]+=t[1]-hw[1],Aw[2]+=t[2]-hw[2],Aw[3]+=t[0]-hw[0],Aw[4]+=t[1]-hw[1],Aw[5]+=t[2]-hw[2],this.viewer.cameraFlight.flyTo({aabb:Aw,fitFOV:65})},onClickedNothing:()=>{this.hideControl()}}):this.warn("Can't find overview canvas: '"+t.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={}){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);return new ns(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 nw(this);t._setSectionPlane(e),t.setVisible(!1),this._controls[e.id]=t,this._overview&&this._overview.addSectionPlane(e),e.once("destroyed",(()=>{this._sectionPlaneDestroyed(e)}))}flipSectionPlanes(){const e=this.viewer.scene.sectionPlanes;for(let t in e){e[t].flipDir()}}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{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set collidable(e){this._mesh.collidable=!1!==e}get collidable(){return this._mesh.collidable}set clippable(e){this._mesh.clippable=!1!==e}get clippable(){return this._mesh.clippable}set pickable(e){this._mesh.pickable=!1!==e}get pickable(){return this._mesh.pickable}set opacity(e){this._mesh.opacity=e}get opacity(){return this._mesh.opacity}_updatePlaneSizeFromImage(){const e=.5*this._size,t=this._imageSize[0],i=this._imageSize[1],s=i/t;this._geometry.positions=t>i?[e,e*s,0,-e,e*s,0,-e,-e*s,0,e,-e*s,0]:[e/s,e,0,-e/s,e,0,-e/s,-e,0,e/s,-e,0]}},exports.StoreyViewsPlugin=class extends V{constructor(e,t={}){super("StoreyViews",e),this._objectsMemento=new ic,this._cameraMemento=new $h,this.storeys={},this.modelStoreys={},this._fitStoreyMaps=!!t.fitStoreyMaps,this._onModelLoaded=this.viewer.scene.on("modelLoaded",(e=>{this._registerModelStoreys(e),this.fire("storeys",this.storeys)}))}_registerModelStoreys(e){const t=this.viewer,i=t.scene,s=t.metaScene,r=s.metaModels[e],o=i.models[e];if(!r||!r.rootMetaObjects)return;const n=r.rootMetaObjects;for(let t=0,r=n.length;t.5?a.length:0,h=new cw(this,o.aabb,l,e,n,A);h._onModelDestroyed=o.once("destroyed",(()=>{this._deregisterModelStoreys(e),this.fire("storeys",this.storeys)})),this.storeys[n]=h,this.modelStoreys[e]||(this.modelStoreys[e]={}),this.modelStoreys[e][n]=h}}}_deregisterModelStoreys(e){const t=this.modelStoreys[e];if(t){const i=this.viewer.scene;for(let e in t)if(t.hasOwnProperty(e)){const s=t[e],r=i.models[s.modelId];r&&r.off(s._onModelDestroyed),delete this.storeys[e]}delete this.modelStoreys[e]}}get fitStoreyMaps(){return this._fitStoreyMaps}gotoStoreyCamera(e,t={}){const i=this.storeys[e];if(!i)return this.error("IfcBuildingStorey not found with this ID: "+e),void(t.done&&t.done());const s=this.viewer,r=s.scene.camera,o=i.storeyAABB;if(o[3]{t.done()})):(s.cameraFlight.jumpTo(_.apply(t,{eye:h,look:n,up:u,orthoScale:A})),s.camera.ortho.scale=A)}showStoreyObjects(e,t={}){if(!this.storeys[e])return void this.error("IfcBuildingStorey not found with this ID: "+e);const i=this.viewer,s=i.scene;i.metaScene.metaObjects[e]&&(t.hideOthers&&s.setObjectsVisible(i.scene.visibleObjectIds,!1),this.withStoreyObjects(e,((e,t)=>{e&&(e.visible=!0)})))}withStoreyObjects(e,t){const i=this.viewer,s=i.scene,r=i.metaScene,o=r.metaObjects[e];if(!o)return;const n=o.getObjectIDsInSubtree();for(var a=0,l=n.length;athis.storeys[i[1]].storeyAABB[4]?i[1]:null}worldPosToStoreyMap(e,t,i){const s=e.storeyId,r=this.storeys[s];if(!r)return this.error("IfcBuildingStorey not found with this ID: "+s),!1;const o=this._fitStoreyMaps?r.storeyAABB:r.modelAABB,n=o[0],a=o[1],l=o[2],A=o[3]-n,h=o[4]-a,c=o[5]-l,u=this.viewer.camera.worldUp,d=u[0]>u[1]&&u[0]>u[2],p=!d&&u[1]>u[0]&&u[1]>u[2];!d&&!p&&u[2]>u[0]&&(u[2],u[1]);const f=e.width/A,g=p?e.height/c:e.height/h;return i[0]=Math.floor(e.width-(t[0]-n)*f),i[1]=Math.floor(e.height-(t[2]-l)*g),i[0]>=0&&i[0]=0&&i[1]<=e.height}worldDirToStoreyMap(e,t,i){const s=this.viewer.camera,r=s.eye,o=s.look,n=c.subVec3(o,r,dw),a=s.worldUp,l=a[0]>a[1]&&a[0]>a[2],A=!l&&a[1]>a[0]&&a[1]>a[2];!l&&!A&&a[2]>a[0]&&(a[2],a[1]),l?(i[0]=n[1],i[1]=n[2]):A?(i[0]=n[0],i[1]=n[2]):(i[0]=n[0],i[1]=n[1]),c.normalizeVec2(i)}destroy(){this.viewer.scene.off(this._onModelLoaded),super.destroy()}},exports.Texture=Ss,exports.TextureTranscoder=class{transcode(e,t,i={}){}destroy(){}},exports.TreeViewPlugin=class extends V{constructor(e,t={}){super("TreeViewPlugin",e),this.errors=[],this.valid=!0;const i=t.containerElement||document.getElementById(t.containerElementId);if(i instanceof HTMLElement){for(let e=0;;e++)if(!Sw[e]){Sw[e]=this,this._index=e,this._id=`tree-${e}`;break}if(this._containerElement=i,this._metaModels={},this._autoAddModels=!1!==t.autoAddModels,this._autoExpandDepth=t.autoExpandDepth||0,this._sortNodes=!1!==t.sortNodes,this._viewer=e,this._rootElement=null,this._muteSceneEvents=!1,this._muteTreeEvents=!1,this._rootNodes=[],this._objectNodes={},this._nodeNodes={},this._rootNames={},this._sortNodes=t.sortNodes,this._pruneEmptyNodes=t.pruneEmptyNodes,this._showListItemElementId=null,this._renderService=t.renderService||new Dw,this._showIndeterminate=t.showIndeterminate??!1,!this._renderService)throw new Error("TreeViewPlugin: no render service set");if(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--,this._renderService.setCheckbox(i.nodeId,s);let r=i.parent;for(;r;){r.checked=s,s?r.numVisibleEntities++:r.numVisibleEntities--;const e=this._showIndeterminate&&r.numVisibleEntities>0&&r.numVisibleEntities0,e),r=r.parent}this._muteTreeEvents=!1})),this._onObjectXrayed=this._viewer.scene.on("objectXRayed",(e=>{if(this._muteSceneEvents)return;const t=e.id,i=this._objectNodes[t];if(!i)return;this._muteTreeEvents=!0;const s=e.xrayed;s!==i.xrayed&&(i.xrayed=s,this._renderService.setXRayed(i.nodeId,s),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=this._renderService.isChecked(t),s=this._renderService.getIdFromCheckbox(t),r=this._nodeNodes[s],o=this._viewer.scene.objects;let n=0;this._withNodeTree(r,(e=>{const t=e.objectId,s=o[t],r=0===e.children.length;e.numVisibleEntities=i?e.numEntities:0,r&&i!==e.checked&&n++,e.checked=i,this._renderService.setCheckbox(e.nodeId,i),s&&(s.visible=i)}));let a=r.parent;for(;a;){a.checked=i,i?a.numVisibleEntities+=n:a.numVisibleEntities-=n;const e=this._showIndeterminate&&a.numVisibleEntities>0&&a.numVisibleEntities0,e),a=a.parent}this._muteSceneEvents=!1},this._hierarchy=t.hierarchy||"containment",this._autoExpandDepth=t.autoExpandDepth||0,this._autoAddModels){const e=Object.keys(this.viewer.metaScene.metaModels);for(let t=0,i=e.length;t{this.viewer.metaScene.metaModels[e]&&this.addModel(e)}))}this.hierarchy=t.hierarchy}else this.error("Mandatory config expected: valid containerElementId or 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&&(this._hierarchy=e,this._createNodes())}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._metaModels[e]?this.warn("Model already added: "+e):(this._metaModels[e]=s,t&&t.rootName&&(this._rootNames[e]=t.rootName),i.on("destroyed",(()=>{this.removeModel(i.id)})),this._createNodes()):this.error("MetaModel not found: "+e)}removeModel(e){if(!this._containerElement)return;this._metaModels[e]&&(this._rootNames[e]&&delete this._rootNames[e],delete this._metaModels[e],this._createNodes())}showNode(e){this.unShowNode();const t=this._objectNodes[e];if(!t)return;this.collapse();const i=t.nodeId,s=this._renderService.getSwitchElement(i);if(s)return this._expandSwitchElement(s),s.scrollIntoView(),!0;const r=[];r.unshift(t);let o=t.parent;for(;o;)r.unshift(o),o=o.parent;for(let e=0,t=r.length;e{if(s===e)return;const r=this._renderService.getSwitchElement(i.nodeId);if(r){this._expandSwitchElement(r);const e=i.children;for(var o=0,n=e.length;o0;return this.valid}_validateMetaModelForStoreysHierarchy(e=0,t,i){return!0}_createEnabledNodes(){switch(this._pruneEmptyNodes&&this._findEmptyNodes(),this._hierarchy){case"storeys":this._createStoreysNodes(),0===this._rootNodes.length&&this.error("Failed to build storeys hierarchy");break;case"types":this._createTypesNodes();break;default:this._createContainmentNodes()}this._sortNodes&&this._doSortNodes(),this._synchNodesToEntities(),this._createTrees(),this.expandToDepth(this._autoExpandDepth)}_createDisabledNodes(){const e=this._renderService.createRootNode();this._rootElement=e,this._containerElement.appendChild(e);const t=this._viewer.metaScene.rootMetaObjects;for(let i in t){const s=t[i],r=s.type,o=s.name,n=o&&""!==o&&"Undefined"!==o&&"Default"!==o?o:r,a=this._renderService.createDisabledNodeElement(n);e.appendChild(a)}}_findEmptyNodes(){const e=this._viewer.metaScene.rootMetaObjects;for(let t in e)this._findEmptyNodes2(e[t])}_findEmptyNodes2(e,t=0){const i=this.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{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]s?1:0}_synchNodesToEntities(){const e=Object.keys(this.viewer.metaScene.metaObjects),t=this._viewer.metaScene.metaObjects,i=this._viewer.scene.objects;for(let s=0,r=e.length;sthis._createNodeElement(e))),t=this._renderService.createRootNode();e.forEach((e=>{t.appendChild(e)})),this._containerElement.appendChild(t),this._rootElement=t}_createNodeElement(e){return this._renderService.createNodeElement(e,this._switchExpandHandler,this._checkboxChangeHandler,(t=>{this.fire("contextmenu",{event:t,viewer:this._viewer,treeViewPlugin:this,treeViewNode:e}),t.preventDefault()}),(t=>{this.fire("nodeTitleClicked",{event:t,viewer:this._viewer,treeViewPlugin:this,treeViewNode:e}),t.preventDefault()}))}_expandSwitchElement(e){if(this._renderService.isExpanded(e))return;const t=this._renderService.getId(e),i=this._nodeNodes[t].children.map((e=>this._createNodeElement(e)));this._renderService.addChildren(e,i),this._renderService.expand(e,this._switchExpandHandler,this._switchCollapseHandler)}_collapseNode(e){const t=this._renderService.getSwitchElement(e);this._collapseSwitchElement(t)}_collapseSwitchElement(e){this._renderService.collapse(e,this._switchExpandHandler,this._switchCollapseHandler)}},exports.UnsignedByteType=1009,exports.UnsignedInt248Type=1020,exports.UnsignedIntType=1014,exports.UnsignedShort4444Type=1017,exports.UnsignedShort5551Type=1018,exports.UnsignedShortType=1012,exports.VBOGeometry=Ls,exports.ViewCullPlugin=class extends V{constructor(e,t={}){super("ViewCull",e),this._objectCullStates=function(e){const t=e.id;let i=Rw[t];return i||(i=new Tw(e),Rw[t]=i,e.on("destroyed",(()=>{delete Rw[t],i._destroy()}))),i}(e.scene),this._maxTreeDepth=t.maxTreeDepth||8,this._modelInfos={},this._frustum=new U,this._kdRoot=null,this._frustumDirty=!1,this._kdTreeDirty=!1,this._onViewMatrix=e.scene.camera.on("viewMatrix",(()=>{this._frustumDirty=!0})),this._onProjMatrix=e.scene.camera.on("projMatMatrix",(()=>{this._frustumDirty=!0})),this._onModelLoaded=e.scene.on("modelLoaded",(e=>{const t=this.viewer.scene.models[e];t&&this._addModel(t)})),this._onSceneTick=e.scene.on("tick",(()=>{this._doCull()}))}set enabled(e){this._enabled=e}get enabled(){return this._enabled}_addModel(e){const t={model:e,onDestroyed:e.on("destroyed",(()=>{this._removeModel(e)}))};this._modelInfos[e.id]=t,this._kdTreeDirty=!0}_removeModel(e){const t=this._modelInfos[e.id];t&&(t.model.off(t.onDestroyed),delete this._modelInfos[e.id],this._kdTreeDirty=!0)}_doCull(){const e=this._frustumDirty||this._kdTreeDirty;if(this._frustumDirty&&this._buildFrustum(),this._kdTreeDirty&&this._buildKDTree(),e){const e=this._kdRoot;e&&this._visitKDNode(e)}}_buildFrustum(){const e=this.viewer.scene.camera;O(this._frustum,e.viewMatrix,e.projMatrix),this._frustumDirty=!1}_buildKDTree(){const e=this.viewer.scene;this._kdRoot,this._kdRoot={aabb:e.getAABB(),intersection:U.INTERSECT};for(let e=0,t=this._objectCullStates.numObjects;e=this._maxTreeDepth)return e.objects=e.objects||[],e.objects.push(i),void c.expandAABB3(e.aabb,r);if(e.left&&c.containsAABB3(e.left.aabb,r))return void this._insertEntityIntoKDTree(e.left,t,i,s+1);if(e.right&&c.containsAABB3(e.right.aabb,r))return void this._insertEntityIntoKDTree(e.right,t,i,s+1);const o=e.aabb;Lw[0]=o[3]-o[0],Lw[1]=o[4]-o[1],Lw[2]=o[5]-o[2];let n=0;if(Lw[1]>Lw[n]&&(n=1),Lw[2]>Lw[n]&&(n=2),!e.left){const a=o.slice();if(a[n+3]=(o[n]+o[n+3])/2,e.left={aabb:a,intersection:U.INTERSECT},c.containsAABB3(a,r))return void this._insertEntityIntoKDTree(e.left,t,i,s+1)}if(!e.right){const a=o.slice();if(a[n]=(o[n]+o[n+3])/2,e.right={aabb:a,intersection:U.INTERSECT},c.containsAABB3(a,r))return void this._insertEntityIntoKDTree(e.right,t,i,s+1)}e.objects=e.objects||[],e.objects.push(i),c.expandAABB3(e.aabb,r)}_visitKDNode(e,t=U.INTERSECT){if(t!==U.INTERSECT&&e.intersects===t)return;t===U.INTERSECT&&(t=k(this._frustum,e.aabb),e.intersects=t);const i=t===U.OUTSIDE,s=e.objects;if(s&&s.length>0)for(let e=0,t=s.length;e{this._parseModel(e,t,i,s),r.processes--}),(e=>{r.processes--,this.error(e),s.fire("error",e)}))}_parseModel(e,t,i,s){if(s.destroyed)return;const r=t.stats||{};if(r.sourceFormat="IFC",r.schemaVersion="",r.title="",r.author="",r.created="",r.numMetaObjects=0,r.numPropertySets=0,r.numObjects=0,r.numGeometries=0,r.numTriangles=0,r.numVertices=0,!this._ifcAPI)throw"WebIFCLoaderPlugin has no WebIFC instance configured - please inject via WebIFCLoaderPlugin constructor";const o=new Uint8Array(e),n=this._ifcAPI.OpenModel(o),a=this._ifcAPI.GetModelSchema(n),l=this._ifcAPI.GetLineIDsWithType(n,this._webIFC.IFCPROJECT).get(0),A=!1!==t.loadMetadata,h={modelID:n,modelSchema:a,sceneModel:s,loadMetadata:A,metadata:A?{id:"",projectId:""+l,author:"",createdAt:"",schema:"",creatingApplication:"",metaObjects:[],propertySets:[]}:null,metaObjects:{},options:i,log:function(e){},nextId:0,stats:r};if(A){if(i.includeTypes){h.includeTypes={};for(let e=0,t=i.includeTypes.length;e{s.destroyed||(s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1))}))}_parseMetaObjects(e){const t=this._ifcAPI.GetLineIDsWithType(e.modelID,this._webIFC.IFCPROJECT).get(0),i=this._ifcAPI.GetLine(e.modelID,t);this._parseSpatialChildren(e,i)}_parseSpatialChildren(e,t,i){const s=this._ifcAPI.GetNameFromTypeCode(t.type);if(e.includeTypes&&!e.includeTypes[s])return;if(e.excludeTypes&&e.excludeTypes[s])return;this._createMetaObject(e,t,i);const r=t.GlobalId.value;this._parseRelatedItemsOfType(e,t.expressID,"RelatingObject","RelatedObjects",this._webIFC.IFCRELAGGREGATES,r),this._parseRelatedItemsOfType(e,t.expressID,"RelatingStructure","RelatedElements",this._webIFC.IFCRELCONTAINEDINSPATIALSTRUCTURE,r)}_createMetaObject(e,t,i){const s=t.GlobalId.value,r=this._ifcAPI.GetNameFromTypeCode(t.type),o={id:s,name:t.Name&&""!==t.Name.value?t.Name.value:r,type:r,parent:i};e.metadata.metaObjects.push(o),e.metaObjects[s]=o,e.stats.numMetaObjects++}_parseRelatedItemsOfType(e,t,i,s,r,o){const n=this._ifcAPI.GetLineIDsWithType(e.modelID,r);for(let r=0;re.value)).includes(t)}else h=A.value===t;if(h){const t=l[s];if(Array.isArray(t))t.forEach((t=>{const i=this._ifcAPI.GetLine(e.modelID,t.value);this._parseSpatialChildren(e,i,o)}));else{const i=this._ifcAPI.GetLine(e.modelID,t.value);this._parseSpatialChildren(e,i,o)}}}}_parsePropertySets(e){const t=this._ifcAPI.GetLineIDsWithType(e.modelID,this._webIFC.IFCRELDEFINESBYPROPERTIES);for(let i=0;i0){const o="Default",n=t.Name.value,a=[];for(let e=0,t=s.length;e{const i=t.expressID,s=t.geometries,r=[],o=this._ifcAPI.GetLine(e.modelID,i).GlobalId.value;if(e.loadMetadata){const t=o,i=e.metaObjects[t];if(e.includeTypes&&(!i||!e.includeTypes[i.type]))return;if(e.excludeTypes&&(!i||e.excludeTypes[i.type]))return}const n=c.mat4(),a=c.vec3();for(let t=0,i=s.size();t{o.destroyed||(o.finalize(),a.finalize(),this.viewer.scene.canvas.spinner.processes--,o.once("destroyed",(()=>{this.viewer.metaScene.destroyMetaModel(a.id)})),this.scheduleTask((()=>{o.destroyed||(o.scene.fire("modelLoaded",o.id),o.fire("loaded",!0,!1))})))},A=e=>{this.viewer.scene.canvas.spinner.processes--,this.error(e),o.fire("error",e)};let h=0;const c={getNextId:()=>`${n}.${h++}`};if(e.metaModelSrc||e.metaModelData)if(e.metaModelSrc){const r=e.metaModelSrc;this._dataSource.getMetaModel(r,(r=>{o.destroyed||(a.loadData(r,{includeTypes:i,excludeTypes:s,globalizeObjectIds:t.globalizeObjectIds}),e.src?this._loadModel(e.src,e,t,o,null,c,l,A):(this._parseModel(e.xkt,e,t,o,null,c),l()))}),(e=>{A(`load(): Failed to load model metadata for model '${n} from '${r}' - ${e}`)}))}else e.metaModelData&&(a.loadData(e.metaModelData,{includeTypes:i,excludeTypes:s,globalizeObjectIds:t.globalizeObjectIds}),e.src?this._loadModel(e.src,e,t,o,null,c,l,A):(this._parseModel(e.xkt,e,t,o,null,c),l()));else if(e.src)this._loadModel(e.src,e,t,o,a,c,l,A);else if(e.xkt)this._parseModel(e.xkt,e,t,o,a,c),l();else if(e.manifestSrc||e.manifest){const r=e.manifestSrc?function(e){const t=e.split("/");return t.pop(),t.join("/")+"/"}(e.manifestSrc):"",n=(e,n,l)=>{let A=0;const h=()=>{o.destroyed||A>=e.length?n():this._dataSource.getMetaModel(`${r}${e[A]}`,(e=>{a.loadData(e,{includeTypes:i,excludeTypes:s,globalizeObjectIds:t.globalizeObjectIds}),A++,this.scheduleTask(h,200)}),l)};h()},h=(i,s,n)=>{let a=0;const l=()=>{o.destroyed||a>=i.length?s():this._dataSource.getXKT(`${r}${i[a]}`,(i=>{this._parseModel(i,e,t,o,null,c),o.preFinalize(),a++,this.scheduleTask(l,200)}),n)};l()},u=(i,s,n)=>{let l=0;const A=()=>{o.destroyed||l>=i.length?s():this._dataSource.getXKT(`${r}${i[l]}`,(i=>{this._parseModel(i,e,t,o,a,c),o.preFinalize(),l++,this.scheduleTask(A,200)}),n)};A()};if(e.manifest){const t=e.manifest,i=t.xktFiles;if(!i||0===i.length)return void A("load(): Failed to load model manifest - manifest not valid");const s=t.metaModelFiles;s?n(s,(()=>{h(i,l,A)}),A):u(i,l,A)}else this._dataSource.getManifest(e.manifestSrc,(e=>{if(o.destroyed)return;const t=e.xktFiles;if(!t||0===t.length)return void A("load(): Failed to load model manifest - manifest not valid");const i=e.metaModelFiles;i?n(i,(()=>{h(t,l,A)}),A):u(t,l,A)}),A)}return o}_loadModel(e,t,i,s,r,o,n,a){this._dataSource.getXKT(t.src,(e=>{this._parseModel(e,t,i,s,r,o),s.preFinalize(),n()}),a)}async _parseModel(e,t,i,s,r,o){if(s.destroyed)return;const n=new DataView(e),a=new Uint8Array(e),l=n.getUint32(0,!0),A=EP[l];if(!A)return void this.error("Unsupported .XKT file version: "+l+" - this XKTLoaderPlugin supports versions "+Object.keys(EP));if(A.parseArrayBuffer)return void A.parseArrayBuffer(this.viewer,i,e,s,r,o);const h=n.getUint32(4,!0),c=[];let u=4*(h+2);for(let e=0;eRC(e,t)))}},exports.ZonesPlugin=class extends V{constructor(e,t={}){super("Zones",e),this._pointerLens=t.pointerLens,this._container=t.container||document.body,this._zones=[],this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.zIndex=t.zIndex||1e4,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,zone:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,zone:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,zone:t,event:e})}}createZone(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=new UC(this,{id:e.id,plugin:this,container:this._container,geometry:e.geometry,alpha:e.alpha,color:e.color,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._zones.push(t),t.on("destroyed",(()=>{const e=this._zones.indexOf(t);e>=0&&this._zones.splice(e,1)})),this.fire("zoneCreated",t),t}get zones(){return this._zones}destroy(){super.destroy()}},exports.ZonesPolysurfaceMouseControl=class extends D{constructor(e,t={}){super(e.viewer.scene),this.zonesPlugin=e,this.pointerLens=t.pointerLens,this._action=null}get active(){return!!this._action}activate(e,t,i,s){if("object"==typeof e&&null!==e){const r=e,o=(e,t)=>{if(e in r)return r[e];if(void 0!==t)return t;throw"config missing: "+e};e=o("altitude"),t=o("height"),i=o("color","#008000"),s=o("alpha",.5)}if(this._action)return;const r=this.zonesPlugin,o=r.viewer,n=o.scene,a=this,l=RC(o,(function(t,i){return LC(e,c.vec3([0,1,0]),t,i)}));!function o(){a._action=kC(n,e,t,i,s,a.pointerLens,r,l,(e=>{let t=!0;a._action={deactivate:()=>{t=!1}},a.fire("zoneEnd",e),t&&o()}))}()}deactivate(){this._action&&(this._action.deactivate(),this._action=null)}destroy(){this.deactivate(),super.destroy()}},exports.ZonesPolysurfaceTouchControl=class extends D{constructor(e,t={}){super(e.viewer.scene),this.zonesPlugin=e,this.pointerLens=t.pointerLens,this.pointerCircle=new Q(e.viewer),this._action=null}get active(){return!!this._action}activate(e,t,i,s){if("object"==typeof e&&null!==e){const r=e,o=(e,t)=>{if(e in r)return r[e];if(void 0!==t)return t;throw"config missing: "+e};e=o("altitude"),t=o("height"),i=o("color","#008000"),s=o("alpha",.5)}if(this._action)return;const r=this.zonesPlugin,o=r.viewer,n=o.scene,a=this,l=fe(o,this.pointerCircle,(function(t,i){return LC(e,c.vec3([0,1,0]),t,i)}));!function o(){a._action=kC(n,e,t,i,s,a.pointerLens,r,l,(e=>{let t=!0;a._action={deactivate:()=>{t=!1}},a.fire("zoneEnd",e),t&&o()}))}()}deactivate(){this._action&&(this._action.deactivate(),this._action=null)}destroy(){this.deactivate(),super.destroy()}},exports.ZonesTouchControl=class extends OC{constructor(e,t={}){const i=new Q(e.viewer);super(e,t,((e,t)=>fe(e,i,t))),this.pointerCircle=i}destroy(){this.pointerCircle.destroy(),super.destroy()}},exports.activateDraggableDot=de,exports.activateDraggableDots=pe,exports.buildBoxGeometry=zt,exports.buildBoxLinesGeometry=Os,exports.buildBoxLinesGeometryFromAABB=function(e={}){return Os({id:e.id,center:[(e.aabb[0]+e.aabb[3])/2,(e.aabb[1]+e.aabb[4])/2,(e.aabb[2]+e.aabb[5])/2],xSize:Math.abs(e.aabb[3]-e.aabb[0])/2,ySize:Math.abs(e.aabb[4]-e.aabb[1])/2,zSize:Math.abs(e.aabb[5]-e.aabb[2])/2})},exports.buildCylinderGeometry=is,exports.buildGridGeometry=ks,exports.buildLineGeometry=function(e={}){if(3!==e.startPoint.length)throw"Start point should contain 3 elements in array: x, y and z";if(3!==e.endPoint.length)throw"End point should contain 3 elements in array: x, y and z";let t=[],i=[],s=e.startPoint[0],r=e.startPoint[1],o=e.startPoint[2],n=e.endPoint[0],a=e.endPoint[1],l=e.endPoint[2],A=Math.sqrt((n-s)**2+(a-r)**2+(l-o)**2),h=[(n-s)/A,(a-r)/A,(l-o)/A];if(e.pattern){let c=e.pattern.length,u=!1,d=0,p=0,f=0,g=[s,r,o],m=e.pattern[p];for(i.push(g[0],g[1],g[2]);m<=A-d;){let s=[h[0]*m,h[1]*m,h[2]*m],r=[g[0]+s[0],g[1]+s[1],g[2]+s[2]];i.push(r[0],r[1],r[2]),u||(t.push(f),t.push(f+1)),u=!u,f+=1,g=r,p+=1,p>=c&&(p=0),d+=m,m=e.pattern[p]}e.extendToEnd&&(i.push(n,a,l),t.push(t.length-2),t.push(t.length-1))}else t.push(0),t.push(1),i.push(s,r,o,n,a,l);return _.apply(e,{primitive:"lines",positions:i,indices:t})},exports.buildPlaneGeometry=Ns,exports.buildPolylineGeometry=Vs,exports.buildPolylineGeometryFromCurve=function(e={}){let t=e.curve.getPoints(e.divisions).map((e=>[...e])).flat();return Vs({id:e.id,points:t})},exports.buildSphereGeometry=ss,exports.buildTorusGeometry=Qs,exports.buildVectorTextGeometry=os,exports.createRTCViewMat=z,exports.frustumIntersectsAABB3=k,exports.getKTX2TextureTranscoder=VA,exports.getPlaneRTCPos=X,exports.isTriangleMeshSolid=js,exports.load3DSGeometry=function(e,t={}){return new Promise((function(i,s){t.src||(console.error("load3DSGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,_.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("load3DSGeometry: no data loaded"),r.processes--,s());var o=Us.parse.from3DS(e).edit.objects[0].mesh,n=o.vertices,a=o.uvt,l=o.indices;r.processes--,i(_.apply(t,{primitive:"triangles",positions:n,normals:null,uv:a,indices:l}))}),(function(e){console.error("load3DSGeometry: "+e),r.processes--,s()}))}))},exports.loadOBJGeometry=function(e,t={}){return new Promise((function(i,s){t.src||(console.error("loadOBJGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,_.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("loadOBJGeometry: no data loaded"),r.processes--,s());for(var o=Us.parse.fromOBJ(e),n=Us.edit.unwrap(o.i_verts,o.c_verts,3),a=Us.edit.unwrap(o.i_norms,o.c_norms,3),l=Us.edit.unwrap(o.i_uvt,o.c_uvt,2),A=new Int32Array(o.i_verts.length),h=0;h0?a:null,autoNormals:0===a.length,uv:l,indices:A}))}),(function(e){console.error("loadOBJGeometry: "+e),r.processes--,s()}))}))},exports.math=c,exports.meshSurfaceArea=ir,exports.meshVolume=Xs,exports.rtcToWorldPos=function(e,t,i){return i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i},exports.sRGBEncoding=3001,exports.setFrustum=O,exports.stats=p,exports.touchPointSelector=fe,exports.transformToNode=ce,exports.utils=_,exports.worldToRTCPos=W,exports.worldToRTCPositions=K; diff --git a/dist/xeokit-sdk.min.es.js b/dist/xeokit-sdk.min.es.js index 25d8ed36a..5db78c89b 100644 --- a/dist/xeokit-sdk.min.es.js +++ b/dist/xeokit-sdk.min.es.js @@ -1,4 +1,4 @@ -class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){let e;if(2===arguments.length){const t=arguments[0];if(e=arguments[1],this.items[t])throw"ID clash: '"+t+"'";return this.items[t]=e,t}for(e=arguments[0]||{};;){const t=this._lastUniqueId++;if(!this.items[t])return this.items[t]=e,t}}removeItem(e){const t=this.items[e];return delete this.items[e],t}}const t=new e;class i{constructor(e){this.id=e,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0}}class s{constructor(){this.items=[]}}class r{constructor(e,t,i,s,r){this.id=e,this.getTitle=t,this.doAction=i,this.getEnabled=s,this.getShown=r,this.itemElement=null,this.subMenu=null,this.enabled=!0}}class o{constructor(e={}){this._id=t.addItem(),this._context=null,this._enabled=!1,this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={},this._shown=!1,this._nextId=0,this._eventSubs={},!1!==e.hideOnMouseDown&&(document.addEventListener("mousedown",(e=>{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),document.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),e.items&&(this.items=e.items),this._hideOnAction=!1!==e.hideOnAction,this.context=e.context,this.enabled=!1!==e.enabled,this.hide()}on(e,t){let 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{const o=this._getNextId(),n=new i(o);for(let i=0,o=e.length;i0,A=this._getNextId(),h=i.getTitle||(()=>i.title||""),c=i.doAction||i.callback||(()=>{}),u=i.getEnabled||(()=>!0),d=i.getShown||(()=>!0),p=new r(A,h,c,u,d);if(p.parentMenu=n,a.items.push(p),l){const e=t(s);p.subMenu=e,e.parentItem=p}this._itemList.push(p),this._itemMap[p.id]=p}}return this._menuList.push(n),this._menuMap[n.id]=n,n};this._rootMenu=t(e)}_getNextId(){return"ContextMenu_"+this._id+"_"+this._nextId++}_createUI(){const e=t=>{this._createMenuUI(t);const i=t.groups;for(let t=0,s=i.length;t'),i.push("
    "),t)for(let e=0,s=t.length;e'+l+""),r===o-1||e')):(i.push('
  • '+l+"
  • "),r===o-1||e'))}}i.push("
"),i.push("");const s=i.join("");document.body.insertAdjacentHTML("beforeend",s);const r=document.querySelector("."+e.id);e.menuElement=r,r.style["border-radius"]="4px",r.style.display="none",r.style["z-index"]=3e5,r.style.background="white",r.style.border="1px solid black",r.style["box-shadow"]="0 4px 5px 0 gray",r.oncontextmenu=e=>{e.preventDefault()};const o=this;let n=null;if(t)for(let e=0,i=t.length;e{e.preventDefault();const i=t.subMenu;if(!i)return void(n&&(o._hideMenu(n.id),n=null));if(n&&n.id!==i.id&&(o._hideMenu(n.id),n=null),!1===t.enabled)return;const s=t.itemElement,r=i.menuElement,a=s.getBoundingClientRect();r.getBoundingClientRect();a.right+200>window.innerWidth?o._showMenu(i.id,a.left-200,a.top-1):o._showMenu(i.id,a.right-5,a.top-1),n=i})),s||(t.itemElement.addEventListener("click",(e=>{e.preventDefault(),o._context&&!1!==t.enabled&&(t.doAction&&t.doAction(o._context),this._hideOnAction?o.hide():(o._updateItemsTitles(),o._updateItemsEnabledStatus()))})),t.itemElement.addEventListener("mouseup",(e=>{3===e.which&&(e.preventDefault(),o._context&&!1!==t.enabled&&(t.doAction&&t.doAction(o._context),this._hideOnAction?o.hide():(o._updateItemsTitles(),o._updateItemsEnabledStatus())))})),t.itemElement.addEventListener("mouseenter",(e=>{e.preventDefault(),!1!==t.enabled&&t.doHover&&t.doHover(o._context)})))):console.error("ContextMenu item element not found: "+t.id)}}}_updateItemsTitles(){if(this._context)for(let e=0,t=this._itemList.length;e{n.subMenu&&(e=n.itemElement,t=e.getBoundingClientRect(),i=n.subMenu.menuElement,s={visibility:i.style.visibility,display:i.style.display},i.style.display="block",i.style.visibility="hidden",o=n.subMenu.menuElement.getBoundingClientRect().width,i.style.visibility=s.visibility,i.style.display=s.display,r=t.right+o>window.innerWidth,e.setAttribute("data-submenuposition",r?"left":"right"))}))}_showMenu(e,t,i){const s=this._menuMap[e];if(!s)return void console.error("Menu not found: "+e);if(s.shown)return;const r=s.menuElement;r&&(this._showMenuElement(r,t,i),s.shown=!0)}_hideMenu(e){const t=this._menuMap[e];if(!t)return void console.error("Menu not found: "+e);if(!t.shown)return;const i=t.menuElement;i&&(this._hideMenuElement(i),t.shown=!1)}_hideAllMenus(){for(let e=0,t=this._menuList.length;ewindow.innerHeight&&(i=window.innerHeight-s),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=i+"px"}_hideMenuElement(e){e.style.display="none"}}class n{constructor(e,t={}){this.viewer=e,this.scene=this.viewer.scene,this._lensCursorDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._lensCursorDiv,this.viewer.scene.canvas.canvas),this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red",this._lensCursorDiv.style.borderRadius="20px",this._lensCursorDiv.style.width="10px",this._lensCursorDiv.style.height="10px",this._lensCursorDiv.style.margin="-200px -200px",this._lensCursorDiv.style.zIndex="100000",this._lensCursorDiv.style.position="absolute",this._lensCursorDiv.style.pointerEvents="none",this._lensContainer=document.createElement("div"),this._lensContainerId=t.containerId||"xeokit-lens",this._lensContainer.setAttribute("id",this._lensContainerId),this._lensContainer.style.border="1px solid black",this._lensContainer.style.background="white",this._lensContainer.style.borderRadius="50%",this._lensContainer.style.width="300px",this._lensContainer.style.height="300px",this._lensContainer.style.zIndex="15000",this._lensContainer.style.position="absolute",this._lensContainer.style.pointerEvents="none",this._lensContainer.style.visibility="hidden",this._lensCanvas=document.createElement("canvas"),this._lensCanvas.id=`${this._lensContainerId}-canvas`,this._lensCanvas.style.borderRadius="50%",this._lensCanvas.style.width="300px",this._lensCanvas.style.height="300px",this._lensCanvas.style.zIndex="15000",this._lensCanvas.style.pointerEvents="none",document.body.appendChild(this._lensContainer),this._lensContainer.appendChild(this._lensCanvas),this._lensCanvasContext=this._lensCanvas.getContext("2d"),this._canvasElement=this.viewer.scene.canvas.canvas,this._canvasPos=null,this._snappedCanvasPos=null,this._lensPosToggle=t.lensPosToggle||!0,this._lensPosToggleAmount=t.lensPosToggleAmount||85,this._lensPosMarginLeft=t.lensPosMarginLeft||85,this._lensPosMarginTop=t.lensPosMarginTop||25,this._lensContainer.style.marginTop=`${this._lensPosMarginTop}px`,this._lensContainer.style.marginLeft=`${this._lensPosMarginLeft}px`,this._zoomLevel=t.zoomLevel||2,this._active=!1!==t.active,this._visible=!1,this._snapped=!1,this._onViewerRendering=this.viewer.scene.on("rendering",(()=>{this._active&&this._visible&&this.update()}))}update(){if(!this._active||!this._visible)return;if(!this._canvasPos)return;const e=this._lensContainer.getBoundingClientRect(),t=this._canvasElement.getBoundingClientRect(),i=this._canvasPos[0]e.left&&this._canvasPos[1]e.top;this._lensContainer.style.marginLeft=`${this._lensPosMarginLeft}px`,i&&(this._lensPosToggle?this._lensContainer.style.marginTop=t.bottom-t.top-this._lensCanvas.height-this._lensPosToggleAmount+"px":this._lensContainer.style.marginTop=`${this._lensPosMarginTop}px`,this._lensPosToggle=!this._lensPosToggle),this._lensCanvasContext.clearRect(0,0,this._lensCanvas.width,this._lensCanvas.height);const s=Math.max(this._lensCanvas.width,this._lensCanvas.height)/this._zoomLevel;this._lensCanvasContext.drawImage(this._canvasElement,this._canvasPos[0]-s/2,this._canvasPos[1]-s/2,s,s,0,0,this._lensCanvas.width,this._lensCanvas.height);const r=[(e.left+e.right)/2-t.left,(e.top+e.bottom)/2-t.top];if(this._snappedCanvasPos){const e=this._snappedCanvasPos[0]-this._canvasPos[0],t=this._snappedCanvasPos[1]-this._canvasPos[1];this._lensCursorDiv.style.marginLeft=r[0]+e*this._zoomLevel-10+"px",this._lensCursorDiv.style.marginTop=r[1]+t*this._zoomLevel-10+"px"}else this._lensCursorDiv.style.marginLeft=r[0]-10+"px",this._lensCursorDiv.style.marginTop=r[1]-10+"px"}set zoomFactor(e){this._zoomFactor=e,this.update()}get zoomFactor(){return this._zoomFactor}set canvasPos(e){this._canvasPos=e,this.update()}get canvasPos(){return this._canvasPos}set snappedCanvasPos(e){this._snappedCanvasPos=e,this.update()}get snappedCanvasPos(){return this._snappedCanvasPos}set snapped(e){this._snapped=e,e?(this._lensCursorDiv.style.background="greenyellow",this._lensCursorDiv.style.border="2px solid green"):(this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red")}get snapped(){return this._snapped}set active(e){this._active=e,this._lensContainer.style.visibility=e&&this._visible?"visible":"hidden",e&&this._visible||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}get active(){return this._active}set visible(e){this._visible=e,this._lensContainer.style.visibility=e&&this._active?"visible":"hidden",e&&this._active||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}get visible(){return this._visible}destroy(){this._destroyed||(this.viewer.scene.off(this._onViewerRendering),this._lensContainer.removeChild(this._lensCanvas),document.body.removeChild(this._lensContainer),this._destroyed=!0)}}let a=!0,l=a?Float64Array:Float32Array;const A=new l(3),h=new l(16),c=new l(16),u=new l(4),d={setDoublePrecisionEnabled(e){a=e,l=a?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>a,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new l(e||2),vec3:e=>new l(e||3),vec4:e=>new l(e||4),mat3:e=>new l(e||9),mat3ToMat4:(e,t=new l(16))=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t),mat4:e=>new l(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,i){const s=new l(2);for(let r=0,o=e.length;r{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,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(ee[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i),addVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i),addVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i),addVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i),subVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i),subVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i),subVec2:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i),geometricMeanVec2(...e){const t=new l(e[0]);for(let i=1;i(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i),subScalarVec4:(e,t,i)=>(i||(i=e),i[0]=t-e[0],i[1]=t-e[1],i[2]=t-e[2],i[3]=t-e[3],i),mulVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]*t[0],i[1]=e[1]*t[1],i[2]=e[2]*t[2],i[3]=e[3]*t[3],i),mulVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i),mulVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i),mulVec2Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i),divVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i),divVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i[3]=e[3]/t[3],i),divScalarVec3:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i),divVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i),divVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i[3]=e[3]/t,i),divScalarVec4:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i[3]=e/t[3],i),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const i=e[0],s=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[s*a-r*n,r*o-i*a,i*n-s*o,0]},cross3Vec3(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return i[0]=r*l-o*a,i[1]=o*n-s*l,i[2]=s*a-r*n,i},sqLenVec4:e=>d.dotVec4(e,e),lenVec4:e=>Math.sqrt(d.sqLenVec4(e)),dotVec3:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],dotVec2:(e,t)=>e[0]*t[0]+e[1]*t[1],sqLenVec3:e=>d.dotVec3(e,e),sqLenVec2:e=>d.dotVec2(e,e),lenVec3:e=>Math.sqrt(d.sqLenVec3(e)),distVec3:(()=>{const e=new l(3);return(t,i)=>d.lenVec3(d.subVec3(t,i,e))})(),lenVec2:e=>Math.sqrt(d.sqLenVec2(e)),distVec2:(()=>{const e=new l(2);return(t,i)=>d.lenVec2(d.subVec2(t,i,e))})(),rcpVec3:(e,t)=>d.divScalarVec3(1,e,t),normalizeVec4(e,t){const i=1/d.lenVec4(e);return d.mulVec4Scalar(e,i,t)},normalizeVec3(e,t){const i=1/d.lenVec3(e);return d.mulVec3Scalar(e,i,t)},normalizeVec2(e,t){const i=1/d.lenVec2(e);return d.mulVec2Scalar(e,i,t)},angleVec3(e,t){let i=d.dotVec3(e,t)/Math.sqrt(d.sqLenVec3(e)*d.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:(()=>{const e=new l(3);return(t,i)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=d.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=d.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=d.lenVec3(e),i)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let i=0,s=(t=Array.prototype.slice.call(t)).length;i({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||d.vec3())[0]=e.x,t[1]=e.y,t[2]=e.z,t),dupMat4:e=>e.slice(0,16),mat4To3:e=>[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]],m4s:e=>[e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e],setMat4ToZeroes:()=>d.m4s(0),setMat4ToOnes:()=>d.m4s(1),diagonalMat4v:e=>new l([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,i,s)=>d.diagonalMat4v([e,t,i,s]),diagonalMat4s:e=>d.diagonalMat4c(e,e,e,e),identityMat4:(e=new l(16))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e),identityMat3:(e=new l(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i),addMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i),addScalarMat4:(e,t,i)=>d.addMat4Scalar(t,e,i),subMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i),subMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i),subScalarMat4:(e,t,i)=>(i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i),mulMat4(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],A=e[6],h=e[7],c=e[8],u=e[9],d=e[10],p=e[11],f=e[12],g=e[13],m=e[14],_=e[15],v=t[0],b=t[1],y=t[2],x=t[3],B=t[4],w=t[5],P=t[6],C=t[7],M=t[8],E=t[9],F=t[10],I=t[11],D=t[12],S=t[13],T=t[14],R=t[15];return i[0]=v*s+b*a+y*c+x*f,i[1]=v*r+b*l+y*u+x*g,i[2]=v*o+b*A+y*d+x*m,i[3]=v*n+b*h+y*p+x*_,i[4]=B*s+w*a+P*c+C*f,i[5]=B*r+w*l+P*u+C*g,i[6]=B*o+w*A+P*d+C*m,i[7]=B*n+w*h+P*p+C*_,i[8]=M*s+E*a+F*c+I*f,i[9]=M*r+E*l+F*u+I*g,i[10]=M*o+E*A+F*d+I*m,i[11]=M*n+E*h+F*p+I*_,i[12]=D*s+S*a+T*c+R*f,i[13]=D*r+S*l+T*u+R*g,i[14]=D*o+S*A+T*d+R*m,i[15]=D*n+S*h+T*p+R*_,i},mulMat3(e,t,i){i||(i=new l(9));const s=e[0],r=e[3],o=e[6],n=e[1],a=e[4],A=e[7],h=e[2],c=e[5],u=e[8],d=t[0],p=t[3],f=t[6],g=t[1],m=t[4],_=t[7],v=t[2],b=t[5],y=t[8];return i[0]=s*d+r*g+o*v,i[3]=s*p+r*m+o*b,i[6]=s*f+r*_+o*y,i[1]=n*d+a*g+A*v,i[4]=n*p+a*m+A*b,i[7]=n*f+a*_+A*y,i[2]=h*d+c*g+u*v,i[5]=h*p+c*m+u*b,i[8]=h*f+c*_+u*y,i},mulMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i),mulMat4v4(e,t,i=d.vec4()){const s=t[0],r=t[1],o=t[2],n=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*n,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*n,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*n,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*n,i},transposeMat4(e,t){const i=e[4],s=e[14],r=e[8],o=e[13],n=e[12],a=e[9];if(!t||e===t){const t=e[1],l=e[2],A=e[3],h=e[6],c=e[7],u=e[11];return e[1]=i,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=h,e[11]=s,e[12]=A,e[13]=c,e[14]=u,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=n,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=o,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4(e){const t=e[0],i=e[1],s=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],A=e[8],h=e[9],c=e[10],u=e[11],d=e[12],p=e[13],f=e[14],g=e[15];return d*h*a*r-A*p*a*r-d*n*c*r+o*p*c*r+A*n*f*r-o*h*f*r-d*h*s*l+A*p*s*l+d*i*c*l-t*p*c*l-A*i*f*l+t*h*f*l+d*n*s*u-o*p*s*u-d*i*a*u+t*p*a*u+o*i*f*u-t*n*f*u-A*n*s*g+o*h*s*g+A*i*a*g-t*h*a*g-o*i*c*g+t*n*c*g},inverseMat4(e,t){t||(t=e);const i=e[0],s=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],A=e[7],h=e[8],c=e[9],u=e[10],d=e[11],p=e[12],f=e[13],g=e[14],m=e[15],_=i*a-s*n,v=i*l-r*n,b=i*A-o*n,y=s*l-r*a,x=s*A-o*a,B=r*A-o*l,w=h*f-c*p,P=h*g-u*p,C=h*m-d*p,M=c*g-u*f,E=c*m-d*f,F=u*m-d*g,I=1/(_*F-v*E+b*M+y*C-x*P+B*w);return t[0]=(a*F-l*E+A*M)*I,t[1]=(-s*F+r*E-o*M)*I,t[2]=(f*B-g*x+m*y)*I,t[3]=(-c*B+u*x-d*y)*I,t[4]=(-n*F+l*C-A*P)*I,t[5]=(i*F-r*C+o*P)*I,t[6]=(-p*B+g*b-m*v)*I,t[7]=(h*B-u*b+d*v)*I,t[8]=(n*E-a*C+A*w)*I,t[9]=(-i*E+s*C-o*w)*I,t[10]=(p*x-f*b+m*_)*I,t[11]=(-h*x+c*b-d*_)*I,t[12]=(-n*M+a*P-l*w)*I,t[13]=(i*M-s*P+r*w)*I,t[14]=(-p*y+f*v-g*_)*I,t[15]=(h*y-c*v+u*_)*I,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const i=t||d.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v(e,t){const i=t||d.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(()=>{const e=new l(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,d.translationMat4v(e,r))})(),translationMat4s:(e,t)=>d.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>d.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,i,s){const r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;const o=s[7];s[4]+=o*e,s[5]+=o*t,s[6]+=o*i;const n=s[11];s[8]+=n*e,s[9]+=n*t,s[10]+=n*i;const a=s[15];return s[12]+=a*e,s[13]+=a*t,s[14]+=a*i,s},setMat4Translation:(e,t,i)=>(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i),rotationMat4v(e,t,i){const s=d.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=s[0],l=s[1],A=s[2];let h,c,u,p,f,g;return h=a*l,c=l*A,u=A*a,p=a*r,f=l*r,g=A*r,(i=i||d.mat4())[0]=n*a*a+o,i[1]=n*h+g,i[2]=n*u-f,i[3]=0,i[4]=n*h-g,i[5]=n*l*l+o,i[6]=n*c+p,i[7]=0,i[8]=n*u+f,i[9]=n*c-p,i[10]=n*A*A+o,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:(e,t,i,s,r)=>d.rotationMat4v(e,[t,i,s],r),scalingMat4v:(e,t=d.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=d.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new l(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,d.scalingMat4v(e,r))})(),scaleMat4c:(e,t,i,s)=>(s[0]*=e,s[4]*=t,s[8]*=i,s[1]*=e,s[5]*=t,s[9]*=i,s[2]*=e,s[6]*=t,s[10]*=i,s[3]*=e,s[7]*=t,s[11]*=i,s),scaleMat4v(e,t){const i=e[0],s=e[1],r=e[2];return t[0]*=i,t[4]*=s,t[8]*=r,t[1]*=i,t[5]*=s,t[9]*=r,t[2]*=i,t[6]*=s,t[10]*=r,t[3]*=i,t[7]*=s,t[11]*=r,t},scalingMat4s:e=>d.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,i=d.mat4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=s+s,l=r+r,A=o+o,h=s*a,c=s*l,u=s*A,p=r*l,f=r*A,g=o*A,m=n*a,_=n*l,v=n*A;return i[0]=1-(p+g),i[1]=c+v,i[2]=u-_,i[3]=0,i[4]=c-v,i[5]=1-(h+g),i[6]=f+m,i[7]=0,i[8]=u+_,i[9]=f-m,i[10]=1-(h+p),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler(e,t,i=d.vec4()){const s=d.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],A=e[9],h=e[2],c=e[6],u=e[10];return"XYZ"===t?(i[1]=Math.asin(s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(-A,u),i[2]=Math.atan2(-o,r)):(i[0]=Math.atan2(c,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(A,-1,1)),Math.abs(A)<.99999?(i[1]=Math.atan2(n,u),i[2]=Math.atan2(a,l)):(i[1]=Math.atan2(-h,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(c,-1,1)),Math.abs(c)<.99999?(i[1]=Math.atan2(-h,u),i[2]=Math.atan2(-o,l)):(i[1]=0,i[2]=Math.atan2(a,r))):"ZYX"===t?(i[1]=Math.asin(-s(h,-1,1)),Math.abs(h)<.99999?(i[0]=Math.atan2(c,u),i[2]=Math.atan2(a,r)):(i[0]=0,i[2]=Math.atan2(-o,l))):"YZX"===t?(i[2]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-A,l),i[1]=Math.atan2(-h,r)):(i[0]=0,i[1]=Math.atan2(n,u))):"XZY"===t&&(i[2]=Math.asin(-s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(c,l),i[1]=Math.atan2(n,r)):(i[0]=Math.atan2(-A,u),i[1]=0)),i},composeMat4:(e,t,i,s=d.mat4())=>(d.quaternionToRotationMat4(t,s),d.scaleMat4v(i,s),d.translateMat4v(e,s),s),decomposeMat4:(()=>{const e=new l(3),t=new l(16);return function(i,s,r,o){e[0]=i[0],e[1]=i[1],e[2]=i[2];let n=d.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];const a=d.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];const l=d.lenVec3(e);d.determinantMat4(i)<0&&(n=-n),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);const A=1/n,h=1/a,c=1/l;return t[0]*=A,t[1]*=A,t[2]*=A,t[4]*=h,t[5]*=h,t[6]*=h,t[8]*=c,t[9]*=c,t[10]*=c,d.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v(e,t,i,s){s||(s=d.mat4());const r=e[0],o=e[1],n=e[2],a=i[0],l=i[1],A=i[2],h=t[0],c=t[1],u=t[2];if(r===h&&o===c&&n===u)return d.identityMat4();let p,f,g,m,_,v,b,y,x,B;return p=r-h,f=o-c,g=n-u,B=1/Math.sqrt(p*p+f*f+g*g),p*=B,f*=B,g*=B,m=l*g-A*f,_=A*p-a*g,v=a*f-l*p,B=Math.sqrt(m*m+_*_+v*v),B?(B=1/B,m*=B,_*=B,v*=B):(m=0,_=0,v=0),b=f*v-g*_,y=g*m-p*v,x=p*_-f*m,B=Math.sqrt(b*b+y*y+x*x),B?(B=1/B,b*=B,y*=B,x*=B):(b=0,y=0,x=0),s[0]=m,s[1]=b,s[2]=p,s[3]=0,s[4]=_,s[5]=y,s[6]=f,s[7]=0,s[8]=v,s[9]=x,s[10]=g,s[11]=0,s[12]=-(m*r+_*o+v*n),s[13]=-(b*r+y*o+x*n),s[14]=-(p*r+f*o+g*n),s[15]=1,s},lookAtMat4c:(e,t,i,s,r,o,n,a,l)=>d.lookAtMat4v([e,t,i],[s,r,o],[n,a,l],[]),orthoMat4c(e,t,i,s,r,o,n){n||(n=d.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2/l,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=-2/A,n[11]=0,n[12]=-(e+t)/a,n[13]=-(s+i)/l,n[14]=-(o+r)/A,n[15]=1,n},frustumMat4v(e,t,i){i||(i=d.mat4());const s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];d.addVec4(r,s,h),d.subVec4(r,s,c);const o=2*s[2],n=c[0],a=c[1],l=c[2];return i[0]=o/n,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=o/a,i[6]=0,i[7]=0,i[8]=h[0]/n,i[9]=h[1]/a,i[10]=-h[2]/l,i[11]=-1,i[12]=0,i[13]=0,i[14]=-o*r[2]/l,i[15]=0,i},frustumMat4(e,t,i,s,r,o,n){n||(n=d.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2*r/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2*r/l,n[6]=0,n[7]=0,n[8]=(t+e)/a,n[9]=(s+i)/l,n[10]=-(o+r)/A,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/A,n[15]=0,n},perspectiveMat4(e,t,i,s,r){const o=[],n=[];return o[2]=i,n[2]=s,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],d.frustumMat4v(o,n,r)},compareMat4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15],transformPoint3(e,t,i=d.vec3()){const s=t[0],r=t[1],o=t[2];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12],i[1]=e[1]*s+e[5]*r+e[9]*o+e[13],i[2]=e[2]*s+e[6]*r+e[10]*o+e[14],i},transformPoint4:(e,t,i=d.vec4())=>(i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i),transformPoints3(e,t,i){const s=i||[],r=t.length;let o,n,a,l;const A=e[0],h=e[1],c=e[2],u=e[3],d=e[4],p=e[5],f=e[6],g=e[7],m=e[8],_=e[9],v=e[10],b=e[11],y=e[12],x=e[13],B=e[14],w=e[15];let P;for(let e=0;e{const e=new l(16),t=new l(16),i=new l(16);return function(s,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),i),s,n)}})(),lerpVec3(e,t,i,s,r,o){const n=o||d.vec3(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n},lerpMat4(e,t,i,s,r,o){const n=o||d.mat4(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n[3]=s[3]+a*(r[3]-s[3]),n[4]=s[4]+a*(r[4]-s[4]),n[5]=s[5]+a*(r[5]-s[5]),n[6]=s[6]+a*(r[6]-s[6]),n[7]=s[7]+a*(r[7]-s[7]),n[8]=s[8]+a*(r[8]-s[8]),n[9]=s[9]+a*(r[9]-s[9]),n[10]=s[10]+a*(r[10]-s[10]),n[11]=s[11]+a*(r[11]-s[11]),n[12]=s[12]+a*(r[12]-s[12]),n[13]=s[13]+a*(r[13]-s[13]),n[14]=s[14]+a*(r[14]-s[14]),n[15]=s[15]+a*(r[15]-s[15]),n},flatten(e){const t=[];let i,s,r,o,n;for(i=0,s=e.length;i(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,i=d.vec4()){const s=e[0]*d.DEGTORAD/2,r=e[1]*d.DEGTORAD/2,o=e[2]*d.DEGTORAD/2,n=Math.cos(s),a=Math.cos(r),l=Math.cos(o),A=Math.sin(s),h=Math.sin(r),c=Math.sin(o);return"XYZ"===t?(i[0]=A*a*l+n*h*c,i[1]=n*h*l-A*a*c,i[2]=n*a*c+A*h*l,i[3]=n*a*l-A*h*c):"YXZ"===t?(i[0]=A*a*l+n*h*c,i[1]=n*h*l-A*a*c,i[2]=n*a*c-A*h*l,i[3]=n*a*l+A*h*c):"ZXY"===t?(i[0]=A*a*l-n*h*c,i[1]=n*h*l+A*a*c,i[2]=n*a*c+A*h*l,i[3]=n*a*l-A*h*c):"ZYX"===t?(i[0]=A*a*l-n*h*c,i[1]=n*h*l+A*a*c,i[2]=n*a*c-A*h*l,i[3]=n*a*l+A*h*c):"YZX"===t?(i[0]=A*a*l+n*h*c,i[1]=n*h*l+A*a*c,i[2]=n*a*c-A*h*l,i[3]=n*a*l-A*h*c):"XZY"===t&&(i[0]=A*a*l-n*h*c,i[1]=n*h*l-A*a*c,i[2]=n*a*c+A*h*l,i[3]=n*a*l+A*h*c),i},mat4ToQuaternion(e,t=d.vec4()){const i=e[0],s=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],A=e[6],h=e[10];let c;const u=i+n+h;return u>0?(c=.5/Math.sqrt(u+1),t[3]=.25/c,t[0]=(A-a)*c,t[1]=(r-l)*c,t[2]=(o-s)*c):i>n&&i>h?(c=2*Math.sqrt(1+i-n-h),t[3]=(A-a)/c,t[0]=.25*c,t[1]=(s+o)/c,t[2]=(r+l)/c):n>h?(c=2*Math.sqrt(1+n-i-h),t[3]=(r-l)/c,t[0]=(s+o)/c,t[1]=.25*c,t[2]=(a+A)/c):(c=2*Math.sqrt(1+h-i-n),t[3]=(o-s)/c,t[0]=(r+l)/c,t[1]=(a+A)/c,t[2]=.25*c),t},vec3PairToQuaternion(e,t,i=d.vec4()){const s=Math.sqrt(d.dotVec3(e,e)*d.dotVec3(t,t));let r=s+d.dotVec3(e,t);return r<1e-8*s?(r=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):d.cross3Vec3(e,t,i),i[3]=r,d.normalizeQuaternion(i)},angleAxisToQuaternion(e,t=d.vec4()){const i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:(()=>{const e=new l(16);return(t,i,s)=>(s=s||d.vec3(),d.quaternionToRotationMat4(t,e),d.mat4ToEuler(e,i,s),s)})(),mulQuaternions(e,t,i=d.vec4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],A=t[2],h=t[3];return i[0]=n*a+s*h+r*A-o*l,i[1]=n*l+r*h+o*a-s*A,i[2]=n*A+o*h+s*l-r*a,i[3]=n*h-s*a-r*l-o*A,i},vec3ApplyQuaternion(e,t,i=d.vec3()){const s=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],A=e[3],h=A*s+a*o-l*r,c=A*r+l*s-n*o,u=A*o+n*r-a*s,p=-n*s-a*r-l*o;return i[0]=h*A+p*-n+c*-l-u*-a,i[1]=c*A+p*-a+u*-n-h*-l,i[2]=u*A+p*-l+h*-a-c*-n,i},quaternionToMat4(e,t){t=d.identityMat4(t);const i=e[0],s=e[1],r=e[2],o=e[3],n=2*i,a=2*s,l=2*r,A=n*o,h=a*o,c=l*o,u=n*i,p=a*i,f=l*i,g=a*s,m=l*s,_=l*r;return t[0]=1-(g+_),t[1]=p+c,t[2]=f-h,t[4]=p-c,t[5]=1-(u+_),t[6]=m+A,t[8]=f+h,t[9]=m-A,t[10]=1-(u+g),t},quaternionToRotationMat4(e,t){const i=e[0],s=e[1],r=e[2],o=e[3],n=i+i,a=s+s,l=r+r,A=i*n,h=i*a,c=i*l,u=s*a,d=s*l,p=r*l,f=o*n,g=o*a,m=o*l;return t[0]=1-(u+p),t[4]=h-m,t[8]=c+g,t[1]=h+m,t[5]=1-(A+p),t[9]=d-f,t[2]=c-g,t[6]=d+f,t[10]=1-(A+u),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const i=d.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>d.normalizeQuaternion(d.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=d.vec4()){const i=(e=d.normalizeQuaternion(e,u))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:e=>new l(e||6),AABB2:e=>new l(e||4),OBB3:e=>new l(e||32),OBB2:e=>new l(e||16),Sphere3:(e,t,i,s)=>new l([e,t,i,s]),transformOBB3(e,t,i=t){let s;const r=t.length;let o,n,a;const l=e[0],A=e[1],h=e[2],c=e[3],u=e[4],d=e[5],p=e[6],f=e[7],g=e[8],m=e[9],_=e[10],v=e[11],b=e[12],y=e[13],x=e[14],B=e[15];for(s=0;s{const e=new l(3),t=new l(3),i=new l(3);return s=>(e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5],d.subVec3(t,e,i),Math.abs(d.lenVec3(i)))})(),getAABB3DiagPoint:(()=>{const e=new l(3),t=new l(3),i=new l(3);return(s,r)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5];const o=d.subVec3(t,e,i),n=r[0]-s[0],a=s[3]-r[0],l=r[1]-s[1],A=s[4]-r[1],h=r[2]-s[2],c=s[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>A?l:A,o[2]+=h>c?h:c,Math.abs(d.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const i=t||d.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center(e,t){const i=t||d.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:(e=d.AABB3())=>(e[0]=d.MAX_DOUBLE,e[1]=d.MAX_DOUBLE,e[2]=d.MAX_DOUBLE,e[3]=d.MIN_DOUBLE,e[4]=d.MIN_DOUBLE,e[5]=d.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=d.OBB3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t),positions3ToAABB3:(()=>{const e=new l(3);return(t,i,s)=>{i=i||d.AABB3();let r,o,n,a=d.MAX_DOUBLE,l=d.MAX_DOUBLE,A=d.MAX_DOUBLE,h=d.MIN_DOUBLE,c=d.MIN_DOUBLE,u=d.MIN_DOUBLE;for(let i=0,p=t.length;ih&&(h=r),o>c&&(c=o),n>u&&(u=n);return i[0]=a,i[1]=l,i[2]=A,i[3]=h,i[4]=c,i[5]=u,i}})(),OBB3ToAABB3(e,t=d.AABB3()){let i,s,r,o=d.MAX_DOUBLE,n=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MIN_DOUBLE,A=d.MIN_DOUBLE,h=d.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToAABB3(e,t=d.AABB3()){let i,s,r,o=d.MAX_DOUBLE,n=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MIN_DOUBLE,A=d.MIN_DOUBLE,h=d.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToSphere3:(()=>{const e=new l(3);return(t,i)=>{i=i||d.vec4();let s,r=0,o=0,n=0;const a=t.length;for(s=0;sA&&(A=l);return i[3]=A,i}})(),positions3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(i,s)=>{s=s||d.vec4();let r,o=0,n=0,a=0;const l=i.length;let A=0;for(r=0;rA&&(A=c);return s[3]=A,s}})(),OBB3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(i,s)=>{s=s||d.vec4();let r,o=0,n=0,a=0;const l=i.length,A=l/4;for(r=0;rc&&(c=h);return s[3]=c,s}})(),getSphere3Center:(e,t=d.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=d.vec3()){let i=0,s=0,r=0;for(var o=0,n=e.length;o(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3](e[0]=d.MAX_DOUBLE,e[1]=d.MAX_DOUBLE,e[2]=d.MIN_DOUBLE,e[3]=d.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]e[0]<=t[0]&&e[3]>=t[0]&&e[1]<=t[1]&&e[4]>=t[1]&&e[2]<=t[2]&&e[5]>=t[2],planeAABB3Intersect(e,t,i){let s,r;e[0]>0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]);if(s<=-t&&r<=-t)return-1;return s>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=d.AABB2()){let i,s,r,o,n=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MIN_DOUBLE,A=d.MIN_DOUBLE;for(let t=0,h=e.length;tl&&(l=i),s>A&&(A=s);return t[0]=n,t[1]=a,t[2]=l,t[3]=A,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]2*(1-e)*(i-t)+2*e*(s-i),tangentQuadraticBezier3:(e,t,i,s,r)=>-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r,tangentSpline:e=>6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e),catmullRomInterpolate(e,t,i,s,r){const o=.5*(i-e),n=.5*(s-t),a=r*r;return(2*t-2*i+o+n)*(r*a)+(-3*t+3*i-2*o-n)*a+o*r+t},b2p0(e,t){const i=1-e;return i*i*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0(e,t){const i=1-e;return i*i*i*t},b3p1(e,t){const i=1-e;return 3*i*i*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal(e,t,i,s=d.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=i[0]-e[0],l=i[1]-e[1],A=i[2]-e[2],h=o*A-n*l,c=n*a-r*A,u=r*l-o*a,p=Math.sqrt(h*h+c*c+u*u);return 0===p?(s[0]=0,s[1]=0,s[2]=0):(s[0]=h/p,s[1]=c/p,s[2]=u/p),s},rayTriangleIntersect:(()=>{const e=new l(3),t=new l(3),i=new l(3),s=new l(3),r=new l(3);return(o,n,a,l,A,h)=>{h=h||d.vec3();const c=d.subVec3(l,a,e),u=d.subVec3(A,a,t),p=d.cross3Vec3(n,u,i),f=d.dotVec3(c,p);if(f<1e-6)return null;const g=d.subVec3(o,a,s),m=d.dotVec3(g,p);if(m<0||m>f)return null;const _=d.cross3Vec3(g,c,r),v=d.dotVec3(n,_);if(v<0||m+v>f)return null;const b=d.dotVec3(u,_)/f;return h[0]=o[0]+b*n[0],h[1]=o[1]+b*n[1],h[2]=o[2]+b*n[2],h}})(),rayPlaneIntersect:(()=>{const e=new l(3),t=new l(3),i=new l(3),s=new l(3);return(r,o,n,a,l,A)=>{A=A||d.vec3(),o=d.normalizeVec3(o,e);const h=d.subVec3(a,n,t),c=d.subVec3(l,n,i),u=d.cross3Vec3(h,c,s);d.normalizeVec3(u,u);const p=-d.dotVec3(n,u),f=-(d.dotVec3(r,u)+p)/d.dotVec3(o,u);return A[0]=r[0]+f*o[0],A[1]=r[1]+f*o[1],A[2]=r[2]+f*o[2],A}})(),cartesianToBarycentric:(()=>{const e=new l(3),t=new l(3),i=new l(3);return(s,r,o,n,a)=>{const l=d.subVec3(n,r,e),A=d.subVec3(o,r,t),h=d.subVec3(s,r,i),c=d.dotVec3(l,l),u=d.dotVec3(l,A),p=d.dotVec3(l,h),f=d.dotVec3(A,A),g=d.dotVec3(A,h),m=c*f-u*u;if(0===m)return null;const _=1/m,v=(f*p-u*g)*_,b=(c*g-u*p)*_;return a[0]=1-v-b,a[1]=b,a[2]=v,a}})(),barycentricInsideTriangle(e){const t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian(e,t,i,s,r=d.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+i[0]*n+s[0]*a,r[1]=t[1]*o+i[1]*n+s[1]*a,r[2]=t[2]*o+i[2]*n+s[2]*a,r},mergeVertices(e,t,i,s){const r={},o=[],n=[],a=t?[]:null,l=i?[]:null,A=[];let h,c,u,d;const p=1e4;let f,g,m=0;for(f=0,g=e.length;f{const e=new l(3),t=new l(3),i=new l(3),s=new l(3),r=new l(3),o=new l(3);return(n,a,l)=>{let A,h;const c=new Array(n.length/3);let u,p,f,g,m,_,v;for(A=0,h=a.length;A{const e=new l(3),t=new l(3),i=new l(3),s=new l(3),r=new l(3),o=new l(3),n=new l(3);return(a,l,A)=>{const h=new Float32Array(a.length);for(let c=0;c>24&255,h=u>>16&255,A=u>>8&255,l=255&u,a=t[i],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+1],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+2],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,i={}){const s=i.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,A,h,c;const u=1e4;let p,f,g,m,_,v;for(f=0,m=e.length;f{const e=new l(4),t=new l(4);return(i,s,r,o,n)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=1,d.transformVec4(i,e,t),o[0]=t[0],o[1]=t[1],o[2]=t[2],e[0]=r[0],e[1]=r[1],e[2]=r[2],d.transformVec3(i,e,t),d.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new l(16),t=new l(4),i=new l(4),s=(t,i,s,r,o)=>{o[0]=t,o[1]=i,o[2]=s,o[3]=1,d.transformVec4(e,o,o),r||d.mulVec4Scalar(o,1/o[3])};return(r,o,n,a,l,A,h)=>{const c="ortho"===a;d.mulMat4(n,o,e),d.inverseMat4(e,e);const u=2*l[0]/r.width-1,p=1-2*l[1]/r.height;s(u,p,-1,c,t),s(u,p,1,c,i),A[0]=t[0],A[1]=t[1],A[2]=t[2],d.subVec3(i,t,h),d.normalizeVec3(h)}})(),canvasPosToLocalRay:(()=>{const e=new l(3),t=new l(3);return(i,s,r,o,n,a,l,A)=>{d.canvasPosToWorldRay(i,s,r,o,a,e,t),d.worldRayToLocalRay(n,e,t,l,A)}})(),worldRayToLocalRay:(()=>{const e=new l(16),t=new l(4),i=new l(4);return(s,r,o,n,a)=>{const l=d.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,d.transformVec4(l,t,i),n[0]=i[0],n[1]=i[1],n[2]=i[2],d.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(i,s,r,o){const n=new l(6),a={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:n};let A,h;for(n[0]=n[1]=n[2]=Number.POSITIVE_INFINITY,n[3]=n[4]=n[5]=Number.NEGATIVE_INFINITY,A=0,h=i.length;An[3]&&(n[3]=r[t]),r[t+1]n[4]&&(n[4]=r[t+1]),r[t+2]n[5]&&(n[5]=r[t+2])}}if(i.length<20||o>10)return a.triangles=i,a.leaf=!0,a;e[0]=n[3]-n[0],e[1]=n[4]-n[1],e[2]=n[5]-n[2];let u=0;e[1]>e[u]&&(u=1),e[2]>e[u]&&(u=2),a.splitDim=u;const d=(n[u]+n[u+3])/2,p=new Array(i.length);let f=0;const g=new Array(i.length);let m=0;for(A=0,h=i.length;A{const s=e.length/3,r=new Array(s);for(let e=0;e=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=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t}};d.buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=d.vec3(),h=d.vec3(),c=d.vec3(),u=d.vec3(),p=d.vec3(),f=d.vec3(),g=d.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;ux)||(T=i[F.index1],R=i[F.index2],(!L&&T>65535||R>65535)&&(L=!0),y.push(T),y.push(R));return L?new Uint32Array(y):new Uint16Array(y)}}(),d.planeClipsPositions3=function(e,t,i,s=3){for(let r=0,o=i.length;r{this._needsRebuild=!0})),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",(e=>{this._needsRebuild=!0}))}get root(){return this._needsRebuild&&this._rebuild(),this._root}_rebuild(){const e=this.viewer.scene;this._root={aabb:e.getAABB()};for(let t in e.objects){const i=e.objects[t];this._insertEntity(this._root,i,1)}this._needsRebuild=!1}_insertEntity(e,t,i){const s=t.aabb;if(i>=this._maxTreeDepth)return e.entities=e.entities||[],void e.entities.push(t);if(e.left&&d.containsAABB3(e.left.aabb,s))return void this._insertEntity(e.left,t,i+1);if(e.right&&d.containsAABB3(e.right.aabb,s))return void this._insertEntity(e.right,t,i+1);const r=e.aabb;p[0]=r[3]-r[0],p[1]=r[4]-r[1],p[2]=r[5]-r[2];let o=0;if(p[1]>p[o]&&(o=1),p[2]>p[o]&&(o=2),!e.left){const n=r.slice();if(n[o+3]=(r[o]+r[o+3])/2,e.left={aabb:n},d.containsAABB3(n,s))return void this._insertEntity(e.left,t,i+1)}if(!e.right){const n=r.slice();if(n[o]=(r[o]+r[o+3])/2,e.right={aabb:n},d.containsAABB3(n,s))return void this._insertEntity(e.right,t,i+1)}e.entities=e.entities||[],e.entities.push(t)}destroy(){const e=this.viewer.scene;e.off(this._onModelLoaded),e.off(this._onModelUnloaded),this._root=null,this._needsRebuild=!0}}class g{constructor(){this._head=[],this._headLength=0,this._tail=[],this._index=0,this._length=0}get length(){return this._length}shift(){if(this._index>=this._headLength){const e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}const e=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,e}push(e){return this._length++,this._tail.push(e),this}unshift(e){return this._head[--this._index]=e,this._length++,this}}const m={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var _=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r{};t=t||s,i=i||s;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var s=e.target.response;if(200===this.status){var r;try{r=JSON.parse(s)}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}t(r)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(s))}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else i(e)}),!1),r.addEventListener("error",(function(e){i(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,i){var s=e=>{};t=t||s,i=i||s;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const e=!!r[2];var o=r[3];o=window.decodeURIComponent(o),e&&(o=window.atob(o));try{const e=new ArrayBuffer(o.length),i=new Uint8Array(e);for(var n=0;n{t(e)}))}catch(e){I.scheduleTask((()=>{i(e)}))}}else{const s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i("loadArrayBuffer error : "+s.response))},s.send(null)}},queryString:b,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"==typeof e&&"number"==typeof e.length},isString:function(e){return"string"==typeof e||e instanceof String},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},isID:function(e){return y.isString(e)||y.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(y.isNumeric(e)||y.isString(e)?`${e}`:e.id)===(y.isNumeric(t)||y.isString(t)?`${t}`:t.id)},isFunction:function(e){return"function"==typeof e},isObject:function(e){const t={}.constructor;return!!e&&e.constructor===t},copy:function(e){return y.apply(e,{})},apply:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t},apply2:function(e,t){for(const i in e)e.hasOwnProperty(i)&&void 0!==e[i]&&null!==e[i]&&(t[i]=e[i]);return t},applyIf:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(void 0!==t[i]&&null!==t[i]||(t[i]=e[i]));return t},isEmptyObject:function(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return y.isNumeric(e)?`${e}`:`'${e}'`},concat:function(e,t){const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},flattenParentChildHierarchy:function(e){var t=[];return function e(i){i.id=i.uuid,delete i.oid,t.push(i);var s=i.children;if(s)for(var r=0,o=s.length;r{B.removeItem(e.id),delete I.scenes[e.id],delete x[e.id],m.components.scenes--}))},this.clear=function(){let e;for(const t in I.scenes)I.scenes.hasOwnProperty(t)&&(e=I.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete I.scenes[e.id]))},this.scheduleTask=function(e,t=null){w.push(e),w.push(t)},this.runTasks=function(e=-1){let t,i,s=(new Date).getTime(),r=0;for(;w.length>0&&(e<0||s0&&M>0){var t=1e3/M;F+=t,C.push(t),C.length>=30&&(F-=C.shift()),m.frame.fps=Math.round(F/C.length)}for(let e in I.scenes)I.scenes[e].compile();T(e),E=e};!function(e,t){let i=Date.now()+t;(function s(){const r=Date.now()-i;e(),i+=t,setTimeout(s,Math.max(0,t-r))})()}((()=>{D()}),100);const S=function(){let e=Date.now();if(M=e-E,E>0&&M>0){var t=1e3/M;F+=t,C.push(t),C.length>=30&&(F-=C.shift()),m.frame.fps=Math.round(F/C.length)}T(e),function(e){for(var t in P.time=e,I.scenes)if(I.scenes.hasOwnProperty(t)){var i=I.scenes[t];P.sceneId=t,P.startTime=i.startTime,P.deltaTime=null!=P.prevTime?P.time-P.prevTime:0,i.fire("tick",P,!0)}P.prevTime=e}(e),function(){const e=I.scenes,t=!1;let i,s,r,o,n;for(n in e)e.hasOwnProperty(n)&&(i=e[n],s=x[n],s||(s=x[n]={}),r=i.ticksPerOcclusionTest,s.ticksPerOcclusionTest!==r&&(s.ticksPerOcclusionTest=r,s.renderCountdown=r),--i.occlusionTestCountdown<=0&&(i.doOcclusionTest(),i.occlusionTestCountdown=r),o=i.ticksPerRender,s.ticksPerRender!==o&&(s.ticksPerRender=o,s.renderCountdown=o),0==--s.renderCountdown&&(i.render(t),s.renderCountdown=o))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(D):requestAnimationFrame(S)};function T(e){const t=I.runTasks(e+10),i=I.getNumTasks();m.frame.tasksRun=t,m.frame.tasksScheduled=i,m.frame.tasksBudget=10}S();class R{get type(){return"Component"}get isComponent(){return!0}constructor(e=null,t={}){if(this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=t.viewer;else{if("Scene"===e.type)this.scene=e;else{if(!(e instanceof R))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+y.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let i=e.component;const s=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(i&&(y.isNumeric(i)||y.isString(i))){const e=i;if(i=this.scene.components[e],!i)return void this.error("Component not found: "+y.inQuotes(e))}if(!i)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){i=e[t];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&(i=this.scene[t],!i))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+y.inQuotes(i.id));if(o&&!i.isType(o))return void this.error("Expected a "+o+" type or subtype: "+i.type+" "+y.inQuotes(i.id))}this._attachments||(this._attachments={});const l=this._attached[t];let A,h,c;if(l){if(i&&l.id===i.id)return;const e=this._attachments[l.id];for(A=e.subs,h=0,c=A.length;h{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():I.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}scheduleTask(e){I.scheduleTask(e,null)}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,i,s,r,o;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(t=this._attachments[e],i=t.component,s=t.subs,r=0,o=s.length;r=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class N{constructor(){this.planes=[new O,new O,new O,new O,new O,new O]}}function Q(e,t,i){const s=d.mulMat4(i,t,k),r=s[0],o=s[1],n=s[2],a=s[3],l=s[4],A=s[5],h=s[6],c=s[7],u=s[8],p=s[9],f=s[10],g=s[11],m=s[12],_=s[13],v=s[14],b=s[15];e.planes[0].set(a-r,c-l,g-u,b-m),e.planes[1].set(a+r,c+l,g+u,b+m),e.planes[2].set(a-o,c-A,g-p,b-_),e.planes[3].set(a+o,c+A,g+p,b+_),e.planes[4].set(a-n,c-h,g-f,b-v),e.planes[5].set(a+n,c+h,g+f,b+v)}function V(e,t){let i=N.INSIDE;const s=L,r=U;s[0]=t[0],s[1]=t[1],s[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[s,r];for(let t=0;t<6;++t){const s=e.planes[t];if(s.normal[0]*o[s.testVertex[0]][0]+s.normal[1]*o[s.testVertex[1]][1]+s.normal[2]*o[s.testVertex[2]][2]+s.offset<0)return N.OUTSIDE;s.normal[0]*o[1-s.testVertex[0]][0]+s.normal[1]*o[1-s.testVertex[1]][1]+s.normal[2]*o[1-s.testVertex[2]][2]+s.offset<0&&(i=N.INTERSECT)}return i}N.INSIDE=0,N.INTERSECT=1,N.OUTSIDE=2;class H extends R{constructor(e={}){if(!e.viewer)throw"[MarqueePicker] Missing config: viewer";if(!e.objectsKdTree3)throw"[MarqueePicker] Missing config: objectsKdTree3";super(e.viewer.scene,e),this.viewer=e.viewer,this._objectsKdTree3=e.objectsKdTree3,this._canvasMarqueeCorner1=d.vec2(),this._canvasMarqueeCorner2=d.vec2(),this._canvasMarquee=d.AABB2(),this._marqueeFrustum=new N,this._marqueeFrustumProjMat=d.mat4(),this._pickMode=!1,this._marqueeElement=document.createElement("div"),document.body.appendChild(this._marqueeElement),this._marqueeElement.style.position="absolute",this._marqueeElement.style["z-index"]="40000005",this._marqueeElement.style.width="8px",this._marqueeElement.style.height="8px",this._marqueeElement.style.visibility="hidden",this._marqueeElement.style.top="0px",this._marqueeElement.style.left="0px",this._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",this._marqueeElement.style.opacity=1,this._marqueeElement.style["pointer-events"]="none"}setMarqueeCorner1(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarqueeCorner2(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarquee(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}setMarqueeVisible(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}getMarqueeVisible(){return this._marqueVisible}setPickMode(e){if(e!==H.PICK_MODE_INSIDE&&e!==H.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===H.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}getPickMode(){return this._pickMode}clear(){this.fire("clear",{})}pick(){this._updateMarquee(),this._buildMarqueeFrustum();const e=[],t=(i,s=N.INTERSECT)=>{if(s===N.INTERSECT&&(s=V(this._marqueeFrustum,i.aabb)),s!==N.OUTSIDE){if(i.entities){const t=i.entities;for(let i=0,s=t.length;i3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&t(this._objectsKdTree3.root),this.fire("picked",e),e}_updateMarquee(){this._canvasMarquee[0]=Math.min(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[1]=Math.min(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._canvasMarquee[2]=Math.max(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[3]=Math.max(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._marqueeElement.style.width=this._canvasMarquee[2]-this._canvasMarquee[0]+"px",this._marqueeElement.style.height=this._canvasMarquee[3]-this._canvasMarquee[1]+"px",this._marqueeElement.style.left=`${this._canvasMarquee[0]}px`,this._marqueeElement.style.top=`${this._canvasMarquee[1]}px`}_buildMarqueeFrustum(){const e=this.viewer.scene.canvas.canvas,t=e.clientWidth,i=e.clientHeight,s=e.clientLeft,r=e.clientTop,o=2/t,n=2/i,a=e.clientHeight/e.clientWidth,l=(this._canvasMarquee[0]-s)*o-1,A=(this._canvasMarquee[2]-s)*o-1,h=-(this._canvasMarquee[3]-r)*n+1,c=-(this._canvasMarquee[1]-r)*n+1,u=this.viewer.scene.camera.frustum.near*(17*a);d.frustumMat4(l,A,h*a,c*a,u,1e4,this._marqueeFrustumProjMat),Q(this._marqueeFrustum,this.viewer.scene.camera.viewMatrix,this._marqueeFrustumProjMat)}destroy(){super.destroy(),this._marqueeElement.parentElement&&(this._marqueeElement.parentElement.removeChild(this._marqueeElement),this._marqueeElement=null,this._objectsKdTree3=null)}}H.PICK_MODE_INTERSECTS=0,H.PICK_MODE_INSIDE=1;class j extends R{constructor(e){super(e.marqueePicker,e);const t=e.marqueePicker,i=t.viewer.scene.canvas.canvas;let s,r,o,n,a,l,A,h=!1,c=!1,u=!1;i.addEventListener("mousedown",(e=>{this.getActive()&&0===e.button&&(A=setTimeout((function(){const o=t.viewer.scene.input;o.keyDown[o.KEY_CTRL]||t.clear(),s=e.pageX,r=e.pageY,a=e.offsetX,t.setMarqueeCorner1([s,r]),h=!0,t.viewer.cameraControl.pointerEnabled=!1,t.setMarqueeVisible(!0),i.style.cursor="crosshair"}),400),c=!0)})),i.addEventListener("mouseup",(e=>{if(!this.getActive())return;if(!h&&!u)return;if(0!==e.button)return;clearTimeout(A),o=e.pageX,n=e.pageY;const i=Math.abs(o-s),a=Math.abs(n-r);h=!1,t.viewer.cameraControl.pointerEnabled=!0,u&&(u=!1),(i>3||a>3)&&t.pick()})),document.addEventListener("mouseup",(e=>{this.getActive()&&0===e.button&&(clearTimeout(A),h&&(t.setMarqueeVisible(!1),h=!1,c=!1,u=!0,t.viewer.cameraControl.pointerEnabled=!0))}),!0),i.addEventListener("mousemove",(e=>{this.getActive()&&0===e.button&&c&&(clearTimeout(A),h&&(o=e.pageX,n=e.pageY,l=e.offsetX,t.setMarqueeVisible(!0),t.setMarqueeCorner2([o,n]),t.setPickMode(a{if(!this._running)return;i||(i=e);const r=e-i,o=Math.min(r/300,1),n=t+(2-t)*o;this._circleRadius=n,this._circleDiv.style.width=`${this._circleRadius}px`,this._circleDiv.style.height=`${this._circleRadius}px`,this._circleDiv.style.marginLeft=this._circlePos[0]-this._circleRadius/2+"px",this._circleDiv.style.marginTop=this._circlePos[1]-this._circleRadius/2+"px",o<1&&requestAnimationFrame(s)};this._running=!0,requestAnimationFrame(s),this._circleDiv.style.visibility="visible"}stop(){this._destroyed||(this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius=`${this._circleRadius}px`,this._circleDiv.style.visibility="hidden")}set durationMs(e){this.stop(),this._durationMs=e}get durationMs(){return this._durationMs}destroy(){this._destroyed||(this.stop(),this._circleDiv.parentElement.removeChild(this._circleDiv),this._destroyed=!0)}}class z{constructor(e,t,i){this.id=i&&i.id?i.id:e,this.viewer=t,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,t.addPlugin(this)}scheduleTask(e){I.scheduleTask(e,null)}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}const W={isIphoneSafari(){const e=window.navigator.userAgent,t=/iPhone/i.test(e),i=/Safari/i.test(e)&&!/Chrome/i.test(e);return t&&i}};class K{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!1!==t.visible,this._culled=!1;var i=this._dot,s=i.style;s["border-radius"]="25px",s.border="solid 2px white",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,s.width="8px",s.height="8px",s.visibility=this._visible?"visible":"hidden",s.top="0px",s.left="0px",s["box-shadow"]="0 2px 5px 0 #182A3D;",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._dotClickable,o=r.style;o["border-radius"]="35px",o.border="solid 10px white",o.position="absolute",o["z-index"]=void 0===t.zIndex?"40000007":t.zIndex+1,o.width="8px",o.height="8px",o.visibility="visible",o.top="0px",o.left="0px",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),r.addEventListener("click",(t=>{e.dispatchEvent(new MouseEvent("mouseover",t))})),t.onMouseOver&&r.addEventListener("mouseover",(i=>{t.onMouseOver(i,this),e.dispatchEvent(new MouseEvent("mouseover",i))})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onTouchstart&&r.addEventListener("touchstart",(e=>{t.onTouchstart(e,this)})),t.onTouchmove&&r.addEventListener("touchmove",(e=>{t.onTouchmove(e,this)})),t.onTouchend&&r.addEventListener("touchend",(e=>{t.onTouchend(e,this)})),t.onContextMenu&&(W.isIphoneSafari()?(r.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),r.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):r.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")}))),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.borderColor)}setPos(e,t){this._x=e,this._y=t;var i=this._dot.style;i.left=Math.round(e)-4+"px",i.top=Math.round(t)-4+"px";var s=this._dotClickable.style;s.left=Math.round(e)-9+"px",s.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}const X=d.vec3(),J=function(){const e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,o){return o=o||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,d.transformVec4(s,t,i),d.setMat4Translation(s,i,o),o.slice()}}();function Y(e,t,i){const s=Float32Array.from([e[0]])[0],r=e[0]-s,o=Float32Array.from([e[1]])[0],n=e[1]-o,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=s,t[1]=o,t[2]=a,i[0]=r,i[1]=n,i[2]=l}function Z(e,t,i,s=1e3){const r=d.getPositionsCenter(e,X),o=Math.round(r[0]/s)*s,n=Math.round(r[1]/s)*s,a=Math.round(r[2]/s)*s;i[0]=o,i[1]=n,i[2]=a;const l=0!==i[0]||0!==i[1]||0!==i[2];if(l)for(let i=0,s=e.length;i0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,i=this.meshes[0]._colorize[3];let s=255;if(t){if(e<0?e=0:e>1&&(e=1),s=Math.floor(255*e),i===s)return}else if(s=255,i===s)return;for(let e=0,t=this.meshes.length;e=0&&(e+=i)}return e>0?e:-1}_getFlag(e){return!!(this._flags&e)}_finalize(){const e=this.model.scene;this._isObject&&(this.visible&&e._objectVisibilityUpdated(this),this.highlighted&&e._objectHighlightedUpdated(this),this.xrayed&&e._objectXRayedUpdated(this),this.selected&&e._objectSelectedUpdated(this));for(let e=0,t=this.meshes.length;e{this._viewPosDirty=!0,this._needUpdate()})),this._onCameraProjMatrix=this.scene.camera.on("projMatrix",(()=>{this._canvasPosDirty=!0,this._needUpdate()})),this._onEntityDestroyed=null,this._onEntityModelDestroyed=null,this._renderer.addMarker(this),this.entity=t.entity,this.worldPos=t.worldPos,this.occludable=t.occludable}_update(){if(this._viewPosDirty&&(d.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){ue.set(this._viewPos),ue[3]=1,d.transformPoint4(this.scene.camera.projMatrix,ue,de);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+de[0]/de[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-de[1]/de[3])*e[3]/2),this._canvasPosDirty=!1,this.fire("canvasPos",this._canvasPos)}}_setVisible(e){this._visible,this._visible=e,this.fire("visible",this._visible)}set entity(e){if(this._entity){if(this._entity===e)return;null!==this._onEntityDestroyed&&(this._entity.model?this._entity.model.off(this._onEntityDestroyed):this._entity.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model&&this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null)}this._entity=e,this._entity&&(this._entity instanceof ce?this._onEntityModelDestroyed=this._entity.model.on("destroyed",(()=>{this._entity=null,this._onEntityModelDestroyed=null})):this._onEntityDestroyed=this._entity.on("destroyed",(()=>{this._entity=null,this._onEntityDestroyed=null}))),this.fire("entity",this._entity,!0)}get entity(){return this._entity}set occludable(e){(e=!!e)!==this._occludable&&(this._occludable=e,this._occludable&&this._renderer.markerWorldPosUpdated(this))}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),Y(this._worldPos,this._origin,this._rtcPos),this._occludable&&this._renderer.markerWorldPosUpdated(this),this._viewPosDirty=!0,this.fire("worldPos",this._worldPos),this._needUpdate()}get worldPos(){return this._worldPos}get origin(){return this._origin}get rtcPos(){return this._rtcPos}get viewPos(){return this._update(),this._viewPos}get canvasPos(){return this._update(),this._canvasPos}get visible(){return!!this._visible}destroy(){this.fire("destroyed",!0),this.scene.camera.off(this._onCameraViewMatrix),this.scene.camera.off(this._onCameraProjMatrix),this._entity&&(null!==this._onEntityDestroyed&&this._entity.model.off(this._onEntityDestroyed),null!==this._onEntityModelDestroyed&&this._entity.model.off(this._onEntityModelDestroyed)),this._renderer.removeMarker(this),super.destroy()}}const fe=()=>{};function ge(e,t,i){const s=e.getBoundingClientRect(),r=t.getBoundingClientRect();i[0]+=s.left-r.left,i[1]+=s.top-r.top}class me extends pe{constructor(e,t,i,s={}){super(e,t);const r=(e,t)=>i=>{e&&e(i),this.fire(t,i,!0)};this._dot=new K(i,{fillColor:s.fillColor,zIndex:s.zIndex,onMouseOver:r(s.onMouseOver,"mouseover"),onMouseLeave:r(s.onMouseLeave,"mouseleave"),onMouseWheel:r(s.onMouseWheel,"wheel"),onMouseDown:r(s.onMouseDown,"mousedown"),onMouseUp:r(s.onMouseUp,"mouseup"),onMouseMove:r(s.onMouseMove,"mousemove"),onTouchstart:r(s.onTouchstart,"touchstart"),onTouchmove:r(s.onTouchmove,"touchmove"),onTouchend:r(s.onTouchend,"touchend"),onContextMenu:r(s.onContextMenu,"contextmenu")});const o=()=>{const t=this.canvasPos.slice();ge(e.canvas.canvas,i,t),this._dot.setPos(t[0],t[1])};this.on("worldPos",o);const n=e.camera.on("viewMatrix",o),a=e.camera.on("projMatrix",o);this._cleanup=()=>{e.camera.off(n),e.camera.off(a),this._dot.destroy()}}setClickable(e){this._dot.setClickable(e)}setCulled(e){this._dot.setCulled(e)}setFillColor(e){this._dot.setFillColor(e)}setHighlighted(e){this._dot.setHighlighted(e)}setOpacity(e){this._dot.setOpacity(e)}setVisible(e){this._dot.setVisible(e)}destroy(){this._cleanup(),super.destroy()}}function _e(e,t){const i=function(e,i){if(e in t)return t[e];if(void 0!==i)return i;throw"config missing: "+e},s=i("viewer"),r=i("ray2WorldPos"),o=i("handleMouseEvents",!1),n=i("handleTouchEvents",!1),a=i("onStart",fe),l=i("onMove",fe),A=i("onEnd",fe),h=s.scene,c=h.canvas.canvas,u=e=>{const t=d.vec2([e.clientX,e.clientY]);ge(c.ownerDocument.documentElement,c,t),l(t,(e=>{const t=d.vec3(),i=d.vec3();return d.canvasPosToWorldRay(c,h.camera.viewMatrix,h.camera.projMatrix,h.camera.projection,e,t,i),r(t,i,e)})(t))};let p=null;const f=function(e){const t=p.matchesEvent(e);t&&u(t)},g=function(t){const i=p.matchesEvent(t);i&&(e.setOpacity(b),p.cleanup(),u(i),A())},m=function(t,i){p&&p.cleanup(),e.setOpacity(1),e.setClickable(!1),s.cameraControl.active=!1,p={matchesEvent:t,cleanup:function(){p=null,e.setClickable(!0),s.cameraControl.active=!0,i()}},a()},_=[],v=function(t,i){const s=e.on(t,i);_.push((()=>e.off(s)))};if(o&&(v("mouseover",(()=>!p&&e.setOpacity(1))),v("mouseleave",(()=>!p&&e.setOpacity(b))),v("mousedown",(e=>{1===e.which&&(c.addEventListener("mousemove",f),c.addEventListener("mouseup",g),m((e=>1===e.which&&e),(()=>{c.removeEventListener("mousemove",f),c.removeEventListener("mouseup",g)})))}))),n){let e;v("touchstart",(t=>{t.preventDefault(),1===t.touches.length&&(e=t.touches[0].identifier,m((t=>[...t.changedTouches].find((t=>t.identifier===e))),(()=>{e=null})))})),v("touchmove",(e=>{e.preventDefault(),f(e)})),v("touchend",(e=>{e.preventDefault(),g(e)}))}const b=.8;return e.setOpacity(b),function(){p&&p.cleanup(),_.forEach((e=>e())),e.setOpacity(1)}}function ve(e){const t=function(t,i){if(t in e)return e[t];if(void 0!==i)return i;throw"config missing: "+t},i=t("viewer"),s=t("handleMouseEvents",!1),r=t("handleTouchEvents",!1),o=t("pointerLens",null),n=t("dots"),a=t("ray2WorldPos"),l=t("onEnd",fe),A=o?function(e){o.visible=!!e,e&&(o.canvasPos=e)}:()=>{},h=n.map((e=>{let t;return _e(e,{handleMouseEvents:s,handleTouchEvents:r,viewer:i,ray2WorldPos:(e,i,s)=>a(e,i,s)||t,onStart:()=>{t=e.worldPos.slice(),c(!1,e)},onMove:(t,i)=>{A(t),e.worldPos=i},onEnd:()=>{l(t,e)||(e.worldPos=t),A(null),c(!0,e)}})})),c=(e,t)=>n.forEach((i=>i!==t&&i.setClickable(e)));return c(!0),function(){h.forEach((e=>e())),A(null)}}const be=function(e,t,i){return function(s,r,o){const n=e.scene,a=n.canvas.canvas,l=(e,t)=>(t[0]=e.clientX,t[1]=e.clientY,ge(a.ownerDocument.documentElement,a,t),t),A=e=>{const t=d.vec3(),s=d.vec3();return d.canvasPosToWorldRay(a,n.camera.viewMatrix,n.camera.projMatrix,n.camera.projection,e,t,s),i(t,s)};let h=null;const c=()=>{};let u,p=c;const f=function(){t.stop(),clearTimeout(h),e.cameraControl.active=!0,p=c,u=null},g=function(){f(),a.removeEventListener("touchstart",m),a.removeEventListener("touchmove",_),a.removeEventListener("touchend",v)},m=function(i){const o=i.touches;if(1!==o.length)f(),s();else{const i=o[0],s=l(i,d.vec2());A(s)&&(u=i.identifier,p=e=>{d.distVec2(s,e)>20&&f()},h=setTimeout((function(){t.start(s),h=setTimeout((function(){t.stop(),e.cameraControl.active=!1,p=e=>{r(e,A(e))},p(s)}),300)}),250))}};a.addEventListener("touchstart",m,{passive:!0});const _=function(e){const t=[...e.changedTouches].find((e=>e.identifier===u));t&&p(l(t,d.vec2()))};a.addEventListener("touchmove",_,{passive:!0});const v=function(e){const t=[...e.changedTouches].find((e=>e.identifier===u));if(t){g();const e=l(t,d.vec2());o(e,A(e))}};return a.addEventListener("touchend",v,{passive:!0}),g}};class ye{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6,this._visible=!0,this._culled=!1;var i=this._wire,s=i.style;s.border="solid "+this._thickness+"px "+this._color,s.position="absolute",s["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,s.width="0px",s.height="0px",s.visibility="visible",s.top="0px",s.left="0px",s["-webkit-transform-origin"]="0 0",s["-moz-transform-origin"]="0 0",s["-ms-transform-origin"]="0 0",s["-o-transform-origin"]="0 0",s["transform-origin"]="0 0",s["-webkit-transform"]="rotate(0deg)",s["-moz-transform"]="rotate(0deg)",s["-ms-transform"]="rotate(0deg)",s["-o-transform"]="rotate(0deg)",s.transform="rotate(0deg)",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._wireClickable,o=r.style;o.border="solid "+this._thicknessClickable+"px "+this._color,o.position="absolute",o["z-index"]=void 0===t.zIndex?"2000002":t.zIndex+1,o.width="0px",o.height="0px",o.visibility="visible",o.top="0px",o.left="0px",o["-webkit-transform-origin"]="0 0",o["-moz-transform-origin"]="0 0",o["-ms-transform-origin"]="0 0",o["-o-transform-origin"]="0 0",o["transform-origin"]="0 0",o["-webkit-transform"]="rotate(0deg)",o["-moz-transform"]="rotate(0deg)",o["-ms-transform"]="rotate(0deg)",o["-o-transform"]="rotate(0deg)",o.transform="rotate(0deg)",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),t.onMouseOver&&r.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&(W.isIphoneSafari()?(r.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),r.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):r.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")}))),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}get visible(){return"visible"===this._wire.style.visibility}_update(){var e=Math.abs(Math.sqrt((this._x1-this._x2)*(this._x1-this._x2)+(this._y1-this._y2)*(this._y1-this._y2))),t=180*Math.atan2(this._y2-this._y1,this._x2-this._x1)/Math.PI,i=this._wire.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)";var s=this._wireClickable.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)"}setStartAndEnd(e,t,i,s){this._x1=e,this._y1=t,this._x2=i,this._y2=s,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class xe{constructor(e,t={}){this._highlightClass="viewer-ruler-label-highlighted",this._prefix=t.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label",this._timeout=null;var i=this._label,s=i.style;s["border-radius"]="5px",s.color="white",s.padding="4px",s.border="solid 1px",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,s.width="auto",s.height="auto",s.visibility="visible",s.top="0px",s.left="0px",s["pointer-events"]="all",s.opacity=1,t.onContextMenu,i.innerText="",e.appendChild(i),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&i.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&i.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&i.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&i.addEventListener("mousedown",(e=>{t.onMouseDown(e,this),e.stopPropagation()})),t.onMouseUp&&i.addEventListener("mouseup",(e=>{t.onMouseUp(e,this),e.stopPropagation()})),t.onMouseMove&&i.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&(W.isIphoneSafari()?(i.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),i.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):i.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")})))}setPos(e,t){this._x=e,this._y=t;var i=this._label.style;i.left=Math.round(e)-20+"px",i.top=Math.round(t)-12+"px"}setPosOnWire(e,t,i,s){var r=e+.5*(i-e),o=t+.5*(s-t),n=this._label.style;n.left=Math.round(r)-20+"px",n.top=Math.round(o)-12+"px"}setPosBetweenWires(e,t,i,s,r,o){var n=(e+i+r)/3,a=(t+s+o)/3,l=this._label.style;l.left=Math.round(n)-20+"px",l.top=Math.round(a)-12+"px"}setText(e){this._label.innerHTML=this._prefix+(e||"")}setFillColor(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}setBorderColor(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}setOpacity(e){this._label.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}setClickable(e){this._label.style["pointer-events"]=e?"all":"none"}setPrefix(e){this._prefix!==e&&(this._prefix=e)}destroy(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}var Be=d.vec3(),we=d.vec3();class Pe extends R{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._color=t.color||e.defaultColor;var i=this.plugin.viewer.scene;this._originWorld=d.vec3(),this._cornerWorld=d.vec3(),this._targetWorld=d.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},l=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))};this._originDot=new me(i,t.origin,this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._cornerDot=new me(i,t.corner,this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetDot=new me(i,t.target,this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._originWire=new ye(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetWire=new ye(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._angleLabel=new xe(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._cornerVisible=!1,this._targetVisible=!1,this._originWireVisible=!1,this._targetWireVisible=!1,this._angleVisible=!1,this._labelsVisible=!1,this._clickable=!1,this._originDot.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._cornerDot.on("worldPos",(e=>{this._cornerWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetDot.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(d.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){const u=-.3,p=this._originDot.viewPos[2],f=this._cornerDot.viewPos[2],g=this._targetDot.viewPos[2];if(p>u||f>u||g>u)return this._originDot.setVisible(!1),this._cornerDot.setVisible(!1),this._targetDot.setVisible(!1),this._originWire.setVisible(!1),this._targetWire.setVisible(!1),void this._angleLabel.setCulled(!0);d.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,i=this._cp,s=e.canvas.canvas.getBoundingClientRect();const m=this._container.getBoundingClientRect();for(var r=s.top-m.top,o=s.left-m.left,n=e.canvas.boundary,a=n[2],l=n[3],A=0,h=0,c=t.length;he.offsetTop+(e.offsetParent&&e.offsetParent!==t.parentNode&&h(e.offsetParent)),c=e=>e.offsetLeft+(e.offsetParent&&e.offsetParent!==t.parentNode&&c(e.offsetParent)),u=d.vec2(),p=e=>{e.snappedToVertex||e.snappedToEdge?(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.canvasPos,s.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red");const i=e.snappedCanvasPos||e.canvasPos;switch(r=!0,o=e.entity,l.set(e.worldPos),A.set(i),this._mouseState){case 0:this._canvasToPagePos?(this._canvasToPagePos(t,i,u),this.markerDiv.style.left=u[0]-5+"px",this.markerDiv.style.top=u[1]-5+"px"):(this.markerDiv.style.left=c(t)+i[0]-5+"px",this.markerDiv.style.top=h(t)+i[1]-5+"px");break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos,this._currentAngleMeasurement.corner.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos,this._currentAngleMeasurement.target.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer"}};this._onHoverSnapOrSurface=i.on("hoverSnapOrSurface",(e=>{this._snapping&&p(e)})),this._onHoverSurface=i.on("hoverSurface",(e=>{this._snapping||p(e)})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(n=e.clientX,a=e.clientY)}),t.addEventListener("mouseup",this._onMouseUp=e=>{if(1===e.which&&!(e.clientX>n+20||e.clientXa+20||e.clientY{if(r=!1,s&&(s.visible=!0,s.pointerPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!1),this.markerDiv.style.left="-100px",this.markerDiv.style.top="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}};this._onHoverSnapOrSurfaceOff=i.on("hoverSnapOrSurfaceOff",(e=>{this._snapping&&f(e)})),this._onHoverOff=i.on("hoverOff",(e=>{this._snapping||f(e)})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onHoverSnapOrSurface),t.off(this._onHoverSurface),t.off(this._onHoverSnapOrSurfaceOff),t.off(this._onHoverOff),this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}get currentMeasurement(){return this._currentAngleMeasurement}destroy(){this.deactivate(),super.destroy()}}class Ee extends z{constructor(e,t={}){super("AngleMeasurements",e),this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.zIndex=t.zIndex||1e4,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,angleMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get control(){return this._defaultControl||(this._defaultControl=new Me(this,{})),this._defaultControl}get measurements(){return this._measurements}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,i=e.corner,s=e.target,r=new Pe(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},corner:{entity:i.entity,worldPos:i.worldPos},target:{entity:s.entity,worldPos:s.worldPos},visible:e.visible,originVisible:!0,originWireVisible:!0,cornerVisible:!0,targetWireVisible:!0,targetVisible:!0,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[r.id]=r,r.on("destroyed",(()=>{delete this._measurements[r.id]})),r.clickable=!0,this.fire("measurementCreated",r),r}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("AngleMeasurement not found: "+e)}setLabelsShown(e){for(const[t,i]of Object.entries(this.measurements))i.labelShown=e}clear(){const e=Object.keys(this._measurements);for(var t=0,i=e.length;t{this.plugin.viewer.cameraControl.active=!1},c=()=>{this.plugin.viewer.cameraControl.active=!0},u=()=>{o&&(clearTimeout(o),o=null),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),c(),this._touchState=0};i.addEventListener("touchstart",this._onCanvasTouchStart=i=>{const l=i.touches.length;if(1!==l)return void(o&&(clearTimeout(o),o=null));const c=i.touches[0],p=c.clientX,f=c.clientY;switch(n.set([p,f]),a.set([p,f]),this._touchState){case 0:if(1!==l&&null!==o)return void u();const i=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping});if(i&&i.snapped)s.set(i.worldPos),this.pointerCircle.start(i.snappedCanvasPos);else{const e=t.pick({canvasPos:a,pickSurface:!0});if(!e||!e.worldPos)return;s.set(e.worldPos),this.pointerCircle.start(e.canvasPos)}o=setTimeout((()=>{1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{if(o=null,1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{if(o=null,1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{this.pointerCircle.stop();const i=e.touches.length;if(1!==i||1!==e.changedTouches.length)return void(o&&(clearTimeout(o),o=null));const r=e.touches[0],n=r.clientX,l=r.clientY;if(r.identifier!==A)return;let h,c;switch(a.set([n,l]),this._touchState){case 2:this.pointerLens&&(this.pointerLens.canvasPos=a),h=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),h&&h.snapped?(this.pointerLens&&(this.pointerLens.snappedCanvasPos=h.snappedCanvasPos,this.pointerLens.snapped=!0),s.set(h.worldPos),this._currentAngleMeasurement.origin.worldPos=h.worldPos):(c=t.pick({canvasPos:a,pickSurface:!0}),c&&c.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=c.canvasPos,this.pointerLens.snapped=!1),s.set(c.worldPos),this._currentAngleMeasurement.origin.worldPos=c.worldPos):this.pointerLens&&(this.pointerLens.cursorPos=null,this.pointerLens.snapped=!1)),this._touchState=2;break;case 5:if(1!==i&&null!==o)return clearTimeout(o),o=null,this.pointerLens&&(this.pointerLens.visible=!1),void(this._touchState=7);this.pointerLens&&(this.pointerLens.canvasPos=a),h=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),h&&h.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=h.snappedCanvasPos,this.pointerLens.snapped=!0),this._currentAngleMeasurement.corner.worldPos=h.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1):(c=t.pick({canvasPos:a,pickSurface:!0}),c&&c.worldPos&&(this.pointerLens&&(this.pointerLens.cursorPos=c.canvasPos,this.pointerLens.snapped=!1),this._currentAngleMeasurement.corner.worldPos=c.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1)),this._touchState=5;break;case 8:if(1!==i&&null!==o)return clearTimeout(o),o=null,this.pointerLens&&(this.pointerLens.visible=!1),void(this._touchState=7);this.pointerLens&&(this.pointerLens.canvasPos=a),h=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),h&&h.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=h.snappedCanvasPos,this.pointerLens.snapped=!0),this._currentAngleMeasurement.target.worldPos=h.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.angleVisible=!0):(c=t.pick({canvasPos:a,pickSurface:!0}),c&&c.worldPos&&(this.pointerLens&&(this.pointerLens.cursorPos=c.canvasPos,this.pointerLens.snapped=!1),this._currentAngleMeasurement.target.worldPos=c.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.angleVisible=!0)),this._touchState=8}}),{passive:!0}),i.addEventListener("touchend",this._onCanvasTouchEnd=i=>{this.pointerCircle.stop();const s=i.changedTouches.length;if(1!==s)return;const h=i.changedTouches[0],u=h.clientX,p=h.clientY;if(h.identifier===A)switch(o&&(clearTimeout(o),o=null),l.set([u,p]),this._touchState){case 1:{if(1!==s||u>n[0]+r||un[1]+r||pn[0]+r||un[1]+r||pn[0]+r||un[1]+r||p{const o=e=>{const t=r.scene.pick({canvasPos:s,snapToEdge:e,snapToVertex:e,pickSurface:!0});return t&&t.worldPos?t.worldPos:e&&o(!1)};return o(!!t.snapping)},onEnd:(e,t)=>{const i=!d.compareVec3(e,t.worldPos);return i&&this.fire("edited"),i}}),n=e.on("destroyed",o);this._deactivate=function(){e.off("destroyed",n),o()}}deactivate(){this._deactivate(),super.destroy()}}class De extends Ie{constructor(e,t){super(e,t,!0,!1)}}class Se extends Ie{constructor(e,t){super(e,t,!1,!0)}}const Te=d.vec3(),Re=d.vec3(),Le=d.vec3();class Ue extends pe{constructor(e,t){if(super(e,t),this.plugin=t.plugin,this._container=t.container,!this._container)throw"config missing: container";if(!t.markerElement&&!t.markerHTML)throw"config missing: need either markerElement or markerHTML";if(!t.labelElement&&!t.labelHTML)throw"config missing: need either labelElement or labelHTML";this._htmlDirty=!1,t.markerElement?(this._marker=t.markerElement,this._marker.addEventListener("click",this._onMouseClickedExternalMarker=()=>{this.plugin.fire("markerClicked",this)}),this._marker.addEventListener("contextmenu",this._onContextMenuExtenalMarker=()=>{this.plugin.fire("contextmenu",this)}),this._marker.addEventListener("mouseenter",this._onMouseEnterExternalMarker=()=>{this.plugin.fire("markerMouseEnter",this)}),this._marker.addEventListener("mouseleave",this._onMouseLeaveExternalMarker=()=>{this.plugin.fire("markerMouseLeave",this)}),this._markerExternal=!0):(this._markerHTML=t.markerHTML,this._htmlDirty=!0,this._markerExternal=!1),t.labelElement?(this._label=t.labelElement,this._labelExternal=!0):(this._labelHTML=t.labelHTML,this._htmlDirty=!0,this._labelExternal=!1),this._markerShown=!!t.markerShown,this._labelShown=!!t.labelShown,this._values=t.values||{},this._layoutDirty=!0,this._visibilityDirty=!0,this._labelPosition=24,this._buildHTML(),this._onTick=this.scene.on("tick",(()=>{this._htmlDirty&&(this._buildHTML(),this._htmlDirty=!1,this._layoutDirty=!0,this._visibilityDirty=!0),(this._layoutDirty||this._visibilityDirty)&&(this._markerShown||this._labelShown)&&(this._updatePosition(),this._layoutDirty=!1),this._visibilityDirty&&(this._marker.style.visibility=this.visible&&this._markerShown?"visible":"hidden",this._label.style.visibility=this.visible&&this._markerShown&&this._labelShown?"visible":"hidden",this._visibilityDirty=!1)})),this.on("canvasPos",(()=>{this._layoutDirty=!0})),this.on("visible",(()=>{this._visibilityDirty=!0})),this.setMarkerShown(!1!==t.markerShown),this.setLabelShown(t.labelShown),this.eye=t.eye?t.eye.slice():null,this.look=t.look?t.look.slice():null,this.up=t.up?t.up.slice():null,this.projection=t.projection}_buildHTML(){if(!this._markerExternal){this._marker&&(this._container.removeChild(this._marker),this._marker=null);let e=this._markerHTML||"

";y.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e.trim());const t=document.createRange().createContextualFragment(e);this._marker=t.firstChild,this._container.appendChild(this._marker),this._marker.style.visibility=this._markerShown?"visible":"hidden",this._marker.addEventListener("click",(()=>{this.plugin.fire("markerClicked",this)})),this._marker.addEventListener("contextmenu",(e=>{e.preventDefault(),this.plugin.fire("contextmenu",this)})),this._marker.addEventListener("mouseenter",(()=>{this.plugin.fire("markerMouseEnter",this)})),this._marker.addEventListener("mouseleave",(()=>{this.plugin.fire("markerMouseLeave",this)})),this._marker.addEventListener("wheel",(e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))}))}if(!this._labelExternal){this._label&&(this._container.removeChild(this._label),this._label=null);let e=this._labelHTML||"

";y.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e.trim());const t=document.createRange().createContextualFragment(e);this._label=t.firstChild,this._container.appendChild(this._label),this._label.style.visibility=this._markerShown&&this._labelShown?"visible":"hidden",this._label.addEventListener("wheel",(e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))}))}}_updatePosition(){const e=e=>e+"px",t=this.scene.canvas.boundary,i=t[0]+this.canvasPos[0],s=t[1]+this.canvasPos[1],r=this._marker.getBoundingClientRect().width,o=i+("right"===this._markerAlign?-1:"center"===this._markerAlign?0:1)*(r/2-12);this._marker.style.left=e(o-r/2),this._marker.style.top=e(s-12),this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;const n=this._label.getBoundingClientRect().width,a=Math.sign(this._labelPosition);this._label.style.left=e(o+a*(r/2+Math.abs(this._labelPosition)+n/2)-n/2),this._label.style.top=e(s-17),this._label.style["z-index"]=90005+Math.floor(this._viewPos[2])+1}_renderTemplate(e){for(var t in this._values)if(this._values.hasOwnProperty(t)){const i=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),i)}return e}setFromPickResult(e){if(e.worldPos&&e.worldNormal){const t=d.normalizeVec3(e.worldNormal,Te),i=this.plugin&&this.plugin.surfaceOffset||0,s=d.mulVec3Scalar(t,i,Re),r=d.addVec3(e.worldPos,s,Le);this.entity=e.entity,this.worldPos=r}else this.error("Param 'pickResult' does not have both worldPos and worldNormal")}setMarkerAlign(e){const t=["left","center","right"];t.includes(e)?(this._markerAlign=e,this._updatePosition()):this.error("Param 'align' should be one of: "+JSON.stringify(t))}setLabelPosition(e){"number"!=typeof e?this.error("Param 'position' is not a number"):0===e?this.error("Param 'position' is zero"):(this._labelPosition=e,this._updatePosition())}setMarkerShown(e){e=!!e,this._markerShown!==e&&(this._markerShown=e,this._visibilityDirty=!0)}getMarkerShown(){return this._markerShown}setLabelShown(e){e=!!e,this._labelShown!==e&&(this._labelShown=e,this._visibilityDirty=!0)}getLabelShown(){return this._labelShown}setField(e,t){this._values[e]=t||"",this._htmlDirty=!0}getField(e){return this._values[e]}setValues(e){for(var t in e)if(e.hasOwnProperty(t)){const i=e[t];this.setField(t,i)}}getValues(){return this._values}destroy(){this._marker&&(this._markerExternal?(this._marker.removeEventListener("click",this._onMouseClickedExternalMarker),this._marker.removeEventListener("contextmenu",this._onContextMenuExtenalMarker),this._marker.removeEventListener("mouseenter",this._onMouseEnterExternalMarker),this._marker.removeEventListener("mouseleave",this._onMouseLeaveExternalMarker),this._marker=null):(this._marker.parentNode.removeChild(this._marker),this._marker=null)),this._label&&(this._labelExternal||this._label.parentNode.removeChild(this._label),this._label=null),this.scene.off(this._onTick),super.destroy()}}class ke extends z{constructor(e,t){super("Annotations",e),this._labelHTML=t.labelHTML||"
",this._markerHTML=t.markerHTML||"
",this._container=t.container||document.body,this._values=t.values||{},this.annotations={},this.surfaceOffset=t.surfaceOffset}getContainerElement(){return this._container}send(e,t){if("clearAnnotations"===e)this.clear()}set surfaceOffset(e){null==e&&(e=.3),this._surfaceOffset=e}get surfaceOffset(){return this._surfaceOffset}createAnnotation(e){this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id);var t=null;e.markerElementId&&((t=document.getElementById(e.markerElementId))||this.error("Can't find DOM element for 'markerElementId' value '"+e.markerElementId+"' - defaulting to internally-generated empty DIV"));var i=null;e.labelElementId&&((i=document.getElementById(e.labelElementId))||this.error("Can't find DOM element for 'labelElementId' value '"+e.labelElementId+"' - defaulting to internally-generated empty DIV"));const s=new Ue(this.viewer.scene,{id:e.id,plugin:this,container:this._container,markerElement:t,labelElement:i,markerHTML:e.markerHTML||this._markerHTML,labelHTML:e.labelHTML||this._labelHTML,occludable:e.occludable,values:y.apply(e.values,y.apply(this._values,{})),markerShown:e.markerShown,labelShown:e.labelShown,eye:e.eye,look:e.look,up:e.up,projection:e.projection,visible:!1!==e.visible});return e.pickResult=e.pickResult||e.pickRecord,e.pickResult?s.setFromPickResult(e.pickResult):(s.entity=e.entity,s.worldPos=e.worldPos),this.annotations[s.id]=s,s.on("destroyed",(()=>{delete this.annotations[s.id],this.fire("annotationDestroyed",s.id)})),this.fire("annotationCreated",s.id),s}destroyAnnotation(e){var t=this.annotations[e];t?t.destroy():this.log("Annotation not found: "+e)}clear(){const e=Object.keys(this.annotations);for(var t=0,i=e.length;t
',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){const e="xeokit-spinner-css";if(document.getElementById(e))return;const t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}_adjustPosition(){if(this._isCustom)return;const e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const Ne=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class Qe extends R{constructor(e,t={}){super(e,t),this._backgroundColor=d.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const i=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),i.scene._webglContextLost(),i.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){i._initWebGL(),i.gl&&(i.scene._webglContextRestored(i.gl),i.fire("webglcontextrestored",i.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let s=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(s=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{s&&(s=!1,i.canvas.width=Math.round(i.canvas.clientWidth*i._resolutionScale),i.canvas.height=Math.round(i.canvas.clientHeight*i._resolutionScale),i.boundary[0]=i.canvas.offsetLeft,i.boundary[1]=i.canvas.offsetTop,i.boundary[2]=i.canvas.clientWidth,i.boundary[3]=i.canvas.clientHeight,i.fire("boundary",i.boundary))})),this._spinner=new Oe(this.scene,{canvas:this.canvas,elementId:t.spinnerElementId})}get type(){return"Canvas"}get backgroundColorFromAmbientLight(){return this._backgroundColorFromAmbientLight}set backgroundColorFromAmbientLight(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}get backgroundColor(){return this._backgroundColor}set backgroundColor(e){e?(this._backgroundColor[0]=e[0],this._backgroundColor[1]=e[1],this._backgroundColor[2]=e[2]):(this._backgroundColor[0]=1,this._backgroundColor[1]=1,this._backgroundColor[2]=1),this.glRedraw()}get resolutionScale(){return this._resolutionScale}set resolutionScale(e){if((e=e||1)===this._resolutionScale)return;this._resolutionScale=e;const t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}get spinner(){return this._spinner}_createCanvas(){const e="xeokit-canvas-"+d.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),s=i.style;s.height="100%",s.width="100%",s.padding="0",s.margin="0",s.background="rgba(0,0,0,0);",s.float="left",s.left="0",s.top="0",s.position="absolute",s.opacity="1.0",s["z-index"]="-10000",i.innerHTML+='',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&&e0?He.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?He.FS_MAX_FLOAT_PRECISION="mediump":He.FS_MAX_FLOAT_PRECISION="lowp":He.FS_MAX_FLOAT_PRECISION="mediump",He.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),He.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),He.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),He.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),He.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),He.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),He.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),He.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),He.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),He.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){He.SUPPORTED_EXTENSIONS[e]=!0})))}class Ge{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get snappedCanvasPos(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null}set snappedCanvasPos(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}get worldPos(){return this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}get snapped(){return this.snappedToEdge||this.snappedToVertex}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}class ze{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;e0&&"/"===i.charAt(s+1)&&(i=i.substring(0,s)),t.push(i);return t.join("\n")}function Ye(e){console.error(e.join("\n"))}class Ze{constructor(e,t){this.id=Xe.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 ze(e,e.VERTEX_SHADER,Je(this.source.vertex)),this._fragmentShader=new ze(e,e.FRAGMENT_SHADER,Je(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void Ye(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void Ye(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void Ye(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void Ye(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 Ye(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;ithis.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}setData(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}bind(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}unbind(){this.allocated&&this._gl.bindBuffer(this.type,null)}destroy(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}class $e{constructor(e,t){this.scene=e,this.aabb=d.AABB3(),this.origin=d.vec3(t),this.originHash=this.origin.join(),this.numMarkers=0,this.markers={},this.markerList=[],this.markerIndices={},this.positions=[],this.indices=[],this.positionsBuf=null,this.lenPositionsBuf=0,this.indicesBuf=null,this.sectionPlanesActive=[],this.culledBySectionPlanes=!1,this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.aabbDirty=!1,this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!1}addMarker(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}markerWorldPosUpdated(e){if(!this.markers[e.id])return;const t=this.markerIndices[e.id];this.positions[3*t+0]=e.worldPos[0],this.positions[3*t+1]=e.worldPos[1],this.positions[3*t+2]=e.worldPos[2],this.positionsDirty=!0}removeMarker(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}update(){this.markerListDirty&&(this._buildMarkerList(),this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0),this.positionsDirty&&(this._buildPositions(),this.positionsDirty=!1,this.aabbDirty=!0,this.vbosDirty=!0),this.aabbDirty&&(this._buildAABB(),this.aabbDirty=!1),this.vbosDirty&&(this._buildVBOs(),this.vbosDirty=!1),this.occlusionTestListDirty&&this._buildOcclusionTestList(),this._updateActiveSectionPlanes()}_buildMarkerList(){for(var e in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(e)&&(this.markerList[this.numMarkers]=this.markers[e],this.markerIndices[e]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers}_buildPositions(){let e=0;for(let t=0;t-t){i._setVisible(!1);continue}const n=i.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>s||l-10>r?i._setVisible(!1):!i.entity||i.entity.visible?i.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=i,this.pixels[o++]=a,this.pixels[o++]=l):i._setVisible(!0):i._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let i=0;i{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i||(i=new $e(this._scene,e.origin),this._occlusionLayers[i.originHash]=i,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return;const i=e.origin.join();if(i!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let s=this._occlusionLayers[i];s||(s=new $e(this._scene,e.origin),this._occlusionLayers[i]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.originHash],this._occlusionLayersListDirty=!0):i.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e0,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):e.markerZOffset<0&&i.push("clipPos.z += "+e.markerZOffset+";"),i.push(" gl_Position = clipPos;"),i.push("}"),i}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// OcclusionTester fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Ze(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e0){const e=s.sectionPlanes;for(let s=0;s{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=d.mat4();return()=>(e&&d.inverseMat4(s.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,i=this._program,s=this._scene,r=s.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=s.camera.project._state,l=a.near,A=a.far,h=a.matrix,c=this._getInverseProjectMat(),u=Math.random(),p="perspective"===s.camera.projection;st[0]=o,st[1]=n,t.viewport(0,0,o,n),t.clearColor(0,0,0,1),t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.frontFace(t.CCW),t.clear(t.COLOR_BUFFER_BIT),i.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,A),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,h),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,c),t.uniform1i(this._uPerspective,p),t.uniform1f(this._uScale,r.scale*(A/5)),t.uniform1f(this._uIntensity,r.intensity),t.uniform1f(this._uBias,r.bias),t.uniform1f(this._uKernelRadius,r.kernelRadius),t.uniform1f(this._uMinResolution,r.minResolution),t.uniform2fv(this._uViewport,st),t.uniform1f(this._uRandomSeed,u);const f=e.getDepthTexture();i.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e)return;const i=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new Ze(i,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),o=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new qe(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new qe(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new qe(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const ot=new Float32Array(ct(17,[0,1])),nt=new Float32Array(ct(17,[1,0])),at=new Float32Array(function(e,t){const i=[];for(let s=0;s<=e;s++)i.push(ht(s,t));return i}(17,4)),lt=new Float32Array(2);class At{constructor(e){this._scene=e,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._uViewport=null,this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new Ze(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS 16\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new qe(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new qe(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new qe(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,i){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=d.mat4();return()=>(e&&d.inverseMat4(o.camera.projMatrix,t),t)})());const s=this._scene.canvas.gl,r=this._program,o=this._scene,n=s.drawingBufferWidth,a=s.drawingBufferHeight,l=o.camera.project._state,A=l.near,h=l.far;s.viewport(0,0,n,a),s.clearColor(0,0,0,1),s.enable(s.DEPTH_TEST),s.disable(s.BLEND),s.frontFace(s.CCW),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),r.bind(),lt[0]=n,lt[1]=a,s.uniform2fv(this._uViewport,lt),s.uniform1f(this._uCameraNear,A),s.uniform1f(this._uCameraFar,h),s.uniform1f(this._uDepthCutoff,.01),0===i?s.uniform2fv(this._uSampleOffsets,nt):s.uniform2fv(this._uSampleOffsets,ot),s.uniform1fv(this._uSampleWeights,at);const c=e.getDepthTexture(),u=t.getTexture();r.bindTexture(this._uDepthTexture,c,0),r.bindTexture(this._uOcclusionTexture,u,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),s.drawElements(s.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function ht(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function ct(e,t){const i=[];for(let s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}class ut{constructor(e,t,i){i=i||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=i.size,this._hasDepthTexture=!!i.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(...e){if(this._touch(...e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}createTexture(e,t,i=null){const s=this.gl,r=s.createTexture();return s.bindTexture(s.TEXTURE_2D,r),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),i?s.texStorage2D(s.TEXTURE_2D,1,i,e,t):s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null),r}_touch(...e){let t,i;const s=this.gl;if(this.size?(t=this.size[0],i=this.size[1]):(t=s.drawingBufferWidth,i=s.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===i)return;this.buffer.textures.forEach((e=>s.deleteTexture(e))),s.deleteFramebuffer(this.buffer.framebuf),s.deleteRenderbuffer(this.buffer.renderbuf)}const r=[];let o;e.length>0?r.push(...e.map((e=>this.createTexture(t,i,e)))):r.push(this.createTexture(t,i)),this._hasDepthTexture&&(o=s.createTexture(),s.bindTexture(s.TEXTURE_2D,o),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,s.DEPTH_COMPONENT32F,t,i,0,s.DEPTH_COMPONENT,s.FLOAT,null));const n=s.createRenderbuffer();s.bindRenderbuffer(s.RENDERBUFFER,n),s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT32F,t,i);const a=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,a);for(let e=0;e0&&s.drawBuffers(r.map(((e,t)=>s.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,o,0):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,n),s.bindTexture(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,a),!s.isFramebuffer(a))throw"Invalid framebuffer";s.bindFramebuffer(s.FRAMEBUFFER,null);const l=s.checkFramebufferStatus(s.FRAMEBUFFER);switch(l){case s.FRAMEBUFFER_COMPLETE:break;case s.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case s.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:a,renderbuf:n,texture:r[0],textures:r,depthTexture:o,width:t,height:i},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,i=null,s=null,r=Uint8Array,o=4,n=0){const a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,A=new r(o),h=this.gl;return h.readBuffer(h.COLOR_ATTACHMENT0+n),h.readPixels(a,l,1,1,i||h.RGBA,s||h.UNSIGNED_BYTE,A,0),A}readArray(e=null,t=null,i=Uint8Array,s=4,r=0){const o=new i(this.buffer.width*this.buffer.height*s),n=this.gl;return n.readBuffer(n.COLOR_ATTACHMENT0+r),n.readPixels(0,0,this.buffer.width,this.buffer.height,e||n.RGBA,t||n.UNSIGNED_BYTE,o,0),o}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),i=t.pixelData,s=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,A=4*n,h=new Uint8Array(4*n);for(let e=0;ee.deleteTexture(t))),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}class dt{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let s=i[e];return s||(s=new ut(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=s),s}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}function pt(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}const ft=function(t,i){i=i||{};const s=new Ve(t),r=t.canvas.canvas,o=t.canvas.gl,n=!!i.transparent,a=i.alphaDepthMask,l=new e({});let A={},h={},c=[],u=[],p=!0,f=!0,g=!0,_=!0,v=!0,b=!0,y=!0,x=!0;const B=new dt(t);let w=!1;const P=new rt(t),C=new At(t);function M(){p&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableMap,s=t.drawableListPreCull;let r=0;for(let e in i)i.hasOwnProperty(e)&&(s[r++]=i[e]);s.length=r}}(),p=!1,f=!0),f&&(!function(){let e=0;for(let t in A)if(A.hasOwnProperty(t)){const i=A[t].drawableListPreCull;for(let t=0,s=i.length;te.renderOrder-t.renderOrder))}(),f=!1,g=!0),g&&function(){let e=0;for(let t=0,i=c.length;t0)for(s.withSAO=!0,S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||H>0||k>0||O>0){if(o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):(o.blendEquation(o.FUNC_ADD),o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA)),s.backfaces=!1,a||o.depthMask(!1),(k>0||O>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),O>0)for(S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||G>0){if(s.lastProgramId=null,t.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),G>0)for(S=0;S0)for(S=0;S0||W>0||j>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),o.enable(o.CULL_FACE),W>0)for(S=0;S0)for(S=0;S0||X>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),X>0)for(S=0;S0)for(S=0;S0||Y>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),Y>0)for(S=0;S0)for(S=0;S0){const t=Math.floor(e/4),i=_.size[0],s=t%i-Math.floor(i/2),r=Math.floor(t/i)-Math.floor(i/2),o=Math.sqrt(Math.pow(s,2)+Math.pow(r,2));U.push({x:s,y:r,dist:o,isVertex:p&&f?x[e+3]>y.length/2:p,result:[x[e+0],x[e+1],x[e+2],x[e+3]],normal:[w[e+0],w[e+1],w[e+2],w[e+3]],id:[P[e+0],P[e+1],P[e+2],P[e+3]]})}let k=null,O=null,N=null,Q=null;if(U.length>0){U.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),Q=U[0].isVertex?"vertex":"edge";const e=U[0].result,t=U[0].normal,i=U[0].id,s=y[e[3]],r=s.origin,o=s.coordinateScale;O=d.normalizeVec3([t[0]/d.MAX_INT,t[1]/d.MAX_INT,t[2]/d.MAX_INT]),k=[e[0]*o[0]+r[0],e[1]*o[1]+r[1],e[2]*o[2]+r[2]],N=l.items[i[0]+(i[1]<<8)+(i[2]<<16)+(i[3]<<24)]}if(null===C&&null==k)return null;let V=null;null!==k&&(V=t.camera.projectWorldPos(k));const H=N&&N.delegatePickedEntity?N.delegatePickedEntity():N;return!H&&E&&(E=E.delegatePickedEntity?E.delegatePickedEntity():E),r.reset(),r.snappedToEdge="edge"===Q,r.snappedToVertex="vertex"===Q,r.worldPos=k||C,r.worldNormal=O||M,r.entity=H||E,r.canvasPos=n||t.camera.projectWorldPos(C||k),r.snappedCanvasPos=V||n,r}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new it(t,B),this._occlusionTester.addMarker(e),t.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){M(),this._occlusionTester.bindRenderBuf(),s.reset(),s.backfaces=!0,s.frontface=!0,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e=0,t=u.length;e{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!0:e.keyCode===this.KEY_ALT?this.altDown=!0:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!0),this.keyDown[e.keyCode]=!0,this.fire("keydown",e.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!1:e.keyCode===this.KEY_ALT?this.altDown=!1:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!1),this.keyDown[e.keyCode]=!1,this.fire("keyup",e.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=e=>{this.enabled&&(this.mouseover=!0,this._getMouseCanvasPos(e),this.fire("mouseenter",this.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=e=>{this.enabled&&(this.mouseover=!1,this._getMouseCanvasPos(e),this.fire("mouseleave",this.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!0;break;case 2:this.mouseDownMiddle=!0;break;case 3:this.mouseDownRight=!0}this._getMouseCanvasPos(e),this.element.focus(),this.fire("mousedown",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownRight=!1}this.fire("mouseup",this.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("click",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("dblclick",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}});const e=this.scene.tickify((()=>this.fire("mousemove",this.mouseCanvasPos,!0)));this.element.addEventListener("mousemove",this._mouseMoveListener=t=>{this.enabled&&(this._getMouseCanvasPos(t),e(),this.mouseover&&t.preventDefault())}),this.element.addEventListener("contextmenu",this._contextmenuListener=e=>{this.enabled&&(this._getMouseCanvasPos(e),this.fire("contextmenu",this.mouseCanvasPos,!0))});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,i)=>{if(!this.enabled)return;const s=Math.max(-1,Math.min(1,40*-e.deltaY));t(s)},{passive:!0});{let e,t;const i=2;this.on("mousedown",(i=>{e=i[0],t=i[1]})),this.on("mouseup",(s=>{e>=s[0]-i&&e<=s[0]+i&&t>=s[1]-i&&t<=s[1]+i&&this.fire("mouseclicked",s,!0)}))}this.element.addEventListener("touchstart",this._touchstartListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchstart",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this.element.addEventListener("touchend",this._touchendListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchend",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this._eventsBound=!0}_unbindEvents(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("contextmenu",this._contextmenuListener),this.element.removeEventListener("wheel",this._mouseWheelListener),this.element.removeEventListener("touchstart",this._touchstartListener),this.element.removeEventListener("touchend",this._touchendListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getTouchCanvasPos(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;return[e.pageX-i,e.pageY-s]}_getMouseCanvasPos(e){if(e){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()}}const mt=new e({});class _t{constructor(e){this.id=mt.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){mt.removeItem(this.id)}}class vt extends R{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new _t({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 bt extends R{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new _t({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.canvas.boundary,t=e[2]/e[3],i=this._fovAxis;let s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),d.perspectiveMat4(s*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class yt extends R{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new _t({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,i=e.canvas.boundary,s=i[2],r=i[3],o=s/r;let n,a,l,A;s>r?(n=-t,a=t,l=t/o,A=-t/o):(n=-t*o,a=t*o,l=t,A=-t),d.orthoMat4c(n,a,A,l,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class xt extends R{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new _t({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._left=-1,this._right=1,this._bottom=-1,this._top=1,this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.left=t.left,this.right=t.right,this.bottom=t.bottom,this.top=t.top,this.near=t.near,this.far=t.far}_update(){d.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set left(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}get left(){return this._left}set right(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}get right(){return this._right}set top(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}get top(){return this._top}set bottom(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}get bottom(){return this._bottom}set near(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}get near(){return this._state.near}set far(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class Bt extends R{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new _t({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4()}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!1,this.matrix=t.matrix}set matrix(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}get matrix(){return this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy()}}const wt=d.vec3(),Pt=d.vec3(),Ct=d.vec3(),Mt=d.vec3(),Et=d.vec3(),Ft=d.vec3(),It=d.vec4(),Dt=d.vec4(),St=d.vec4(),Tt=d.mat4(),Rt=d.mat4(),Lt=d.vec3(),Ut=d.vec3(),kt=d.vec3(),Ot=d.vec3();class Nt extends R{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new _t({deviceMatrix:d.mat4(),hasDeviceMatrix:!1,matrix:d.mat4(),normalMatrix:d.mat4(),inverseMatrix:d.mat4()}),this._perspective=new bt(this),this._ortho=new yt(this),this._frustum=new xt(this),this._customProjection=new Bt(this),this._project=this._perspective,this._eye=d.vec3([0,0,10]),this._look=d.vec3([0,0,0]),this._up=d.vec3([0,1,0]),this._worldUp=d.vec3([0,1,0]),this._worldRight=d.vec3([1,0,0]),this._worldForward=d.vec3([0,0,-1]),this.deviceMatrix=t.deviceMatrix,this.eye=t.eye,this.look=t.look,this.up=t.up,this.worldAxis=t.worldAxis,this.gimbalLock=t.gimbalLock,this.constrainPitch=t.constrainPitch,this.projection=t.projection,this._perspective.on("matrix",(()=>{"perspective"===this._projectionType&&this.fire("projMatrix",this._perspective.matrix)})),this._ortho.on("matrix",(()=>{"ortho"===this._projectionType&&this.fire("projMatrix",this._ortho.matrix)})),this._frustum.on("matrix",(()=>{"frustum"===this._projectionType&&this.fire("projMatrix",this._frustum.matrix)})),this._customProjection.on("matrix",(()=>{"customProjection"===this._projectionType&&this.fire("projMatrix",this._customProjection.matrix)}))}_update(){const e=this._state;let t;"ortho"===this.projection?(d.subVec3(this._eye,this._look,Lt),d.normalizeVec3(Lt,Ut),d.mulVec3Scalar(Ut,1e3,kt),d.addVec3(this._look,kt,Ot),t=Ot):t=this._eye,e.hasDeviceMatrix?(d.lookAtMat4v(t,this._look,this._up,Rt),d.mulMat4(e.deviceMatrix,Rt,e.matrix)):d.lookAtMat4v(t,this._look,this._up,e.matrix),d.inverseMat4(this._state.matrix,this._state.inverseMatrix),d.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}orbitYaw(e){let t=d.subVec3(this._eye,this._look,wt);d.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,Tt),t=d.transformPoint3(Tt,t,Pt),this.eye=d.addVec3(this._look,t,Ct),this.up=d.transformPoint3(Tt,this._up,Mt)}orbitPitch(e){if(this._constrainPitch&&(e=d.dotVec3(this._up,this._worldUp)/d.DEGTORAD)<1)return;let t=d.subVec3(this._eye,this._look,wt);const i=d.cross3Vec3(d.normalizeVec3(t,Pt),d.normalizeVec3(this._up,Ct));d.rotationMat4v(.0174532925*e,i,Tt),t=d.transformPoint3(Tt,t,Mt),this.up=d.transformPoint3(Tt,this._up,Et),this.eye=d.addVec3(t,this._look,Ft)}yaw(e){let t=d.subVec3(this._look,this._eye,wt);d.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,Tt),t=d.transformPoint3(Tt,t,Pt),this.look=d.addVec3(t,this._eye,Ct),this._gimbalLock&&(this.up=d.transformPoint3(Tt,this._up,Mt))}pitch(e){if(this._constrainPitch&&(e=d.dotVec3(this._up,this._worldUp)/d.DEGTORAD)<1)return;let t=d.subVec3(this._look,this._eye,wt);const i=d.cross3Vec3(d.normalizeVec3(t,Pt),d.normalizeVec3(this._up,Ct));d.rotationMat4v(.0174532925*e,i,Tt),this.up=d.transformPoint3(Tt,this._up,Ft),t=d.transformPoint3(Tt,t,Mt),this.look=d.addVec3(t,this._eye,Et)}pan(e){const t=d.subVec3(this._eye,this._look,wt),i=[0,0,0];let s;if(0!==e[0]){const r=d.cross3Vec3(d.normalizeVec3(t,[]),d.normalizeVec3(this._up,Pt));s=d.mulVec3Scalar(r,e[0]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]}0!==e[1]&&(s=d.mulVec3Scalar(d.normalizeVec3(this._up,Ct),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=d.mulVec3Scalar(d.normalizeVec3(t,Mt),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=d.addVec3(this._eye,i,Et),this.look=d.addVec3(this._look,i,Ft)}zoom(e){const t=d.subVec3(this._eye,this._look,wt),i=Math.abs(d.lenVec3(t,Pt)),s=Math.abs(i+e);if(s<.5)return;const r=d.normalizeVec3(t,Ct);this.eye=d.addVec3(this._look,d.mulVec3Scalar(r,s),Mt)}set eye(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}get eye(){return this._eye}set look(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}get look(){return this._look}set up(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}get up(){return this._up}set deviceMatrix(e){this._state.deviceMatrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._state.hasDeviceMatrix=!!e,this._needUpdate(0),this.fire("deviceMatrix",this._state.deviceMatrix)}get deviceMatrix(){return this._state.deviceMatrix}set worldAxis(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=d.vec3(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}get worldAxis(){return this._worldAxis}get worldUp(){return this._worldUp}get xUp(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}get yUp(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}get zUp(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}get worldRight(){return this._worldRight}get worldForward(){return this._worldForward}set gimbalLock(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}get gimbalLock(){return this._gimbalLock}set constrainPitch(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}get eyeLookDist(){return d.lenVec3(d.subVec3(this._look,this._eye,wt))}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get viewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get normalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get viewNormalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get inverseViewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}get projMatrix(){return this[this.projection].matrix}get perspective(){return this._perspective}get ortho(){return this._ortho}get frustum(){return this._frustum}get customProjection(){return this._customProjection}set projection(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}get projection(){return this._projectionType}get project(){return this._project}projectWorldPos(e){const t=It,i=Dt,s=St;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,d.mulMat4v4(this.viewMatrix,t,i),d.mulMat4v4(this.projMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[s[0]*o+o,s[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}class Qt extends R{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class Vt extends Qt{get type(){return"DirLight"}constructor(e,t={}){super(e,t),this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const i=this.scene.camera,s=this.scene.canvas;this._onCameraViewMatrix=i.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=i.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=s.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new _t({type:"dir",dir:d.vec3([1,1,1]),color:d.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=d.identityMat4());const e=this.scene.camera,t=this._state.dir,i=e.look,s=[i[0]-t[0],i[1]-t[1],i[2]-t[2]],r=[0,1,0];d.lookAtMat4v(s,i,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=d.identityMat4()),d.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new ut(this.scene.canvas.canvas,this.scene.canvas.gl,{size:[1024,1024]})),this._shadowRenderBuf)}),this.dir=t.dir,this.color=t.color,this.intensity=t.intensity,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set dir(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get dir(){return this._state.dir}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}class Ht extends Qt{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:d.vec3([.7,.7,.7]),intensity:1},this.color=t.color,this.intensity=t.intensity,this.scene._lightCreated(this)}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}get intensity(){return this._state.intensity}destroy(){super.destroy(),this.scene._lightDestroyed(this)}}class jt extends R{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),m.memory.meshes++}destroy(){super.destroy(),m.memory.meshes--}}var Gt=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=d.vec3(),h=d.vec3(),c=d.vec3(),u=d.vec3(),p=d.vec3(),f=d.vec3(),g=d.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;ux)||(T=i[F.index1],R=i[F.index2],(!L&&T>65535||R>65535)&&(L=!0),y.push(T),y.push(R));return L?new Uint32Array(y):new Uint16Array(y)}}();const zt=function(){const e=d.mat4(),t=d.mat4();return function(i,s){s=s||d.mat4();const r=i[0],o=i[1],n=i[2],a=i[3]-r,l=i[4]-o,A=i[5]-n,h=65535;return d.identityMat4(e),d.translationMat4v(i,e),d.identityMat4(t),d.scalingMat4v([a/h,l/h,A/h],t),d.mulMat4(e,t,s),s}}();var Wt=function(){const e=d.mat4(),t=d.mat4();return function(i,s,r){const o=new Uint16Array(i.length),n=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);let a;for(a=0;a=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 Jt(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 Yt(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}const Zt={getPositionsBounds:function(e){const t=new Float32Array(3),i=new Float32Array(3);let s,r;for(s=0;s<3;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;sn&&(r=i,n=o),i=Xt(e,a,"floor","ceil"),s=Jt(i),o=Yt(e,a,s),o>n&&(r=i,n=o),i=Xt(e,a,"ceil","ceil"),s=Jt(i),o=Yt(e,a,s),o>n&&(r=i,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t},decompressNormal:function(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t}},qt=m.memory,$t=d.AABB3();class ei extends jt{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new _t({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=Zt.getPositionsBounds(t.positions),s=Zt.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=Zt.getUVBounds(t.uv),s=Zt.compressUVs(t.uv,e.min,e.max);i.uv=s.quantized,i.uvDecodeMatrix=s.decodeMatrix}else i.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?i.normals=Zt.compressNormals(t.normals):i.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(i.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)),this._buildHash(),qt.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new qe(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),qt.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new qe(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),qt.positions+=e.positionsBuf.numItems),e.normals){let i=e.compressGeometry;e.normalsBuf=new qe(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),qt.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new qe(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),qt.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new qe(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),qt.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=Gt(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new qe(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),qt.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=d.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new qe(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new qe(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),qt.positions+=this._pickTrianglePositionsBuf.numItems,qt.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),Zt.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=Zt.getPositionsBounds(e),s=Zt.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),Zt.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),Zt.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null}set uv(e){if(this._state.compressGeometry)return void this.error("can't update geometry UVs - quantized geometry is immutable");const t=this._state,i=t.uv;i?i.length===e.length?(i.set(e),t.uvBuf&&t.uvBuf.setData(i),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}get colors(){return this._state.colors}set colors(e){if(this._state.compressGeometry)return void this.error("can't update geometry colors - quantized geometry is immutable");const t=this._state,i=t.colors;i?i.length===e.length?(i.set(e),t.colorsBuf&&t.colorsBuf.setData(i),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}get indices(){return this._state.indices}get aabb(){return this._aabbDirty&&(this._aabb||(this._aabb=d.AABB3()),d.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=d.OBB3()),d.positions3ToAABB3(this._state.positions,$t,this._state.positionsDecodeMatrix),d.AABB3ToOBB3($t,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(),qt.meshes--}}function ti(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return y.apply(e,{positions:[c,u,d,l,u,d,l,A,d,c,A,d,c,u,d,c,A,d,c,A,h,c,u,h,c,u,d,c,u,h,l,u,h,l,u,d,l,u,d,l,u,h,l,A,h,l,A,d,l,A,h,c,A,h,c,A,d,l,A,d,c,A,h,l,A,h,l,u,h,c,u,h],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 ii extends R{get type(){return"Material"}constructor(e,t={}){super(e,t),m.memory.materials++}destroy(){super.destroy(),m.memory.materials--}}const si={opaque:0,mask:1,blend:2},ri=["opaque","mask","blend"];class oi extends ii{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new _t({type:"PhongMaterial",ambient:d.vec3([1,1,1]),diffuse:d.vec3([1,1,1]),specular:d.vec3([1,1,1]),emissive:d.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.ambient=t.ambient,this.diffuse=t.diffuse,this.specular=t.specular,this.emissive=t.emissive,this.alpha=t.alpha,this.shininess=t.shininess,this.reflectivity=t.reflectivity,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,t.ambientMap&&(this._ambientMap=this._checkComponent("Texture",t.ambientMap)),t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.reflectivityMap&&(this._reflectivityMap=this._checkComponent("Texture",t.reflectivityMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.diffuseFresnel&&(this._diffuseFresnel=this._checkComponent("Fresnel",t.diffuseFresnel)),t.specularFresnel&&(this._specularFresnel=this._checkComponent("Fresnel",t.specularFresnel)),t.emissiveFresnel&&(this._emissiveFresnel=this._checkComponent("Fresnel",t.emissiveFresnel)),t.alphaFresnel&&(this._alphaFresnel=this._checkComponent("Fresnel",t.alphaFresnel)),t.reflectivityFresnel&&(this._reflectivityFresnel=this._checkComponent("Fresnel",t.reflectivityFresnel)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this._makeHash()}_makeHash(){const e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}set shininess(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}get shininess(){return this._state.shininess}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set reflectivity(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}get reflectivity(){return this._state.reflectivity}get normalMap(){return this._normalMap}get ambientMap(){return this._ambientMap}get diffuseMap(){return this._diffuseMap}get specularMap(){return this._specularMap}get emissiveMap(){return this._emissiveMap}get alphaMap(){return this._alphaMap}get reflectivityMap(){return this._reflectivityMap}get occlusionMap(){return this._occlusionMap}get diffuseFresnel(){return this._diffuseFresnel}get specularFresnel(){return this._specularFresnel}get emissiveFresnel(){return this._emissiveFresnel}get alphaFresnel(){return this._alphaFresnel}get reflectivityFresnel(){return this._reflectivityFresnel}set alphaMode(e){let t=si[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 ri[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}destroy(){super.destroy(),this._state.destroy()}}const ni={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}};class ai extends ii{get type(){return"EmphasisMaterial"}get presets(){return ni}constructor(e,t={}){super(e,t),this._state=new _t({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),this._preset="default",t.preset?(this.preset=t.preset,void 0!==t.fill&&(this.fill=t.fill),t.fillColor&&(this.fillColor=t.fillColor),void 0!==t.fillAlpha&&(this.fillAlpha=t.fillAlpha),void 0!==t.edges&&(this.edges=t.edges),t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth),void 0!==t.backfaces&&(this.backfaces=t.backfaces),void 0!==t.glowThrough&&(this.glowThrough=t.glowThrough)):(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.backfaces=t.backfaces,this.glowThrough=t.glowThrough)}set fill(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}get fill(){return this._state.fill}set fillColor(e){let t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}get fillColor(){return this._state.fillColor}set fillAlpha(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}get fillAlpha(){return this._state.fillAlpha}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set glowThrough(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}get glowThrough(){return this._state.glowThrough}set preset(e){if(e=e||"default",this._preset===e)return;const t=ni[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(ni).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const li={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 Ai extends ii{get type(){return"EdgeMaterial"}get presets(){return li}constructor(e,t={}){super(e,t),this._state=new _t({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),this._preset="default",t.preset?(this.preset=t.preset,t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth)):(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth),this.edges=!1!==t.edges}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=li[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(li).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const hi={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 ci extends R{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=d.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return hi}set units(e){e||(e="meters");hi[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}get units(){return this._units}set scale(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}get scale(){return this._scale}set origin(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}get origin(){return this._origin}worldToRealPos(e,t=d.vec3(3)){t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}realToWorldPos(e,t=d.vec3(3)){return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}class ui extends R{constructor(e,t={}){super(e,t),this._supported=He.SUPPORTED_EXTENSIONS.OES_standard_derivatives,this.enabled=t.enabled,this.kernelRadius=t.kernelRadius,this.intensity=t.intensity,this.bias=t.bias,this.scale=t.scale,this.minResolution=t.minResolution,this.numSamples=t.numSamples,this.blur=t.blur,this.blendCutoff=t.blendCutoff,this.blendFactor=t.blendFactor}get supported(){return this._supported}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}get enabled(){return this._enabled}get possible(){if(!this._supported)return!1;if(!this._enabled)return!1;const e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}get active(){return this._active}set kernelRadius(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}get kernelRadius(){return this._kernelRadius}set intensity(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}get intensity(){return this._intensity}set bias(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}get bias(){return this._bias}set scale(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}get scale(){return this._scale}set minResolution(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}get minResolution(){return this._minResolution}set numSamples(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}get numSamples(){return this._numSamples}set blur(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}get blur(){return this._blur}set blendCutoff(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}get blendCutoff(){return this._blendCutoff}set blendFactor(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}get blendFactor(){return this._blendFactor}destroy(){super.destroy()}}class di extends R{constructor(e,t={}){super(e,t),this.sliceColor=t.sliceColor,this.sliceThickness=t.sliceThickness}set sliceThickness(e){null==e&&(e=0),this._sliceThickness!==e&&(this._sliceThickness=e,this.glRedraw())}get sliceThickness(){return this._sliceThickness}set sliceColor(e){null==e&&(e=[0,0,0,1]),this._sliceColor!==e&&(this._sliceColor=e,this.glRedraw())}get sliceColor(){return this._sliceColor}destroy(){super.destroy()}}const pi={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class fi extends ii{get type(){return"PointsMaterial"}get presets(){return pi}constructor(e,t={}){super(e,t),this._state=new _t({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),t.preset?(this.preset=t.preset,void 0!==t.pointSize&&(this.pointSize=t.pointSize),void 0!==t.roundPoints&&(this.roundPoints=t.roundPoints),void 0!==t.perspectivePoints&&(this.perspectivePoints=t.perspectivePoints),void 0!==t.minPerspectivePointSize&&(this.minPerspectivePointSize=t.minPerspectivePointSize),void 0!==t.maxPerspectivePointSize&&(this.maxPerspectivePointSize=t.minPerspectivePointSize)):(this._preset="default",this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize),this.filterIntensity=t.filterIntensity,this.minIntensity=t.minIntensity,this.maxIntensity=t.maxIntensity}set pointSize(e){this._state.pointSize=e||2,this.glRedraw()}get pointSize(){return this._state.pointSize}set roundPoints(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}get roundPoints(){return this._state.roundPoints}set perspectivePoints(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}get perspectivePoints(){return this._state.perspectivePoints}set minPerspectivePointSize(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}get minPerspectivePointSize(){return this._state.minPerspectivePointSize}set maxPerspectivePointSize(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}get maxPerspectivePointSize(){return this._state.maxPerspectivePointSize}set filterIntensity(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}get filterIntensity(){return this._state.filterIntensity}set minIntensity(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}get minIntensity(){return this._state.minIntensity}set maxIntensity(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}get maxIntensity(){return this._state.maxIntensity}set preset(e){if(e=e||"default",this._preset===e)return;const t=pi[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(pi).join(", "))}get preset(){return this._preset}get hash(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}destroy(){super.destroy(),this._state.destroy()}}const gi={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class mi extends ii{get type(){return"LinesMaterial"}get presets(){return gi}constructor(e,t={}){super(e,t),this._state=new _t({type:"LinesMaterial",lineWidth:null}),t.preset?(this.preset=t.preset,void 0!==t.lineWidth&&(this.lineWidth=t.lineWidth)):(this._preset="default",this.lineWidth=t.lineWidth)}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=gi[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(gi).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function _i(e,t){const i={};let s,r;for(let o=0,n=t.length;o{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new ft(this,{transparent:s,alphaDepthMask:r}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;let e=null;this.getHash=function(){if(e)return e;const t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";const i=[];for(let e=0,s=t;ethis._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},this._sectionPlanesState.setNumCachedSectionPlanes(t.numCachedSectionPlanes||0),this._lightsState=new function(){const e=d.vec4([0,0,0,0]),t=d.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let i=null,s=null;this.getHash=function(){if(i)return i;const e=[],t=this.lights;let s;for(let i=0,r=t.length;i0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),i=e.join(""),i},this.addLight=function(e){this.lights.push(e),s=null,i=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t{this._renderer.imageDirty()}))}_initDefaults(){}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+y.inQuotes(e.id)+" already exists in Scene - ignoring ID, will randomly-generate instead"),e.id=null),!e.id)for(void 0===window.nextID&&(window.nextID=0),e.id="__"+window.nextID++;this.components[e.id];)e.id=d.createUUID();this.components[e.id]=e;const t=e.type;let i=this.types[e.type];i||(i=this.types[t]={}),i[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,i=e.type;delete this.components[t];const s=this.types[i];s&&(delete s[t],y.isEmptyObject(s)&&delete this.types[i]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_deRegisterVisibleObject(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_deRegisterXRayedObject(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}_objectHighlightedUpdated(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}_deRegisterHighlightedObject(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_deRegisterSelectedObject(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_deRegisterColorizedObject(e){delete this.colorizedObjects[e.id],this._numColorizedObjects--,this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_deRegisterOpacityObject(e){delete this.opacityObjects[e.id],this._numOpacityObjects--,this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_deRegisterOffsetObject(e){delete this.offsetObjects[e.id],this._numOffsetObjects--,this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get readableGeometryEnabled(){return this._readableGeometry}get pickSurfacePrecisionEnabled(){return this._readableGeometry}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set numCachedSectionPlanes(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}get numCachedSectionPlanes(){return this._sectionPlanesState.getNumCachedSectionPlanes()}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}get markerZOffset(){return null==this._markerZOffset?-.001:this._markerZOffset}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&I.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const i=this._passes,s=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),A=!0}A||(t=-100,i=-100,s=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=n,this._aabbDirty=!1,this._center=null}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const i=e.includeEntities||e.include;i&&(e.includeEntityIds=_i(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=_i(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){if(void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),e.canvasPos)return this._renderer.snapPick(e);this.error("Scene.snapPick() canvasPos parameter expected")}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,i=e.length;t{if(e.collidable){const l=e.aabb;l[0]o&&(o=l[3]),l[4]>n&&(n=l[4]),l[5]>a&&(a=l[5]),t=!0}})),t){const e=d.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=o,e[4]=n,e[5]=a,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const i=e.visible!==t;return e.visible=t,i}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const i=e.collidable!==t;return e.collidable=t,i}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const i=e.culled!==t;return e.culled=t,i}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const i=e.selected!==t;return e.selected=t,i}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const i=e.highlighted!==t;return e.highlighted=t,i}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const i=e.xrayed!==t;return e.xrayed=t,i}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const i=e.edges!==t;return e.edges=t,i}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const i=e.opacity!==t;return e.opacity=t,i}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const i=e.pickable!==t;return e.pickable=t,i}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){y.isString(e)&&(e=[e]);let i=!1;for(let s=0,r=e.length;s{r>s&&(s=r,e(...i))}));return this._tickifiedFunctions[t]={tickSubId:n,wrapperFunc:o},o}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const bi=1e3,yi=1001,xi=1002,Bi=1003,wi=1004,Pi=1004,Ci=1005,Mi=1005,Ei=1006,Fi=1007,Ii=1007,Di=1008,Si=1008,Ti=1009,Ri=1010,Li=1011,Ui=1012,ki=1013,Oi=1014,Ni=1015,Qi=1016,Vi=1017,Hi=1018,ji=1020,Gi=1021,zi=1022,Wi=1023,Ki=1024,Xi=1025,Ji=1026,Yi=1027,Zi=1028,qi=1029,$i=1030,es=1031,ts=1033,is=33776,ss=33777,rs=33778,os=33779,ns=35840,as=35841,ls=35842,As=35843,hs=36196,cs=37492,us=37496,ds=37808,ps=37809,fs=37810,gs=37811,ms=37812,_s=37813,vs=37814,bs=37815,ys=37816,xs=37817,Bs=37818,ws=37819,Ps=37820,Cs=37821,Ms=36492,Es=3e3,Fs=3001,Is=1e4,Ds=10001,Ss=10002,Ts=10003,Rs=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene._lightsState,r=e._geometry._state,o=e._state.billboard,n=e._state.stationary,a=i.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,A=[];A.push("#version 300 es"),A.push("// Lambertian drawing vertex shader"),A.push("in vec3 position;"),A.push("uniform mat4 modelMatrix;"),A.push("uniform mat4 viewMatrix;"),A.push("uniform mat4 projMatrix;"),A.push("uniform vec4 colorize;"),A.push("uniform vec3 offset;"),l&&A.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(A.push("uniform float logDepthBufFC;"),A.push("out float vFragDepth;"),A.push("bool isPerspectiveMatrix(mat4 m) {"),A.push(" return (m[2][3] == - 1.0);"),A.push("}"),A.push("out float isPerspective;"));a&&A.push("out vec4 vWorldPosition;");if(A.push("uniform vec4 lightAmbient;"),A.push("uniform vec4 materialColor;"),A.push("uniform vec3 materialEmissive;"),r.normalsBuf){A.push("in vec3 normal;"),A.push("uniform mat4 modelNormalMatrix;"),A.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),A.push(" }"),A.push(" return normalize(v);"),A.push("}"))}A.push("out vec4 vColor;"),"points"===r.primitiveName&&A.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(A.push("void billboard(inout mat4 mat) {"),A.push(" mat[0][0] = 1.0;"),A.push(" mat[0][1] = 0.0;"),A.push(" mat[0][2] = 0.0;"),"spherical"===o&&(A.push(" mat[1][0] = 0.0;"),A.push(" mat[1][1] = 1.0;"),A.push(" mat[1][2] = 0.0;")),A.push(" mat[2][0] = 0.0;"),A.push(" mat[2][1] = 0.0;"),A.push(" mat[2][2] =1.0;"),A.push("}"));A.push("void main(void) {"),A.push("vec4 localPosition = vec4(position, 1.0); "),A.push("vec4 worldPosition;"),l&&A.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?A.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):A.push("vec4 localNormal = vec4(normal, 0.0); "),A.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),A.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));A.push("mat4 viewMatrix2 = viewMatrix;"),A.push("mat4 modelMatrix2 = modelMatrix;"),n&&A.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(A.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),A.push("billboard(modelMatrix2);"),A.push("billboard(viewMatrix2);"),A.push("billboard(modelViewMatrix);"),r.normalsBuf&&(A.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),A.push("billboard(modelNormalMatrix2);"),A.push("billboard(viewNormalMatrix2);"),A.push("billboard(modelViewNormalMatrix);")),A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&A.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(A.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),A.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),A.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=s.lights.length;e0,o=t.gammaOutput,n=[];n.push("#version 300 es"),n.push("// Lambertian drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));if(r){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}"points"===s.primitiveName&&(n.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push("float r = dot(cxy, cxy);"),n.push("if (r > 1.0) {"),n.push(" discard;"),n.push("}"));t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");o?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(e)):(this.vertex=function(e){const t=e.scene;e._material;const i=e._state,s=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=i.billboard,l=i.background,A=i.stationary,h=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),c=ks(e),u=s.getNumAllocatedSectionPlanes()>0,d=Us(e),p=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),p&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),u&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));o.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(c){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(let e=0,t=o.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}h&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),p&&f.push("uniform mat3 uvDecodeMatrix;"));r.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===r.primitiveName&&f.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = 1.0;"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===a&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = 1.0;"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(d){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(let e=0,t=o.lights.length;e0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(let e=0,t=o.lights.length;e0,l=ks(e),A=s.uvBuf,h="PhongMaterial"===n.type,c="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,d=Us(e);t.gammaInput;const p=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));d&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),p&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var g=0;g0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),o.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),h&&((o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = "+Ls[o.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(c||u)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),o.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+Ls[o.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),s.colors&&f.push("in vec4 vColor;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._occlusionMap||i._alphaMap)&&f.push("in vec2 vUV;");l&&(o.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));n.ambient&&f.push("uniform vec3 materialAmbient;");n.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==n.alpha&&null!==n.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");n.emissive&&f.push("uniform vec3 materialEmissive;");n.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==n.glossiness&&null!==n.glossiness&&f.push("uniform float materialGlossiness;");void 0!==n.shininess&&null!==n.shininess&&f.push("uniform float materialShininess;");n.specular&&f.push("uniform vec3 materialSpecular;");void 0!==n.metallic&&null!==n.metallic&&f.push("uniform float materialMetallic;");void 0!==n.roughness&&null!==n.roughness&&f.push("uniform float materialRoughness;");void 0!==n.specularF0&&null!==n.specularF0&&f.push("uniform float materialSpecularF0;");A&&i._ambientMap&&(f.push("uniform sampler2D ambientMap;"),i._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));A&&i._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),i._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));A&&i._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),i._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));A&&i._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),i._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&A&&i._metallicMap&&(f.push("uniform sampler2D metallicMap;"),i._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&A&&i._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),i._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&A&&i._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),i._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&i._normalMap&&(f.push("uniform sampler2D normalMap;"),i._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));A&&i._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),i._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));A&&i._alphaMap&&(f.push("uniform sampler2D alphaMap;"),i._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&A&&i._specularMap&&(f.push("uniform sampler2D specularMap;"),i._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&A&&i._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),i._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&A&&i._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),i._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(i._diffuseFresnel||i._specularFresnel||i._alphaFresnel||i._emissiveFresnel||i._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),i._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),i._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),i._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),i._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),i._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(let e=0,t=o.lights.length;e 0.0) { discard; }"),f.push("}")}"points"===s.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),n.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");n.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):n.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");s.colors&&f.push("diffuseColor *= vColor.rgb;");n.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");n.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==n.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");s.colors&&f.push("alpha *= vColor.a;");void 0!==n.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==n.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==n.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==n.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._occlusionMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));A&&i._ambientMap&&(i._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+Ls[i._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));A&&i._diffuseMap&&(i._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+Ls[i._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));A&&i._baseColorMap&&(i._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+Ls[i._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));A&&i._emissiveMap&&(i._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+Ls[i._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));A&&i._alphaMap&&(i._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));A&&i._occlusionMap&&(i._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(o.lights.length>0||o.lightMaps.length>0||o.reflectionMaps.length>0)){A&&i._normalMap?(i._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),A&&i._specularMap&&(i._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),A&&i._glossinessMap&&(i._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),A&&i._specularGlossinessMap&&(i._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),A&&i._metallicMap&&(i._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),A&&i._roughnessMap&&(i._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),A&&i._metallicRoughnessMap&&(i._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),i._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),i._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),i._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),i._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),h&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),u&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),c&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),o.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),h&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(u||c)&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(let e=0,t=o.lights.length;e0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(h=0,c=o.sectionPlanes.length;h0&&r.lightMaps[0].texture&&this._uLightMap&&(a.bindTexture(this._uLightMap,r.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),r.reflectionMaps.length>0&&r.reflectionMaps[0].texture&&this._uReflectionMap&&(a.bindTexture(this._uReflectionMap,r.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor),this._baseTextureUnit=e.textureUnit};class Hs{constructor(e){this.vertex=function(e){const t=e.scene,i=t._lightsState,s=function(e){const t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),r=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,o=!!e._geometry._state.compressGeometry,n=e._state.billboard,a=e._state.stationary,l=[];l.push("#version 300 es"),l.push("// EmphasisFillShaderSource vertex shader"),l.push("in vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),l.push("uniform vec3 offset;"),o&&l.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;"));r&&l.push("out vec4 vWorldPosition;");if(l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),s){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"))}l.push("out vec4 vColor;"),("spherical"===n||"cylindrical"===n)&&(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = 1.0;"),l.push(" mat[0][1] = 0.0;"),l.push(" mat[0][2] = 0.0;"),"spherical"===n&&(l.push(" mat[1][0] = 0.0;"),l.push(" mat[1][1] = 1.0;"),l.push(" mat[1][2] = 0.0;")),l.push(" mat[2][0] = 0.0;"),l.push(" mat[2][1] = 0.0;"),l.push(" mat[2][2] =1.0;"),l.push("}"));l.push("void main(void) {"),l.push("vec4 localPosition = vec4(position, 1.0); "),l.push("vec4 worldPosition;"),o&&l.push("localPosition = positionsDecodeMatrix * localPosition;");s&&(o?l.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):l.push("vec4 localNormal = vec4(normal, 0.0); "),l.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),l.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));l.push("mat4 viewMatrix2 = viewMatrix;"),l.push("mat4 modelMatrix2 = modelMatrix;"),a&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===n||"cylindrical"===n?(l.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),l.push("billboard(modelMatrix2);"),l.push("billboard(viewMatrix2);"),l.push("billboard(modelViewMatrix);"),s&&(l.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),l.push("billboard(modelNormalMatrix2);"),l.push("billboard(viewNormalMatrix2);"),l.push("billboard(modelViewNormalMatrix);")),l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),s)for(let e=0,t=i.lights.length;e0,o=[];o.push("#version 300 es"),o.push("// Lambertian drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}"points"===e._geometry._state.primitiveName&&(o.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("float r = dot(cxy, cxy);"),o.push("if (r > 1.0) {"),o.push(" discard;"),o.push("}"));t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const js=new e({}),Gs=d.vec3(),zs=function(e,t){this.id=js.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Hs(t),this._allocate(t)},Ws={};zs.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=Ws[t];return i||(i=new zs(t,e),Ws[t]=i,m.memory.programs++),i._useCount++,i},zs.prototype.put=function(){0==--this._useCount&&(js.removeItem(this.id),this._program&&this._program.destroy(),delete Ws[this._hash],m.memory.programs--)},zs.prototype.webglContextRestored=function(){this._program=null},zs.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl,n=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,A=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,A?e.getRTCViewMatrix(a.originHash,A):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Edges drawing vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec4 edgeColor;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));i&&n.push("out vec4 vWorldPosition;");n.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n.push("vColor = edgeColor;"),i&&n.push("vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.getNumAllocatedSectionPlanes()>0,o=[];o.push("#version 300 es"),o.push("// Edges drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const Xs=new e({}),Js=d.vec3(),Ys=function(e,t){this.id=Xs.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Ks(t),this._allocate(t)},Zs={};Ys.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=Zs[t];return i||(i=new Ys(t,e),Zs[t]=i,m.memory.programs++),i._useCount++,i},Ys.prototype.put=function(){0==--this._useCount&&(Xs.removeItem(this.id),this._program&&this._program.destroy(),delete Zs[this._hash],m.memory.programs--)},Ys.prototype.webglContextRestored=function(){this._program=null},Ys.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl;let n;const a=t._state,l=t._geometry,A=l._state,h=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(a.originHash,h):r.viewMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh picking vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("out vec4 vViewPosition;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("uniform vec2 pickClipPos;"),n.push("vec4 remapClipPos(vec4 clipPos) {"),n.push(" clipPos.xy /= clipPos.w;"),n.push(" clipPos.xy -= pickClipPos;"),n.push(" clipPos.xy *= clipPos.w;"),n.push(" return clipPos;"),n.push("}"),n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==r&&"cylindrical"!==r||(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"));n.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = remapClipPos(clipPos);"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(r.push("uniform vec4 pickColor;"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = pickColor; "),r.push("}"),r}(e)}}const $s=d.vec3(),er=function(e,t){this._hash=e,this._shaderSource=new qs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},tr={};er.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=tr[t];if(!i){if(i=new er(t,e),i.errors)return console.log(i.errors.join("\n")),null;tr[t]=i,m.memory.programs++}return i._useCount++,i},er.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete tr[this._hash],m.memory.programs--)},er.prototype.webglContextRestored=function(){this._program=null},er.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t>24&255,h=l>>16&255,c=l>>8&255,u=255&l;s.uniform4f(this._uPickColor,u/255,c/255,h/255,A/255),s.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(s.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&s.drawArrays(s.TRIANGLES,0,n.positions.numItems)},er.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Ze(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0,s=!!e._geometry._state.compressGeometry,r=[];r.push("#version 300 es"),r.push("// Surface picking vertex shader"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),i&&(r.push("uniform bool clippable;"),r.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));r.push("uniform vec2 pickClipPos;"),r.push("vec4 remapClipPos(vec4 clipPos) {"),r.push(" clipPos.xy /= clipPos.w;"),r.push(" clipPos.xy -= pickClipPos;"),r.push(" clipPos.xy *= clipPos.w;"),r.push(" return clipPos;"),r.push("}"),r.push("out vec4 vColor;"),s&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),s&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),i&&r.push(" vWorldPosition = worldPosition;");r.push(" vColor = color;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = remapClipPos(clipPos);"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Surface picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),r.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = vColor;"),r.push("}"),r}(e)}}const sr=d.vec3(),rr=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new ir(t),this._allocate(t)},or={};rr.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=or[t];if(!i){if(i=new rr(t,e),i.errors)return console.log(i.errors.join("\n")),null;or[t]=i,m.memory.programs++}return i._useCount++,i},rr.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete or[this._hash],m.memory.programs--)},rr.prototype.webglContextRestored=function(){this._program=null},rr.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,A=o.backfaces,h=o.frontface,c=i.camera.project,u=n._getPickTrianglePositions(),d=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,i.logarithmicDepthBufferEnabled){const e=2/(Math.log(c.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}if(s.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh occlusion vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push("}"),r}(e)}}const ar=d.vec3(),lr=function(e,t){this._hash=e,this._shaderSource=new nr(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ar={};lr.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let i=Ar[t];if(!i){if(i=new lr(t,e),i.errors)return console.log(i.errors.join("\n")),null;Ar[t]=i,m.memory.programs++}return i._useCount++,i},lr.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ar[this._hash],m.memory.programs--)},lr.prototype.webglContextRestored=function(){this._program=null},lr.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._material._state,o=t._state,n=t._geometry._state,a=t.origin;if(r.alpha<1)return;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){const t=r.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=r.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),this._lastMaterialId=r.id}const l=i.camera;if(s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!e._geometry._state.compressGeometry,s=[];s.push("// Mesh shadow vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),s.push("uniform vec3 offset;"),i&&s.push("uniform mat4 positionsDecodeMatrix;");t&&s.push("out vec4 vWorldPosition;");s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),s.push("vec4 worldPosition;"),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;");s.push("worldPosition = modelMatrix * localPosition;"),s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&s.push("vWorldPosition = worldPosition;");return s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(e)}}const cr=function(e,t){this._hash=e,this._shaderSource=new hr(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},ur={};cr.get=function(e){const t=e.scene,i=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=ur[i];if(!s){if(s=new cr(i,e),s.errors)return console.log(s.errors.join("\n")),null;ur[i]=s,m.memory.programs++}return s._useCount++,s},cr.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete ur[this._hash],m.memory.programs--)},cr.prototype.webglContextRestored=function(){this._program=null},cr.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene.canvas.gl,s=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.id!==this._lastMaterialId){const t=s.backfaces;e.backfaces!==t&&(t?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const r=s.frontface;e.frontface!==r&&(r?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=r),e.lineWidth!==s.lineWidth&&(i.lineWidth(s.lineWidth),e.lineWidth=s.lineWidth),this._uPointSize&&i.uniform1i(this._uPointSize,s.pointSize),this._lastMaterialId=s.id}if(i.uniformMatrix4fv(this._uModelMatrix,i.FALSE,t.worldMatrix),r.combineGeometry){const s=t.vertexBufs;s.id!==this._lastVertexBufsId&&(s.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(s.positionsBuf,s.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),this._lastVertexBufsId=s.id)}this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),i.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(i.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(i.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(i.drawArrays(i.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},cr.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Ze(i,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a0)for(let i=0;i0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const Pr=function(){const e=d.vec3(),t=d.vec3(),i=d.vec3(),s=d.vec3(),r=d.vec3(),o=d.vec3(),n=d.vec4(),a=d.vec3(),l=d.vec3(),A=d.vec3(),h=d.vec3(),c=d.vec3(),u=d.vec3(),p=d.vec3(),f=d.vec3(),g=d.vec3(),m=d.vec4(),_=d.vec4(),v=d.vec4(),b=d.vec3(),y=d.vec3(),x=d.vec3(),B=d.vec3(),w=d.vec3(),P=d.vec3(),C=d.vec3(),M=d.vec3(),E=d.vec3(),F=d.vec3(),I=d.vec3();return function(D,S,T,R,L){var U=L.primIndex;if(null!=U&&U>-1){const Q=D.geometry._state,V=D.scene,H=V.camera,j=V.canvas;if("triangles"===Q.primitiveName){L.primitive="triangle";const V=U,G=Q.indices,z=Q.positions;let W,K,X;if(G){var k=G[V+0],O=G[V+1],N=G[V+2];o[0]=k,o[1]=O,o[2]=N,L.indices=o,W=3*k,K=3*O,X=3*N}else W=3*V,K=W+3,X=K+3;if(i[0]=z[W+0],i[1]=z[W+1],i[2]=z[W+2],s[0]=z[K+0],s[1]=z[K+1],s[2]=z[K+2],r[0]=z[X+0],r[1]=z[X+1],r[2]=z[X+2],Q.compressGeometry){const e=Q.positionsDecodeMatrix;e&&(Zt.decompressPosition(i,e,i),Zt.decompressPosition(s,e,s),Zt.decompressPosition(r,e,r))}L.canvasPos?d.canvasPosToLocalRay(j.canvas,D.origin?J(S,D.origin):S,T,R,D.worldMatrix,L.canvasPos,e,t):L.origin&&L.direction&&d.worldRayToLocalRay(D.worldMatrix,L.origin,L.direction,e,t),d.normalizeVec3(t),d.rayPlaneIntersect(e,t,i,s,r,n),L.localPos=n,L.position=n,m[0]=n[0],m[1]=n[1],m[2]=n[2],m[3]=1,d.transformVec4(D.worldMatrix,m,_),a[0]=_[0],a[1]=_[1],a[2]=_[2],L.canvasPos&&D.origin&&(a[0]+=D.origin[0],a[1]+=D.origin[1],a[2]+=D.origin[2]),L.worldPos=a,d.transformVec4(H.matrix,_,v),l[0]=v[0],l[1]=v[1],l[2]=v[2],L.viewPos=l,d.cartesianToBarycentric(n,i,s,r,A),L.bary=A;const Y=Q.normals;if(Y){if(Q.compressGeometry){const e=3*k,t=3*O,i=3*N;Zt.decompressNormal(Y.subarray(e,e+2),h),Zt.decompressNormal(Y.subarray(t,t+2),c),Zt.decompressNormal(Y.subarray(i,i+2),u)}else h[0]=Y[W],h[1]=Y[W+1],h[2]=Y[W+2],c[0]=Y[K],c[1]=Y[K+1],c[2]=Y[K+2],u[0]=Y[X],u[1]=Y[X+1],u[2]=Y[X+2];const e=d.addVec3(d.addVec3(d.mulVec3Scalar(h,A[0],b),d.mulVec3Scalar(c,A[1],y),x),d.mulVec3Scalar(u,A[2],B),w);L.worldNormal=d.normalizeVec3(d.transformVec3(D.worldNormalMatrix,e,P))}const Z=Q.uv;if(Z){if(p[0]=Z[2*k],p[1]=Z[2*k+1],f[0]=Z[2*O],f[1]=Z[2*O+1],g[0]=Z[2*N],g[1]=Z[2*N+1],Q.compressGeometry){const e=Q.uvDecodeMatrix;e&&(Zt.decompressUV(p,e,p),Zt.decompressUV(f,e,f),Zt.decompressUV(g,e,g))}L.uv=d.addVec3(d.addVec3(d.mulVec2Scalar(p,A[0],C),d.mulVec2Scalar(f,A[1],M),E),d.mulVec2Scalar(g,A[2],F),I)}}}}}();function Cr(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);let s=e.height||1;s<0&&(console.error("negative height not allowed - will invert"),s*=-1);let r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<3&&(r=3);let o=e.heightSegments||1;o<0&&(console.error("negative heightSegments not allowed - will invert"),o*=-1),o<1&&(o=1);const n=!!e.openEnded;let a=e.center;const l=a?a[0]:0,A=a?a[1]:0,h=a?a[2]:0,c=s/2,u=s/o,d=2*Math.PI/r,p=1/r,f=(t-i)/o,g=[],m=[],_=[],v=[];let b,x,B,w,P,C,M,E,F,I,D;const S=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(b=0;b<=o;b++)for(P=t-b*f,C=c-b*u,x=0;x<=r;x++)B=Math.sin(x*d),w=Math.cos(x*d),m.push(P*B),m.push(S),m.push(P*w),_.push(x*p),_.push(1*b/o),g.push(P*B+l),g.push(C+A),g.push(P*w+h);for(b=0;b0){for(F=g.length/3,m.push(0),m.push(1),m.push(0),_.push(.5),_.push(.5),g.push(0+l),g.push(c+A),g.push(0+h),x=0;x<=r;x++)B=Math.sin(x*d),w=Math.cos(x*d),I=.5*Math.sin(x*d)+.5,D=.5*Math.cos(x*d)+.5,m.push(t*B),m.push(1),m.push(t*w),_.push(I),_.push(D),g.push(t*B+l),g.push(c+A),g.push(t*w+h);for(x=0;x0){for(F=g.length/3,m.push(0),m.push(-1),m.push(0),_.push(.5),_.push(.5),g.push(0+l),g.push(0-c+A),g.push(0+h),x=0;x<=r;x++)B=Math.sin(x*d),w=Math.cos(x*d),I=.5*Math.sin(x*d)+.5,D=.5*Math.cos(x*d)+.5,m.push(i*B),m.push(-1),m.push(i*w),_.push(I),_.push(D),g.push(i*B+l),g.push(0-c+A),g.push(i*w+h);for(x=0;x":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function Fr(e={}){var t=e.origin||[0,0,0],i=t[0],s=t[1],r=t[2],o=e.size||1,n=[],a=[],l=e.text;y.isNumeric(l)&&(l=""+l);for(var A,h,c,u,d,p,f,g,m,_=(l||"").split("\n"),v=0,b=0,x=.04,B=0;B<_.length;B++){A=0,c=(h=_[B]).length;for(var w=0;w0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let i=0,s=e.length;i1;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);const o=Jr(i,this.wrapS);o&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,o);const n=Jr(i,this.wrapT);if(n&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,n),this.type===i.TEXTURE_3D||this.type===i.TEXTURE_2D_ARRAY){const e=Jr(i,this.wrapR);e&&i.texParameteri(this.target,i.TEXTURE_WRAP_R,e),i.texParameteri(this.type,i.TEXTURE_WRAP_R,e)}r?(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,$r(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,$r(i,this.magFilter))):(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,Jr(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,Jr(i,this.magFilter)));const a=Jr(i,this.format,this.encoding),l=Jr(i,this.type),A=qr(i,this.internalFormat,a,l,this.encoding,!1);i.texStorage2D(i.TEXTURE_2D,s,A,e[0].width,e[0].height);for(let t=0,s=e.length;t>t;return e+1}class so extends R{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new _t({texture:new Zr({gl:this.scene.canvas.gl}),matrix:d.identityMat4(),hasMatrix:t.translate&&(0!==t.translate[0]||0!==t.translate[1])||!!t.rotate||t.scale&&(0!==t.scale[0]||0!==t.scale[1]),minFilter:this._checkMinFilter(t.minFilter),magFilter:this._checkMagFilter(t.magFilter),wrapS:this._checkWrapS(t.wrapS),wrapT:this._checkWrapT(t.wrapT),flipY:this._checkFlipY(t.flipY),encoding:this._checkEncoding(t.encoding)}),this._src=null,this._image=null,this._translate=d.vec2([0,0]),this._scale=d.vec2([1,1]),this._rotate=d.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),m.memory.textures++}_checkMinFilter(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}_checkMagFilter(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}_checkWrapS(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkWrapT(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this._state.texture=new Zr({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,i;0===this._translate[0]&&0===this._translate[1]||(t=d.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(i=d.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?d.mulMat4(t,i):i),0!==this._rotate&&(i=d.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?d.mulMat4(t,i):i),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=eo(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let i=new Image;i.onload=function(){i=eo(i),t._state.texture.setImage(i,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),m.memory.textures--}}class ro extends R{get type(){return"Fresnel"}constructor(e,t={}){super(e,t),this._state=new _t({edgeColor:d.vec3([0,0,0]),centerColor:d.vec3([1,1,1]),edgeBias:0,centerBias:1,power:1}),this.edgeColor=t.edgeColor,this.centerColor=t.centerColor,this.edgeBias=t.edgeBias,this.centerBias=t.centerBias,this.power=t.power}set edgeColor(e){this._state.edgeColor.set(e||[0,0,0]),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set centerColor(e){this._state.centerColor.set(e||[1,1,1]),this.glRedraw()}get centerColor(){return this._state.centerColor}set edgeBias(e){this._state.edgeBias=e||0,this.glRedraw()}get edgeBias(){return this._state.edgeBias}set centerBias(e){this._state.centerBias=null!=e?e:1,this.glRedraw()}get centerBias(){return this._state.centerBias}set power(e){this._state.power=null!=e?e:1,this.glRedraw()}get power(){return this._state.power}destroy(){super.destroy(),this._state.destroy()}}const oo=m.memory,no=d.AABB3();class ao extends jt{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new _t({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._aabb=null,this._obb=d.OBB3();const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=Zt.getPositionsBounds(t.positions),o=Zt.compressPositions(t.positions,e.min,e.max);r=o.quantized,i.positionsDecodeMatrix=o.decodeMatrix,i.positionsBuf=new qe(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),oo.positions+=i.positionsBuf.numItems,d.positions3ToAABB3(t.positions,this._aabb),d.positions3ToAABB3(r,no,i.positionsDecodeMatrix),d.AABB3ToOBB3(no,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);i.colorsBuf=new qe(s,s.ARRAY_BUFFER,e,e.length,4,s.STATIC_DRAW),oo.colors+=i.colorsBuf.numItems}if(t.uv){const e=Zt.getUVBounds(t.uv),r=Zt.compressUVs(t.uv,e.min,e.max),o=r.quantized;i.uvDecodeMatrix=r.decodeMatrix,i.uvBuf=new qe(s,s.ARRAY_BUFFER,o,o.length,2,s.STATIC_DRAW),oo.uvs+=i.uvBuf.numItems}if(t.normals){const e=Zt.compressNormals(t.normals);let r=i.compressGeometry;i.normalsBuf=new qe(s,s.ARRAY_BUFFER,e,e.length,3,s.STATIC_DRAW,r),oo.normals+=i.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);i.indicesBuf=new qe(s,s.ELEMENT_ARRAY_BUFFER,e,e.length,1,s.STATIC_DRAW),oo.indices+=i.indicesBuf.numItems;const o=Gt(r,e,i.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new qe(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),oo.meshes++}else this.error("Config expected: indices");else this.error("Config expected: positions")}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positionsBuf&&t.push("p"),e.colorsBuf&&t.push("c"),(e.normalsBuf||e.autoVertexNormals)&&t.push("n"),e.uvBuf&&t.push("u"),t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf}get primitive(){return this._state.primitiveName}get aabb(){return this._aabb}get obb(){return this._obb}get numTriangles(){return this._numTriangles}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),e.destroy(),oo.meshes--}}var lo={};function Ao(e,t={}){return new Promise((function(i,s){t.src||(console.error("load3DSGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,y.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("load3DSGeometry: no data loaded"),r.processes--,s());var o=lo.parse.from3DS(e).edit.objects[0].mesh,n=o.vertices,a=o.uvt,l=o.indices;r.processes--,i(y.apply(t,{primitive:"triangles",positions:n,normals:null,uv:a,indices:l}))}),(function(e){console.error("load3DSGeometry: "+e),r.processes--,s()}))}))}function ho(e,t={}){return new Promise((function(i,s){t.src||(console.error("loadOBJGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,y.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("loadOBJGeometry: no data loaded"),r.processes--,s());for(var o=lo.parse.fromOBJ(e),n=lo.edit.unwrap(o.i_verts,o.c_verts,3),a=lo.edit.unwrap(o.i_norms,o.c_norms,3),l=lo.edit.unwrap(o.i_uvt,o.c_uvt,2),A=new Int32Array(o.i_verts.length),h=0;h0?a:null,autoNormals:0===a.length,uv:l,indices:A}))}),(function(e){console.error("loadOBJGeometry: "+e),r.processes--,s()}))}))}function co(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return y.apply(e,{primitive:"lines",positions:[l,A,h,l,A,d,l,u,h,l,u,d,c,A,h,c,A,d,c,u,h,c,u,d],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function uo(e={}){return co({id:e.id,center:[(e.aabb[0]+e.aabb[3])/2,(e.aabb[1]+e.aabb[4])/2,(e.aabb[2]+e.aabb[5])/2],xSize:Math.abs(e.aabb[3]-e.aabb[0])/2,ySize:Math.abs(e.aabb[4]-e.aabb[1])/2,zSize:Math.abs(e.aabb[5]-e.aabb[2])/2})}function po(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let i=e.divisions||1;i<0&&(console.error("negative divisions not allowed - will invert"),i*=-1),i<1&&(i=1),t=t||10,i=i||10;const s=t/i,r=t/2,o=[],n=[];let a=0;for(let e=0,t=-r;e<=i;e++,t+=s)o.push(-r),o.push(0),o.push(t),o.push(r),o.push(0),o.push(t),o.push(t),o.push(0),o.push(-r),o.push(t),o.push(0),o.push(r),n.push(a++),n.push(a++),n.push(a++),n.push(a++);return y.apply(e,{primitive:"lines",positions:o,indices:n})}function fo(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);let s=e.xSegments||1;s<0&&(console.error("negative xSegments not allowed - will invert"),s*=-1),s<1&&(s=1);let r=e.xSegments||1;r<0&&(console.error("negative zSegments not allowed - will invert"),r*=-1),r<1&&(r=1);const o=e.center,n=o?o[0]:0,a=o?o[1]:0,l=o?o[2]:0,A=t/2,h=i/2,c=Math.floor(s)||1,u=Math.floor(r)||1,d=c+1,p=u+1,f=t/c,g=i/u,m=new Float32Array(d*p*3),_=new Float32Array(d*p*3),v=new Float32Array(d*p*2);let b,x,B,w,P,C,M,E=0,F=0;for(b=0;b65535?Uint32Array:Uint16Array)(c*u*6);for(b=0;b360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const A=n?n[2]:0,h=[],c=[],u=[],p=[];let f,g,m,_,v,b,x,B,w,P,C,M;for(B=0;B<=r;B++)for(x=0;x<=s;x++)f=x/s*o,g=.785398+B/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),m=(t+i*Math.cos(g))*Math.cos(f),_=(t+i*Math.cos(g))*Math.sin(f),v=i*Math.sin(g),h.push(m+a),h.push(_+l),h.push(v+A),u.push(1-x/s),u.push(B/r),b=d.normalizeVec3(d.subVec3([m,_,v],[a,l,A],[]),[]),c.push(b[0]),c.push(b[1]),c.push(b[2]);for(B=1;B<=r;B++)for(x=1;x<=s;x++)w=(s+1)*B+x-1,P=(s+1)*(B-1)+x-1,C=(s+1)*(B-1)+x,M=(s+1)*B+x,p.push(w),p.push(P),p.push(C),p.push(C),p.push(M),p.push(w);return y.apply(e,{positions:h,normals:c,uv:u,indices:p})}function mo(e={}){if(e.points.length%3!=0)throw"Size of points array for given polyline should be divisible by 3";let t=e.points.length/3;if(t<2)throw"There should be at least 2 points to create a polyline";let i=[];for(let e=0;e[...e])).flat();return mo({id:e.id,points:t})}function vo(e={}){if(3!==e.startPoint.length)throw"Start point should contain 3 elements in array: x, y and z";if(3!==e.endPoint.length)throw"End point should contain 3 elements in array: x, y and z";let t=[],i=[],s=e.startPoint[0],r=e.startPoint[1],o=e.startPoint[2],n=e.endPoint[0],a=e.endPoint[1],l=e.endPoint[2],A=Math.sqrt((n-s)**2+(a-r)**2+(l-o)**2),h=[(n-s)/A,(a-r)/A,(l-o)/A];if(e.pattern){let c=e.pattern.length,u=!1,d=0,p=0,f=0,g=[s,r,o],m=e.pattern[p];for(i.push(g[0],g[1],g[2]);m<=A-d;){let s=[h[0]*m,h[1]*m,h[2]*m],r=[g[0]+s[0],g[1]+s[1],g[2]+s[2]];i.push(r[0],r[1],r[2]),u||(t.push(f),t.push(f+1)),u=!u,f+=1,g=r,p+=1,p>=c&&(p=0),d+=m,m=e.pattern[p]}e.extendToEnd&&(i.push(n,a,l),t.push(t.length-2),t.push(t.length-1))}else t.push(0),t.push(1),i.push(s,r,o,n,a,l);return y.apply(e,{primitive:"lines",positions:i,indices:t})}lo.load=function(e,t){var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=function(e){t(e.target.response)},i.send()},lo.save=function(e,t){var i="data:application/octet-stream;base64,"+btoa(lo.parse._buffToStr(e));window.location.href=i},lo.clone=function(e){return JSON.parse(JSON.stringify(e))},lo.bin={},lo.bin.f=new Float32Array(1),lo.bin.fb=new Uint8Array(lo.bin.f.buffer),lo.bin.rf=function(e,t){for(var i=lo.bin.f,s=lo.bin.fb,r=0;r<4;r++)s[r]=e[t+r];return i[0]},lo.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},lo.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},lo.bin.rASCII0=function(e,t){for(var i="";0!=e[t];)i+=String.fromCharCode(e[t++]);return i},lo.bin.wf=function(e,t,i){new Float32Array(e.buffer,t,1)[0]=i},lo.bin.wsl=function(e,t,i){e[t]=i,e[t+1]=i>>8},lo.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},lo.parse={},lo.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",s=0;sr&&(r=l),Ao&&(o=A),hn&&(n=h)}return{min:{x:t,y:i,z:s},max:{x:r,y:o,z:n}}};class bo extends R{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=d.vec3(t.pos||[0,0,0]),this._up=d.vec3(t.up||[0,1,0]),this._normal=d.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=d.vec3(),this._rtcPos=d.vec3(),this._imageSize=d.vec2(),this._texture=new so(this,{flipY:!0}),this._image=new Image,"jpg"!==this._type&&"png"!==this._type&&(this.error('Unsupported type - defaulting to "jpg"'),this._type="jpg"),this._node=new Vr(this,{matrix:d.inverseMat4(d.lookAtMat4v(this._pos,d.subVec3(this._pos,this._normal,d.mat4()),this._up,d.mat4())),children:[this._bitmapMesh=new wr(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new ei(this,fo({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new oi(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0})})]}),t.image?this.image=t.image:t.src?this.src=t.src:t.imageData&&(this.imageData=t.imageData),this.scene._bitmapCreated(this)}set visible(e){this._bitmapMesh.visible=e}get visible(){return this._bitmapMesh.visible}set image(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}get image(){return this._image}set src(e){if(e){this._image.onload=()=>{this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale()},this._image.src=e;switch(e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}}get src(){return this._image.src}set imageData(e){this._image.onload=()=>{this._texture.image=image,this._imageSize[0]=image.width,this._imageSize[1]=image.height,this._updateBitmapMeshScale()},this._image.src=e}get imageData(){const e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")}set type(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}get type(){return this._type}get pos(){return this._pos}get normal(){return this._normal}get up(){return this._up}set height(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}get height(){return this._height}set collidable(e){this._bitmapMesh.collidable=!1!==e}get collidable(){return this._bitmapMesh.collidable}set clippable(e){this._bitmapMesh.clippable=!1!==e}get clippable(){return this._bitmapMesh.clippable}set pickable(e){this._bitmapMesh.pickable=!1!==e}get pickable(){return this._bitmapMesh.pickable}set opacity(e){this._bitmapMesh.opacity=e}get opacity(){return this._bitmapMesh.opacity}destroy(){super.destroy(),this.scene._bitmapDestroyed(this)}_updateBitmapMeshScale(){const e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height/e,1,this._height]}}const yo=(e,t)=>{const i=[];let s=[];function r(e,i){let s,r;for(let o=0;o<3;o++)if(s=t[3*e+o],r=t[3*i+o],s!==r)return r-s;return 0}let o=e.slice().sort(r),n=null;for(let e=0,t=o.length;eo&&r>n?o>n?(a=r,l=o,A=n):(a=r,l=n,A=o):o>r&&o>n?r>n?(a=o,l=r,A=n):(a=o,l=n,A=r):n>r&&n>o&&(r>o?(a=n,l=r,A=o):(a=n,l=o,A=r)),s[t+0]=[a,l],s[t+1]=[l,A],a>A){const e=A;A=a,a=e}s[t+2]=[A,a]}function a(e,t){let i,s;for(let r=0;r<2;r++)if(i=e[r],s=t[r],s!==i)return s-i;return 0}s=s.slice(0,e.length),s.sort(a);let l=0;for(let e=0;e0&&2!==l)},xo=d.vec3(),Bo=d.vec3(),wo=d.vec3();class Po{constructor(){this.vertices=[],this.indices=[],this.reset()}reset(){this.lenVertices=0,this.lenIndices=0,this.primitive=null}setPrimitive(e){this.primitive=e}addVertex(e){this.vertices[this.lenVertices++]=e[0],this.vertices[this.lenVertices++]=e[1],this.vertices[this.lenVertices++]=e[2]}addIndex(e){this.indices[this.lenIndices++]=e}get volume(){const e=this.vertices,t=this.indices;if("solid"!==this.primitive&&"surface"!==this.primitive&&"triangles"!==this.primitive)return-1;if("solid"!==this.primitive&&!yo(t,e))return-1;let i=0;for(let s=0;s{Co.addVertex(e)})),this.getEachIndex((e=>{Co.addIndex(e)})),this._volume=Co.volume;break;default:this._volume=0}return this._volume}get surfaceArea(){if(null!==this._surfaceArea)return this._surfaceArea;switch(this.layer.primitive){case"solid":case"surface":case"triangles":Ro.reset(),this.getEachVertex((e=>{Ro.addVertex(e)})),this.getEachIndex((e=>{Ro.addIndex(e)})),this._surfaceArea=Ro.surfaceArea;break;default:this._surfaceArea=0}return this._surfaceArea}set aabb(e){if(this._aabbLocal=e,this.origin){this._aabbLocal=e.slice(0);const t=this.origin;this._aabbLocal[0]+=t[0],this._aabbLocal[1]+=t[1],this._aabbLocal[2]+=t[2],this._aabbLocal[3]+=t[0],this._aabbLocal[4]+=t[1],this._aabbLocal[5]+=t[2]}}get aabb(){return this._aabbWorldDirty&&(d.AABB3ToOBB3(this._aabbLocal,Lo),this.transform?(d.transformOBB3(this.transform.worldMatrix,Lo,Uo),d.transformOBB3(this.model.worldMatrix,Uo,ko),d.OBB3ToAABB3(ko,this._aabbWorld)):(d.transformOBB3(this.model.worldMatrix,Lo,Uo),d.OBB3ToAABB3(Uo,this._aabbWorld)),this._aabbWorldDirty=!1),this._aabbWorld}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const No=new class{constructor(){this._uint8Arrays={},this._float32Arrays={}}_clear(){this._uint8Arrays={},this._float32Arrays={}}getUInt8Array(e){let t=this._uint8Arrays[e];return t||(t=new Uint8Array(e),this._uint8Arrays[e]=t),t}getFloat32Array(e){let t=this._float32Arrays[e];return t||(t=new Float32Array(e),this._float32Arrays[e]=t),t}};let Qo=0;const Vo={NOT_RENDERED:0,COLOR_OPAQUE:1,COLOR_TRANSPARENT:2,SILHOUETTE_HIGHLIGHTED:3,SILHOUETTE_SELECTED:4,SILHOUETTE_XRAYED:5,EDGES_COLOR_OPAQUE:6,EDGES_COLOR_TRANSPARENT:7,EDGES_HIGHLIGHTED:8,EDGES_SELECTED:9,EDGES_XRAYED:10,PICK:11},Ho=new Float32Array([1,1,1,1]),jo=new Float32Array([0,0,0,1]),Go=d.vec4(),zo=d.vec3(),Wo=d.vec3(),Ko=d.mat4();class Xo{constructor(e,t=!1,{instancing:i=!1,edges:s=!1,useAlphaCutoff:r=!1}={}){this._scene=e,this._withSAO=t,this._instancing=i,this._edges=s,this._useAlphaCutoff=r,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}_getHash(){return this._scene._sectionPlanesState.getHash()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){return[""]}_buildFragmentShader(){return[""]}_addMatricesUniformBlockLines(e,t=!1){return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}_addRemapClipPosLines(e,t=1){return e.push("uniform vec2 drawingBufferSize;"),e.push("uniform vec2 pickClipPos;"),e.push("vec4 remapClipPos(vec4 clipPos) {"),e.push(" clipPos.xy /= clipPos.w;"),1===t?e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"):e.push(` clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(${t}));`),e.push(" clipPos.xy *= clipPos.w;"),e.push(" return clipPos;"),e.push("}"),e}getValid(){return this._hash===this._getHash()}setSectionPlanesStateUniforms(e){const t=this._scene,{gl:i}=t.canvas,{model:s,layerIndex:r}=e,o=t._sectionPlanesState.getNumAllocatedSectionPlanes(),n=t._sectionPlanesState.sectionPlanes.length;if(o>0){const a=t._sectionPlanesState.sectionPlanes,l=r*n,A=s.renderFlags;t.crossSections&&(i.uniform4fv(this._uSliceColor,t.crossSections.sliceColor),i.uniform1f(this._uSliceThickness,t.crossSections.sliceThickness));for(let t=0;t0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0&&p.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,p.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),p.lightMaps.length>0&&p.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,p.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const i=a.drawingBufferWidth,s=a.drawingBufferHeight;Go[0]=i,Go[1]=s,Go[2]=t.blendCutoff,Go[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,Go),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(this._useAlphaCutoff&&a.uniform1f(this._alphaCutoffLocation,h.alphaCutoff),s){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(i===Vo[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const i=n.xrayMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===Vo[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const i=n.highlightMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===Vo[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const i=n.selectedMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else a.uniform4fv(this._uColor,this._edges?jo:Ho)}this._draw({state:l,frameCtx:e,incrementDrawState:r}),a.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,m.memory.programs--}}class Jo extends Xo{constructor(e,t,{edges:i=!1,useAlphaCutoff:s=!1}={}){super(e,t,{instancing:!1,edges:i,useAlphaCutoff:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;if(this._edges)t.drawElements(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0);else{const e=s.pickElementsCount||i.indicesBuf.numItems,o=s.pickElementsOffset?s.pickElementsOffset*i.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,i.indicesBuf.itemType,o),r&&s.drawElements++}}}class Yo extends Jo{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r;const o=[];o.push("#version 300 es"),o.push("// Triangles batching draw vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;")),o.push("out vec4 vColor;"),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching draw fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class Zo extends Jo{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._lightsState,i=e._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching flat-shading draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),s){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e sliceThickness) { "),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" newColor = sliceColor;"),r.push(" }"),r.push("}")}r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;"),r.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),r.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),r.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,i=t.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching silhouette fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r){for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" newColor = sliceColor;"),o.push(" }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = newColor;"),o.push("}"),o}}class $o extends Jo{constructor(e){super(e,!1,{instancing:!1,edges:!0})}}class en extends $o{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class tn extends $o{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class sn extends Jo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class rn extends Jo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class on extends Jo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec3 worldNormal = octDecode(normal.xy); "),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class nn extends Jo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching occlusion vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class an extends Jo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching depth fragment shader"),s.push("precision highp float;"),s.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),s.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),s.push("}"),s}}class ln extends Jo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class An extends Jo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry shadow vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" int colorFlag = int(flags) & 0xF;"),i.push(" bool visible = (colorFlag > 0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}}class hn extends Jo{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Triangles batching quality draw vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),o.push("vFragDepth = 1.0 + clipPos.w;")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Triangles batching quality draw fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),n.push("uniform sampler2D uAOMap;"),n.push("in vec4 vViewPosition;"),n.push("in vec3 vViewNormal;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("in vec2 vMetallicRoughness;"),s.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick flat normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick flat normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class un extends Jo{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching color texture vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=this._useAlphaCutoff,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching color texture fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const vn=d.vec3(),bn=d.vec3(),yn=d.vec3(),xn=d.vec3(),Bn=d.mat4();class wn extends Xo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=vn;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=bn;if(l){const e=yn;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=J(p,t,Bn),m=xn,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElements(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Pn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._colorTextureRendererAlphaCutoff&&!this._colorTextureRendererAlphaCutoff.getValid()&&(this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererAlphaCutoff=null),this._colorTextureRendererWithSAOAlphaCutoff&&!this._colorTextureRendererWithSAOAlphaCutoff.getValid()&&(this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new qo(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new sn(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new rn(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new _n(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new wn(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Yo(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Yo(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Zo(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Zo(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new un(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new un(this._scene,!0)),this._colorTextureRendererWithSAO}get colorTextureRendererAlphaCutoff(){return this._colorTextureRendererAlphaCutoff||(this._colorTextureRendererAlphaCutoff=new un(this._scene,!1,{useAlphaCutoff:!0})),this._colorTextureRendererAlphaCutoff}get colorTextureRendererWithSAOAlphaCutoff(){return this._colorTextureRendererWithSAOAlphaCutoff||(this._colorTextureRendererWithSAOAlphaCutoff=new un(this._scene,!0,{useAlphaCutoff:!0})),this._colorTextureRendererWithSAOAlphaCutoff}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new hn(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new hn(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new qo(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new an(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new ln(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new en(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new tn(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new sn(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new on(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new cn(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new rn(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new nn(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new An(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new wn(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new _n(this._scene)),this._snapInitRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererAlphaCutoff&&this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff&&this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Cn={};let Mn=65536,En=5e6;class Fn{constructor(){}set doublePrecisionEnabled(e){d.setDoublePrecisionEnabled(e)}get doublePrecisionEnabled(){return d.getDoublePrecisionEnabled()}set maxDataTextureHeight(e){(e=1024*Math.ceil(e/1024))>4096?e=4096:e<1024&&(e=1024),Mn=e}get maxDataTextureHeight(){return Mn}set maxGeometryBatchSize(e){e<1e5?e=1e5:e>5e6&&(e=5e6),En=e}get maxGeometryBatchSize(){return En}}const In=new Fn;class Dn{constructor(e=In.maxGeometryBatchSize){this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const Sn=d.mat4(),Tn=d.mat4();function Rn(e,t,i){const s=e.length,r=new Uint16Array(s),o=t[0],n=t[1],a=t[2],l=t[3]-o,A=t[4]-n,h=t[5]-a,c=65525,u=c/l,p=c/A,f=c/h,g=e=>e>=0?e:0;for(let t=0;t=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 kn(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}const On=d.mat4(),Nn=d.mat4(),Qn=d.vec4([0,0,0,1]),Vn=d.vec3(),Hn=d.vec3(),jn=d.vec3(),Gn=d.vec3(),zn=d.vec3(),Wn=d.vec3(),Kn=d.vec3();class Xn{constructor(e){this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Cn[t];return i||(i=new Pn(e),Cn[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Cn[t],i._destroy()}))),i}(e.model.scene),this._buffer=new Dn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new _t({origin:d.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:e.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=d.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=d.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=d.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.solid=!!e.solid,this.primitive=e.primitive}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)for(let e=0,t=o.length;e0){const e=On;m?d.inverseMat4(d.transposeMat4(m,Nn),e):d.identityMat4(e,e),function(e,t,i,s,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,A,h,c,u=new Float32Array([0,0,0,0]),p=new Float32Array([0,0,0,0]);for(c=0;ch&&(l=n,h=A),n=Un(p,"floor","ceil"),a=kn(n),A=o(p,a),A>h&&(l=n,h=A),n=Un(p,"ceil","ceil"),a=kn(n),A=o(p,a),A>h&&(l=n,h=A),s[r+c+0]=l[0],s[r+c+1]=l[1],s[r+c+2]=0}(e,r,r.length,b.normals,b.normals.length)}if(l)for(let e=0,t=l.length;e0)for(let e=0,t=n.length;e0)for(let e=0,t=a.length;e0){const s=this._state.positionsDecodeMatrix?new Uint16Array(i.positions):Rn(i.positions,this._modelAABB,this._state.positionsDecodeMatrix=d.mat4());if(e.positionsBuf=new qe(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this.model.scene.readableGeometryEnabled)for(let e=0,t=this._portions.length;e0){const s=new Int8Array(i.normals);let r=!0;e.normalsBuf=new qe(t,t.ARRAY_BUFFER,s,i.normals.length,3,t.STATIC_DRAW,r)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new qe(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.uv.length>0)if(e.uvDecodeMatrix){let s=!1;e.uvBuf=new qe(t,t.ARRAY_BUFFER,i.uv,i.uv.length,2,t.STATIC_DRAW,s)}else{const s=Zt.getUVBounds(i.uv),r=Zt.compressUVs(i.uv,s.min,s.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=d.mat3(r.decodeMatrix),e.uvBuf=new qe(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(i.metallicRoughness.length>0){const s=new Uint8Array(i.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new qe(t,t.ARRAY_BUFFER,s,i.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s),o=!1;e.flagsBuf=new qe(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new qe(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new qe(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new qe(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){const s=new Uint32Array(i.edgeIndices);e.edgeIndicesBuf=new qe(t,t.ELEMENT_ARRAY_BUFFER,s,i.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,i){t&ee&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ne&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&oe&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ae&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&se&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&le&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ie&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&te&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ae?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&le?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&se?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=e,s=this._portions[i],r=4*s.vertsBaseIndex,o=4*s.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],A=t[2],h=t[3];for(let e=0;e_)&&(_=e,s.set(v),r&&d.triangleNormal(p,f,g,r),m=!0)}}return m&&r&&(d.transformVec3(this.model.worldNormalMatrix,r,r),d.normalizeVec3(r)),m}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}class Jn extends Xo{constructor(e,t,{edges:i=!1,useAlphaCutoff:s=!1}={}){super(e,t,{instancing:!0,edges:i,useAlphaCutoff:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;this._edges?t.drawElementsInstanced(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0,i.numInstances):(t.drawElementsInstanced(t.TRIANGLES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),r&&s.drawElements++)}}class Yn extends Jn{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r,o,n;const a=[];for(a.push("#version 300 es"),a.push("// Instancing geometry drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec2 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;"),r=0,o=i.lights.length;r= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),s&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),a.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),r=0,o=i.lights.length;r0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class Zn extends Jn{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry flat-shading drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState;let s,r;const o=t.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry flat-shading drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),o){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}for(n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),s=0,r=i.lights.length;s0,i=[];return i.push("#version 300 es"),i.push("// Instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing fill fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = newColor;"),s.push("}"),s}}class $n extends Jn{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class ea extends $n{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class ta extends $n{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesColorRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class ia extends Jn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class sa extends Jn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class ra extends Jn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec2 normal;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("in vec4 modelNormalMatrixCol0;"),i.push("in vec4 modelNormalMatrixCol1;"),i.push("in vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class oa extends Jn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class na extends Jn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Instancing geometry depth drawing fragment shader"),o.push("precision highp float;"),o.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),o.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),o.push("}"),o}}class aa extends Jn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class la extends Jn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const Aa={3e3:"linearToLinear",3001:"sRGBToLinear"};class ha extends Jn{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Instancing geometry quality drawing vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),o.push("in vec4 modelMatrixCol0;"),o.push("in vec4 modelMatrixCol1;"),o.push("in vec4 modelMatrixCol2;"),o.push("in vec4 modelNormalMatrixCol0;"),o.push("in vec4 modelNormalMatrixCol1;"),o.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),o.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),o.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Instancing geometry quality drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),n.push("#define PI 3.14159265359"),n.push("#define RECIPROCAL_PI 0.31830988618"),n.push("#define RECIPROCAL_PI2 0.15915494"),n.push("#define EPSILON 1e-6"),n.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),n.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),n.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),n.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),n.push(" return normalize(surf_norm );"),n.push(" }"),n.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),n.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),n.push(" vec2 st0 = dFdx( uv.st );"),n.push(" vec2 st1 = dFdy( uv.st );"),n.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),n.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),n.push(" vec3 N = normalize( surf_norm );"),n.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),n.push(" mat3 tsn = mat3( S, T, N );"),n.push(" return normalize( tsn * mapN );"),n.push("}"),n.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),n.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),n.push("}"),n.push("struct IncidentLight {"),n.push(" vec3 color;"),n.push(" vec3 direction;"),n.push("};"),n.push("struct ReflectedLight {"),n.push(" vec3 diffuse;"),n.push(" vec3 specular;"),n.push("};"),n.push("struct Geometry {"),n.push(" vec3 position;"),n.push(" vec3 viewNormal;"),n.push(" vec3 worldNormal;"),n.push(" vec3 viewEyeDir;"),n.push("};"),n.push("struct Material {"),n.push(" vec3 diffuseColor;"),n.push(" float specularRoughness;"),n.push(" vec3 specularColor;"),n.push(" float shine;"),n.push("};"),n.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),n.push(" float r = ggxRoughness + 0.0001;"),n.push(" return (2.0 / (r * r) - 2.0);"),n.push("}"),n.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),n.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),n.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),n.push("}"),s.reflectionMaps.length>0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = "+Aa[s.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = "+Aa[s.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&i.push("out float vFlags;"),i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&i.push("vFlags = flags;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class ua extends Jn{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=this._useAlphaCutoff,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const va=d.vec3(),ba=d.vec3(),ya=d.vec3(),xa=d.vec3(),Ba=d.mat4();class wa extends Xo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=va;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=ba;if(l){const e=d.transformPoint3(h,l,ya);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=J(p,t,Ba),m=xa,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0,a.numInstances),a.edgeIndicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Pa{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._colorTextureRendererAlphaCutoff&&!this._colorTextureRendererAlphaCutoff.getValid()&&(this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererAlphaCutoff=null),this._colorTextureRendererWithSAOAlphaCutoff&&!this._colorTextureRendererWithSAOAlphaCutoff.getValid()&&(this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new qn(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new ia(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new sa(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new _a(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new wa(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Yn(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Yn(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Zn(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Zn(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new ua(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new ua(this._scene,!0)),this._colorTextureRendererWithSAO}get colorTextureRendererAlphaCutoff(){return this._colorTextureRendererAlphaCutoff||(this._colorTextureRendererAlphaCutoff=new ua(this._scene,!1,{useAlphaCutoff:!0})),this._colorTextureRendererAlphaCutoff}get colorTextureRendererWithSAOAlphaCutoff(){return this._colorTextureRendererWithSAOAlphaCutoff||(this._colorTextureRendererWithSAOAlphaCutoff=new ua(this._scene,!0,{useAlphaCutoff:!0})),this._colorTextureRendererWithSAOAlphaCutoff}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new ha(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new ha(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new qn(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new na(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new aa(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new ea(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new ta(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new ia(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new ra(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new ca(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new sa(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new oa(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new la(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new wa(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new _a(this._scene)),this._snapInitRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererAlphaCutoff&&this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff&&this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Ca={};const Ma=new Uint8Array(4),Ea=new Float32Array(1),Fa=d.vec4([0,0,0,1]),Ia=new Float32Array(3),Da=d.vec3(),Sa=d.vec3(),Ta=d.vec3(),Ra=d.vec3(),La=d.vec3(),Ua=d.vec3(),ka=d.vec3(),Oa=new Float32Array(4);class Na{constructor(e){this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Ca[t];return i||(i=new Pa(e),Ca[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Ca[t],i._destroy()}))),i}(e.model.scene),this._aabb=d.collapseAABB3(),this._state=new _t({numInstances:0,obb:d.OBB3(),origin:d.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrix=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.solid=!!e.solid,this.numIndices=e.geometry.numIndices,this.primitive=e.geometry.primitive}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;e.colorsBuf=new qe(s,s.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,s.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let i=!1;e.metallicRoughnessBuf=new qe(s,s.ARRAY_BUFFER,t,this._metallicRoughness.length,2,s.STATIC_DRAW,i)}if(o>0){let t=!1;e.flagsBuf=new qe(s,s.ARRAY_BUFFER,new Float32Array(o),o,1,s.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new qe(s,s.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,s.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const i=!1;e.positionsBuf=new qe(s,s.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,s.STATIC_DRAW,i),e.positionsDecodeMatrix=d.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const i=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new qe(s,s.ARRAY_BUFFER,i,i.length,4,s.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const i=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new qe(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new qe(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,s.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new qe(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,s.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelMatrixCol1Buf=new qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelMatrixCol2Buf=new qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new qe(s,s.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,s.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&i&&i.colorTexture&&i.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!i&&!!i.colorTexture,this.model.scene.readableGeometryEnabled||(this._state.geometry=null),this._finalized=!0}initFlags(e,t,i){t&ee&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ne&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&oe&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ae&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&se&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&le&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ie&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&te&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ae?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&le?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&se?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";Ma[0]=t[0],Ma[1]=t[1],Ma[2]=t[2],Ma[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(Ma,4*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&ee),r=!!(t&oe),o=!!(t&ne),n=!!(t&ae),a=!!(t&le),l=!!(t&ie),A=!!(t&te);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Vo.NOT_RENDERED:i?Vo.COLOR_TRANSPARENT:Vo.COLOR_OPAQUE,c=!s||A?Vo.NOT_RENDERED:n?Vo.SILHOUETTE_SELECTED:o?Vo.SILHOUETTE_HIGHLIGHTED:r?Vo.SILHOUETTE_XRAYED:Vo.NOT_RENDERED;let u=0;u=!s||A?Vo.NOT_RENDERED:n?Vo.EDGES_SELECTED:o?Vo.EDGES_HIGHLIGHTED:r?Vo.EDGES_XRAYED:a?i?Vo.EDGES_COLOR_TRANSPARENT:Vo.EDGES_COLOR_OPAQUE:Vo.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Vo.PICK:Vo.NOT_RENDERED)<<12,d|=(t&se?1:0)<<16,Ea[0]=d,this._state.flagsBuf&&this._state.flagsBuf.setData(Ea,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Ia[0]=t[0],Ia[1]=t[1],Ia[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(Ia,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.readableGeometryEnabled)return!1;const i=this._state,s=i.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=s.positionsCompressed,n=i.origin,a=n[0],l=n[1],A=n[2],h=Fa,c=r.matrix,u=this.model.matrix,p=i.positionsDecodeMatrix;for(let e=0,i=o.length;ev)&&(v=e,s.set(b),r&&d.triangleNormal(f,g,m,r),_=!0)}}return _&&r&&(d.transformVec3(a.normalMatrix,r,r),d.transformVec3(this.model.worldNormalMatrix,r,r),d.normalizeVec3(r)),_}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}class Qa extends Xo{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawElements(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0),r&&s.drawElements++}}class Va extends Qa{drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Ha extends Qa{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const ja=d.vec3(),Ga=d.vec3(),za=d.vec3(),Wa=d.vec3(),Ka=d.mat4();class Xa extends Xo{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=ja;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Ga;if(l){const e=za;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=J(p,t,Ka),m=Wa,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ja=d.vec3(),Ya=d.vec3(),Za=d.vec3(),qa=d.vec3(),$a=d.mat4();class el extends Xo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Ja;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Ya;if(l){const e=Za;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=J(p,t,$a),m=qa,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class tl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Va(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Ha(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Xa(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new el(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const il={};class sl{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}class rl{constructor(e){this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=il[t];return i||(i=new tl(e),il[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete il[t],i._destroy()}))),i}(e.model.scene),this.model=e.model,this._buffer=new sl(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new _t({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:d.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=d.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=d.vec3(e.origin)),this.primitive=e.primitive}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new qe(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=Rn(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new qe(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new qe(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.colors.length>0){const s=i.colors.length/4,r=new Float32Array(s);let o=!1;e.flagsBuf=new qe(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new qe(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new qe(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&ee&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ne&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&oe&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ae&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&se&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&le&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ie&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&te&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ae?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&le?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&se?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],A=t[3];for(let e=0;e0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 lightAmbient;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Lines instancing color fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),o.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):o.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class al extends ol{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const ll=d.vec3(),Al=d.vec3(),hl=d.vec3();d.vec3();const cl=d.mat4();class ul extends Xo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=ll;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Al;if(l){const e=d.transformPoint3(h,l,hl);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=J(p,t,cl),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),a.indicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const dl=d.vec3(),pl=d.vec3(),fl=d.vec3();d.vec3();const gl=d.mat4();class ml extends Xo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=dl;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=pl;if(l){const e=d.transformPoint3(h,l,fl);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=J(p,t,gl),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class _l{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._snapInitRenderer||(this._snapInitRenderer=new ul(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new ml(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new nl(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new al(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new ul(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new ml(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const vl={};const bl=new Uint8Array(4),yl=new Float32Array(1),xl=new Float32Array(3),Bl=new Float32Array(4);class wl{constructor(e){this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=vl[t];return i||(i=new _l(e),vl[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete vl[t],i._destroy()}))),i}(e.model.scene),this._aabb=d.collapseAABB3(),this._state=new _t({obb:d.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,e.origin&&(this._state.origin=d.vec3(e.origin)),this._finalized=!1,this.primitive=e.primitive}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;this._state.colorsBuf=new qe(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(r>0){let t=!1;this._state.flagsBuf=new qe(e,e.ARRAY_BUFFER,new Float32Array(r),r,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new qe(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.colorsCompressed&&i.colorsCompressed.length>0){const s=new Uint8Array(i.colorsCompressed),r=!1;t.colorsBuf=new qe(e,e.ARRAY_BUFFER,s,s.length,4,e.STATIC_DRAW,r)}if(i.positionsCompressed&&i.positionsCompressed.length>0){const s=!1;t.positionsBuf=new qe(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,s),t.positionsDecodeMatrix=d.mat4(i.positionsDecodeMatrix)}if(i.indices&&i.indices.length>0&&(t.indicesBuf=new qe(e,e.ELEMENT_ARRAY_BUFFER,new Uint32Array(i.indices),i.indices.length,1,e.STATIC_DRAW),t.numIndices=i.indices.length),this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this.model.scene.readableGeometryEnabled||(this._state.geometry=null),this._finalized=!0}initFlags(e,t,i){t&ee&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ne&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&oe&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ae&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&se&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&le&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ie&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&te&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ae?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&le?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&se?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";bl[0]=t[0],bl[1]=t[1],bl[2]=t[2],bl[3]=t[3],this._state.colorsBuf.setData(bl,4*e,4)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&ee),r=!!(t&oe),o=!!(t&ne),n=!!(t&ae),a=!!(t&le),l=!!(t&ie),A=!!(t&te);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Vo.NOT_RENDERED:i?Vo.COLOR_TRANSPARENT:Vo.COLOR_OPAQUE,c=!s||A?Vo.NOT_RENDERED:n?Vo.SILHOUETTE_SELECTED:o?Vo.SILHOUETTE_HIGHLIGHTED:r?Vo.SILHOUETTE_XRAYED:Vo.NOT_RENDERED;let u=0;u=!s||A?Vo.NOT_RENDERED:n?Vo.EDGES_SELECTED:o?Vo.EDGES_HIGHLIGHTED:r?Vo.EDGES_XRAYED:a?i?Vo.EDGES_COLOR_TRANSPARENT:Vo.EDGES_COLOR_OPAQUE:Vo.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Vo.PICK:Vo.NOT_RENDERED)<<12,d|=(t&se?255:0)<<16,yl[0]=d,this._state.flagsBuf.setData(yl,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(xl[0]=t[0],xl[1]=t[1],xl[2]=t[2],this._state.offsetsBuf.setData(xl,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;Bl[0]=t[0],Bl[1]=t[4],Bl[2]=t[8],Bl[3]=t[12],this._state.modelMatrixCol0Buf.setData(Bl,i),Bl[0]=t[1],Bl[1]=t[5],Bl[2]=t[9],Bl[3]=t[13],this._state.modelMatrixCol1Buf.setData(Bl,i),Bl[0]=t[2],Bl[1]=t[6],Bl[2]=t[10],Bl[3]=t[14],this._state.modelMatrixCol2Buf.setData(Bl,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Vo.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Vo.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Vo.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Vo.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Vo.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Vo.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Vo.PICK)}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class Pl extends Xo{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,i.positionsBuf.numItems),r&&s.drawArrays++}}class Cl extends Pl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial,s=[];return s.push("#version 300 es"),s.push("// Points batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Ml extends Pl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points batching silhouette vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = color;"),o.push("}"),o}}class El extends Pl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class Fl extends Pl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batched pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batched pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Il extends Pl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push(" gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}const Dl=d.vec3(),Sl=d.vec3(),Tl=d.vec3(),Rl=d.vec3(),Ll=d.mat4();class Ul extends Xo{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Dl;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Sl;if(l){const e=Tl;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=J(p,t,Ll),m=Rl,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const kl=d.vec3(),Ol=d.vec3(),Nl=d.vec3(),Ql=d.vec3(),Vl=d.mat4();class Hl extends Xo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=kl;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Ol;if(l){const e=Nl;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=J(p,t,Vl),m=Ql,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class jl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Cl(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Ml(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new El(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Fl(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Il(this._scene)),this._occlusionRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Ul(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Hl(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Gl={};class zl{constructor(e){this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Gl[t];return i||(i=new jl(e),Gl[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Gl[t],i._destroy()}))),i}(e.model.scene);const t=e.maxGeometryBatchSize||5e6,i=function(){const e=[];return{append:function(t,i=1,s=1){e.push({data:t,times:i,denormalizeScale:s})},compileBuffer:function(t){let i=0;e.forEach((e=>{i+=e.times*e.data.length}));const s=new t(i);let r=0;return e.forEach((e=>{const t=e.data,i=e.denormalizeScale,o=s.subarray(r);if(1===i)o.set(t,0);else for(let e=0;ee.length>0?new qe(t,t.ARRAY_BUFFER,e,e.length,i,s):null,r=this._preCompressedPositionsExpected?i.positions.compileBuffer(Uint16Array):Rn(i.positions.compileBuffer(Float32Array),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=s(r,3,t.STATIC_DRAW),e.flagsBuf=s(new Float32Array(this._buffer.vertsIndex),1,t.DYNAMIC_DRAW),e.colorsBuf=s(i.colors.compileBuffer(Uint8Array),4,t.STATIC_DRAW),e.pickColorsBuf=s(i.pickColors.compileBuffer(Uint8Array),4,t.STATIC_DRAW),e.offsetsBuf=this.model.scene.entityOffsetsEnabled?s(new Float32Array(3*this._buffer.vertsIndex),3,t.DYNAMIC_DRAW):null,this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&ee&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ne&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&oe&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ae&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&se&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ie&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&te&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ae?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&se?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Xl extends Wl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 silhouetteColor;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Jl extends Wl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick mesh fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class Yl extends Wl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Zl extends Wl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class ql extends Wl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points instancing depth vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return o.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class $l extends Wl{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("gl_PointSize = pointSize;"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const eA=d.vec3(),tA=d.vec3(),iA=d.vec3();d.vec3();const sA=d.mat4();class rA extends Xo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=eA;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=tA;if(l){const e=d.transformPoint3(h,l,iA);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=J(p,t,sA),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const oA=d.vec3(),nA=d.vec3(),aA=d.vec3();d.vec3();const lA=d.mat4();class AA extends Xo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=oA;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=nA;if(l){const e=d.transformPoint3(h,l,aA);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=J(p,t,lA),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class hA{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Kl(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Xl(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new ql(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Jl(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Yl(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Zl(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new $l(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new rA(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new AA(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const cA={};const uA=new Uint8Array(4),dA=new Float32Array(1),pA=new Float32Array(3),fA=new Float32Array(4);class gA{constructor(e){this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=cA[t];return i||(i=new hA(e),cA[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete cA[t],i._destroy()}))),i}(e.model.scene),this._aabb=d.collapseAABB3(),this._state=new _t({obb:d.OBB3(),numInstances:0,origin:e.origin?d.vec3(e.origin):null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,this.primitive=e.geometry.primitive}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let s=!1;i.flagsBuf=new qe(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,s)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;i.offsetsBuf=new qe(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(s.positionsCompressed&&s.positionsCompressed.length>0){const t=!1;i.positionsBuf=new qe(e,e.ARRAY_BUFFER,s.positionsCompressed,s.positionsCompressed.length,3,e.STATIC_DRAW,t),i.positionsDecodeMatrix=d.mat4(s.positionsDecodeMatrix)}if(s.colorsCompressed&&s.colorsCompressed.length>0){const t=new Uint8Array(s.colorsCompressed),r=!1;i.colorsBuf=new qe(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;i.modelMatrixCol0Buf=new qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),i.modelMatrixCol1Buf=new qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),i.modelMatrixCol2Buf=new qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;i.pickColorsBuf=new qe(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}i.geometry=null,this._finalized=!0}initFlags(e,t,i){t&ee&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ne&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&oe&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ae&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&se&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&le&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ie&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&te&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ae?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&le?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&se?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";uA[0]=t[0],uA[1]=t[1],uA[2]=t[2],this._state.colorsBuf.setData(uA,3*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&ee),r=!!(t&oe),o=!!(t&ne),n=!!(t&ae),a=!!(t&le),l=!!(t&ie),A=!!(t&te);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Vo.NOT_RENDERED:i?Vo.COLOR_TRANSPARENT:Vo.COLOR_OPAQUE,c=!s||A?Vo.NOT_RENDERED:n?Vo.SILHOUETTE_SELECTED:o?Vo.SILHOUETTE_HIGHLIGHTED:r?Vo.SILHOUETTE_XRAYED:Vo.NOT_RENDERED;let u=0;u=!s||A?Vo.NOT_RENDERED:n?Vo.EDGES_SELECTED:o?Vo.EDGES_HIGHLIGHTED:r?Vo.EDGES_XRAYED:a?i?Vo.EDGES_COLOR_TRANSPARENT:Vo.EDGES_COLOR_OPAQUE:Vo.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Vo.PICK:Vo.NOT_RENDERED)<<12,d|=(t&se?255:0)<<16,dA[0]=d,this._state.flagsBuf.setData(dA,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(pA[0]=t[0],pA[1]=t[1],pA[2]=t[2],this._state.offsetsBuf.setData(pA,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;fA[0]=t[0],fA[1]=t[4],fA[2]=t[8],fA[3]=t[12],this._state.modelMatrixCol0Buf.setData(fA,i),fA[0]=t[1],fA[1]=t[5],fA[2]=t[9],fA[3]=t[13],this._state.modelMatrixCol1Buf.setData(fA,i),fA[0]=t[2],fA[1]=t[6],fA[2]=t[10],fA[3]=t[14],this._state.modelMatrixCol2Buf.setData(fA,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Vo.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Vo.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Vo.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Vo.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Vo.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Vo.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Vo.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Vo.PICK)}drawPickNormals(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Vo.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Vo.PICK)}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}const mA=d.vec3(),_A=d.vec3(),vA=d.mat4();class bA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uPerObjectDecodeMatrix,this._uPerVertexPosition,this.uPerObjectColorAndFlags,this._uPerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=mA;if(g){const t=d.transformPoint3(c,A,_A);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=J(p,e,vA)}else f=p;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,8),n.drawArrays(n.LINES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,16),n.drawArrays(n.LINES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,32),n.drawArrays(n.LINES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// LinesDataTextureColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uPerObjectDecodeMatrix;"),i.push("uniform highp sampler2D uPerObjectMatrix;"),i.push("uniform lowp usampler2D uPerObjectColorAndFlags;"),i.push("uniform mediump usampler2D uPerVertexPosition;"),i.push("uniform highp usampler2D uPerLineIndices;"),i.push("uniform mediump usampler2D uPerLineObject;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push(" int lineIndex = gl_VertexID / 2;"),i.push(" int h_packed_object_id_index = (lineIndex >> 3) & 4095;"),i.push(" int v_packed_object_id_index = (lineIndex >> 3) >> 12;"),i.push(" int objectIndex = int(texelFetch(uPerLineObject, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push(" ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" } else {"),i.push(" ivec4 packedVertexBase = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push(" ivec4 packedLineIndexBaseOffset = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push(" int lineIndexBaseOffset = (packedLineIndexBaseOffset.r << 24) + (packedLineIndexBaseOffset.g << 16) + (packedLineIndexBaseOffset.b << 8) + packedLineIndexBaseOffset.a;"),i.push(" int h_index = (lineIndex - lineIndexBaseOffset) & 4095;"),i.push(" int v_index = (lineIndex - lineIndexBaseOffset) >> 12;"),i.push(" ivec3 vertexIndices = ivec3(texelFetch(uPerLineIndices, ivec2(h_index, v_index), 0));"),i.push(" ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push(" int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push(" int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push(" mat4 objectInstanceMatrix = mat4 (texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" vec3 position = vec3(texelFetch(uPerVertexPosition, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" uvec4 color = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push(" if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" };"),i.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push(" vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push(" vFragDepth = 1.0 + clipPos.w;"),i.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push(" gl_Position = clipPos;"),i.push(" vec4 rgb = vec4(color.rgba);"),i.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// LinesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class yA{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null)}eagerCreateRenders(){}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new bA(this._scene,!1)),this._colorRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy()}}const xA={};class BA{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perLineNumberPortionId8Bits=[],this.perLineNumberPortionId16Bits=[],this.perLineNumberPortionId32Bits=[]}}class wA{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerLineIdPortionIds8Bits=null,this.texturePerLineIdPortionIds16Bits=null,this.texturePerLineIdPortionIds32Bits=null,this.texturePerLineIdIndices8Bits=null,this.texturePerLineIdIndices16Bits=null,this.texturePerLineIdIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerLineIdIndices8Bits,16:this.texturePerLineIdIndices16Bits,32:this.texturePerLineIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerLineIdPortionIds8Bits,16:this.texturePerLineIdPortionIds16Bits,32:this.texturePerLineIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindLineIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}}class PA{constructor(e,t,i,s,r=null){this._gl=e,this._texture=t,this._textureWidth=i,this._textureHeight=s,this._textureData=r}bindTexture(e,t,i){return e.bindTexture(t,this,i)}bind(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}unbind(e){}}const CA={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalLines:0,totalLines8Bits:0,totalLines16Bits:0,totalLines32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(CA,null,4));let e=0;Object.keys(CA).forEach((t=>{t.startsWith("size")&&(e+=CA[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/CA.totalLines).toFixed(2)}`);let t={};Object.keys(CA).forEach((i=>{i.startsWith("size")&&(t[i]=`${(CA[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class MA{disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}generateTextureForColorsAndFlags(e,t,i,s,r){const o=t.length;this.numPortions=o;const n=4096,a=Math.ceil(o/512);if(0===a)throw"texture height===0";const l=new Uint8Array(16384*a);CA.sizeDataColorsAndFlags+=l.byteLength,CA.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),l.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20);const A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,n,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,a,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new PA(e,A,n,a,l)}generateTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);CA.sizeDataTextureOffsets+=r.byteLength,CA.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new PA(e,o,i,s,r)}generateTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);CA.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete xA[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new BA,this._dataTextureState=new wA,this._dataTextureGenerator=new MA,this._state=new _t({origin:d.vec3(t.origin),textureState:this._dataTextureState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this.primitive=t.primitive,this._finalized=!1}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&CA.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/2})),(this._state.numVertices+s>4096*FA||t+r>4096*FA)&&CA.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*FA&&t+r<=4096*FA}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/2/8)*2;CA.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}const i=t.positionsCompressed,s=t.indices,r=this._buffer;r.positionsCompressed.push(i);const o=r.lenPositionsCompressed/3,n=i.length/3;let a;r.lenPositionsCompressed+=i.length;let l=0;if(s){let e;l=s.length/2,n<=256?(e=r.indices8Bits,a=r.lenIndices8Bits/2,r.lenIndices8Bits+=s.length):n<=65536?(e=r.indices16Bits,a=r.lenIndices16Bits/2,r.lenIndices16Bits+=s.length):(e=r.indices32Bits,a=r.lenIndices32Bits/2,r.lenIndices32Bits+=s.length),e.push(s)}this._state.numVertices+=n,CA.numberOfGeometries++;return{vertexBase:o,numVertices:n,numLines:l,indicesBase:a}}_createSubPortion(e,t){const i=e.color,s=e.colors,r=e.opacity,o=e.meshMatrix,n=e.pickColor,a=this._buffer,l=this._state;a.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),a.perObjectInstancePositioningMatrices.push(o||RA),a.perObjectSolid.push(!!e.solid),s?a.perObjectColors.push([255*s[0],255*s[1],255*s[2],255]):i&&a.perObjectColors.push([i[0],i[1],i[2],r]),a.perObjectPickColors.push(n),a.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?l.numIndices8Bits:t.numVertices<=65536?l.numIndices16Bits:l.numIndices32Bits,a.perObjectIndexBaseOffsets.push(e/2-t.indicesBase)}const A=this._subPortions.length;if(t.numLines>0){let e,i=2*t.numLines;t.numVertices<=256?(e=a.perLineNumberPortionId8Bits,l.numIndices8Bits+=i,CA.totalLines8Bits+=t.numLines):t.numVertices<=65536?(e=a.perLineNumberPortionId16Bits,l.numIndices16Bits+=i,CA.totalLines16Bits+=t.numLines):(e=a.perLineNumberPortionId32Bits,l.numIndices32Bits+=i,CA.totalLines32Bits+=t.numLines),CA.totalLines+=t.numLines;for(let i=0;i0&&(t.texturePerLineIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerLineIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerLineIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}initFlags(e,t,i){t&ee&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ne&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&oe&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ae&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&se&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ie&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&te&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ae?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&se?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,DA))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),c.bindTexture(c.TEXTURE_2D,h.texturePerObjectColorsAndFlags._texture),c.texSubImage2D(c.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,c.RGBA_INTEGER,c.UNSIGNED_BYTE,DA))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,DA))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,SA))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,IA))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Vo.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Vo.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){}drawSilhouetteHighlighted(e,t){}drawSilhouetteSelected(e,t){}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}setPickMatrices(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawSnapInit(e,t){}drawSnap(e,t){}drawPickNormals(e,t){}destroy(){if(this._destroyed)return;const e=this._state;this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}const UA=d.vec3(),kA=d.vec3(),OA=d.vec3();d.vec3();const NA=d.vec4(),QA=d.mat4();class VA{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=UA;if(g){const t=d.transformPoint3(c,A,kA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=J(r.viewMatrix,e,QA),f=OA,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(let e=0,t=r.length;e0;let r;const o=[];o.push("#version 300 es"),o.push("// TrianglesDataTextureColorRenderer vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("uniform mat4 sceneModelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),o.push("uniform highp sampler2D uTexturePerObjectMatrix;"),o.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),o.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),o.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),o.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),o.push("uniform vec3 uCameraEyeRtc;"),o.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("out float isPerspective;")),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e> 3) & 4095;"),o.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),o.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),o.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),o.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),o.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),o.push("if (int(flags.x) != renderPass) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("} else {"),o.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),o.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),o.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),o.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),o.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),o.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),o.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),o.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),o.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),o.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),o.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),o.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),o.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),o.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),o.push("if (color.a == 0u) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("};"),o.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),o.push("vec3 position;"),o.push("position = positions[gl_VertexID % 3];"),o.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),o.push("if (solid != 1u) {"),o.push("if (isPerspectiveMatrix(projMatrix)) {"),o.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),o.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("} else {"),o.push("if (viewNormal.z < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("}"),o.push("}"),o.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const HA=new Float32Array([1,1,1]),jA=d.vec3(),GA=d.vec3(),zA=d.vec3();d.vec3();const WA=d.mat4();class KA{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=jA;if(A){const t=GA;d.transformPoint3(c,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=J(p,e,WA),g=zA,g[0]=r.eye[0]-e[0],g[1]=r.eye[1]-e[1],g[2]=r.eye[2]-e[2]}else f=p,g=r.eye;if(n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),i===Vo.SILHOUETTE_XRAYED){const e=s.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Vo.SILHOUETTE_HIGHLIGHTED){const e=s.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Vo.SILHOUETTE_SELECTED){const e=s.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,HA);if(s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(m>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,r=o.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = color;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const XA=new Float32Array([0,0,0,1]),JA=d.vec3(),YA=d.vec3();d.vec3();const ZA=d.mat4();class qA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=JA;if(g){const t=d.transformPoint3(c,A,YA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=J(p,e,ZA)}else f=p;if(n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),i===Vo.EDGES_XRAYED){const e=r.xrayMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Vo.EDGES_HIGHLIGHTED){const e=r.highlightMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Vo.EDGES_SELECTED){const e=r.selectedMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,XA);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const $A=d.vec3(),eh=d.vec3(),th=d.mat4();class ih{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=$A;if(g){const t=d.transformPoint3(c,A,eh);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=J(p,e,th)}else f=p;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uObjectPerObjectOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const sh=d.vec3(),rh=d.vec3(),oh=d.vec3(),nh=d.mat4();class ah{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=e.pickViewMatrix||o.viewMatrix,f=e.pickProjMatrix||o.projMatrix,g=e.pickOrigin||o.eye,m=e.pickProjMatrix?e.pickZFar:o.project.far;let _,v;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const b=0!==A[0]||0!==A[1]||0!==A[2],y=0!==h[0]||0!==h[1]||0!==h[2];if(b||y){const e=sh;if(b){const t=d.transformPoint3(c,A,rh);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],_=J(p,e,nh),v=oh,v[0]=g[0]-e[0],v[1]=g[1]-e[1],v[2]=g[2]-e[2]}else _=p,v=g;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,_),n.uniformMatrix4fv(this._uProjMatrix,!1,f),n.uniform3fv(this._uCameraEyeRtc,v),n.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(m+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const x=r._sectionPlanesState.getNumAllocatedSectionPlanes(),B=r._sectionPlanesState.sectionPlanes.length;if(x>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*B,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var s=0;s 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const lh=d.vec3(),Ah=d.vec3(),hh=d.vec3();d.vec3();const ch=d.mat4();class uh{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=e.pickViewMatrix||o.viewMatrix,f=e.pickProjMatrix||o.projMatrix,g=e.pickOrigin||o.eye,m=e.pickProjMatrix?e.pickZFar:o.project.far;let _,v;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const t=lh;if(A){const e=Ah;d.transformPoint3(c,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],_=J(p,t,ch),v=hh,v[0]=g[0]-t[0],v[1]=g[1]-t[1],v[2]=g[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else _=p,v=g,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(n.uniform3fv(this._uCameraEyeRtc,v),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniform1f(this._uPickZNear,e.pickZNear),n.uniform1f(this._uPickZFar,e.pickZFar),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,_),n.uniformMatrix4fv(this._uProjMatrix,!1,f),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(m+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const b=r._sectionPlanesState.getNumAllocatedSectionPlanes(),y=r._sectionPlanesState.sectionPlanes.length;if(b>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*y,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0;s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outPackedDepth = packDepth(zNormalizedDepth); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const dh=d.vec3(),ph=d.vec3(),fh=d.vec3(),gh=d.vec3();d.vec3();const mh=d.mat4();class _h{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=dh;let m,_;g[0]=d.safeInv(p[3]-p[0])*d.MAX_INT,g[1]=d.safeInv(p[4]-p[1])*d.MAX_INT,g[2]=d.safeInv(p[5]-p[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(g[0]),e.snapPickCoordinateScale[1]=d.safeInv(g[1]),e.snapPickCoordinateScale[2]=d.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=ph;if(v){const e=d.transformPoint3(c,A,fh);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=J(f,t,mh),_=gh,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),x=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*x,o=s.renderFlags;for(let t=0;t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(B,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(B,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(B,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uSnapVectorA;"),i.push("uniform vec2 uSnapInvVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),i.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("}"),i.push("{"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vViewPosition = clipPos;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const vh=d.vec3(),bh=d.vec3(),yh=d.vec3(),xh=d.vec3();d.vec3();const Bh=d.mat4();class wh{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=vh;let m,_;g[0]=d.safeInv(p[3]-p[0])*d.MAX_INT,g[1]=d.safeInv(p[4]-p[1])*d.MAX_INT,g[2]=d.safeInv(p[5]-p[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(g[0]),e.snapPickCoordinateScale[1]=d.safeInv(g[1]),e.snapPickCoordinateScale[2]=d.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=bh;if(v){const e=yh;d.transformPoint3(c,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=J(f,t,Bh),_=xh,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this._uVectorA,e.snapVectorA),n.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),x=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*x,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uVectorAB;"),i.push("uniform vec2 uInverseVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),i.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("}"),i.push("{"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" } else {"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ph=d.vec3(),Ch=d.vec3(),Mh=d.vec3();d.vec3();const Eh=d.mat4();class Fh{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=e.pickViewMatrix||o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=Ph;if(A){const t=Ch;d.transformPoint3(c,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=J(p,e,Eh),g=Mh,g[0]=o.eye[0]-e[0],g[1]=o.eye[1]-e[1],g[2]=o.eye[2]-e[2]}else f=p,g=o.eye;n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureOcclusionRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" } else {"),i.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureColorRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ih=d.vec3(),Dh=d.vec3(),Sh=d.vec3();d.vec3();const Th=d.mat4();class Rh{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=Ih;if(g){const t=d.transformPoint3(c,A,Dh);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=J(r.viewMatrix,e,Th),f=Sh,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Lh=d.vec3(),Uh=d.vec3(),kh=d.vec3();d.vec3();const Oh=d.mat4();class Nh{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));const g=0!==l[0]||0!==l[1]||0!==l[2],m=0!==A[0]||0!==A[1]||0!==A[2];if(g||m){const e=Lh;if(g){const t=Uh;d.transformPoint3(h,l,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=A[0],e[1]+=A[1],e[2]+=A[2],p=J(u,e,Oh),f=kh,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=u,f=o.eye;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,c),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),n.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&He.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),He.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out vec4 vFlags2;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(He.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&He.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&He.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&He.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Qh=d.vec3(),Vh=d.vec3(),Hh=d.vec3();d.vec3(),d.vec4();const jh=d.mat4();class Gh{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a));const p=e.pickViewMatrix||r.viewMatrix,f=e.pickProjMatrix||r.projMatrix,g=e.pickOrigin||r.eye,m=e.pickProjMatrix?e.pickZFar:r.project.far;let _,v;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const b=0!==A[0]||0!==A[1]||0!==A[2],y=0!==h[0]||0!==h[1]||0!==h[2];if(b||y){const e=Qh;if(b){const t=d.transformPoint3(c,A,Vh);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],_=J(p,e,jh),v=Hh,v[0]=g[0]-e[0],v[1]=g[1]-e[1],v[2]=g[2]-e[2]}else _=p,v=g;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,_),n.uniformMatrix4fv(this._uProjMatrix,!1,f),n.uniform3fv(this._uCameraEyeRtc,v),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const e=2/(Math.log(m+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const x=s._sectionPlanesState.getNumAllocatedSectionPlanes(),B=s._sectionPlanesState.sectionPlanes.length;if(x>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*B,r=o.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// trianglesDatatextureNormalsRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTexturePickNormalsRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class zh{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new KA(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new ah(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new uh(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new Gh(this._scene)),this._snapRenderer||(this._snapRenderer=new _h(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new wh(this._scene)),this._snapRenderer||(this._snapRenderer=new _h(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new VA(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new VA(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new KA(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Rh(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Nh(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new qA(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new ih(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new ah(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Gh(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Gh(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new uh(this._scene)),this._pickDepthRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new _h(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new wh(this._scene)),this._snapInitRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Fh(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const Wh={};class Kh{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}class Xh{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindTriangleIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}bindEdgeIndicesTextures(e,t,i,s){this.edgeIndicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[s].bindTexture(e,i,6)}}const Jh={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(Jh,null,4));let e=0;Object.keys(Jh).forEach((t=>{t.startsWith("size")&&(e+=Jh[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/Jh.totalPolygons).toFixed(2)}`);let t={};Object.keys(Jh).forEach((i=>{i.startsWith("size")&&(t[i]=`${(Jh[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class Yh{constructor(){}disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}createTextureForColorsAndFlags(e,t,i,s,r,o,n){const a=t.length;this.numPortions=a;const l=4096,A=Math.ceil(a/512);if(0===A)throw"texture height===0";const h=new Uint8Array(16384*A);Jh.sizeDataColorsAndFlags+=h.byteLength,Jh.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),h.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20),h.set([o[e]>>24&255,o[e]>>16&255,o[e]>>8&255,255&o[e]],32*e+24),h.set([n[e]?1:0,0,0,0],32*e+28);const c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,A),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,A,e.RGBA_INTEGER,e.UNSIGNED_BYTE,h,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new PA(e,c,l,A,h)}createTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);Jh.sizeDataTextureOffsets+=r.byteLength,Jh.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new PA(e,o,i,s,r)}createTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);Jh.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Wh[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new Kh,this._dtxState=new Xh,this._dtxTextureFactory=new Yh,this._state=new _t({origin:d.vec3(t.origin),metallicRoughnessBuf:null,textureState:this._dtxState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numEdgeIndices8Bits:0,numEdgeIndices16Bits:0,numEdgeIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this.model.scene.readableGeometryEnabled&&(this._subPortionReadableGeometries={}),this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this.primitive=t.primitive,this._finalized=!1}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&Jh.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/3})),(this._state.numVertices+s>4096*qh||t+r>4096*qh)&&Jh.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*qh&&t+r<=4096*qh}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/3/8)*3;Jh.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}if(t.edgeIndices){const e=8*Math.ceil(t.edgeIndices.length/2/8)*2;Jh.overheadSizeAlignementEdgeIndices+=2*(e-t.edgeIndices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.edgeIndices),t.edgeIndices=i}const i=t.positionsCompressed,s=t.indices,r=t.edgeIndices,o=this._buffer;o.positionsCompressed.push(i);const n=o.lenPositionsCompressed/3,a=i.length/3;let l;o.lenPositionsCompressed+=i.length;let A,h=0;if(s){let e;h=s.length/3,a<=256?(e=o.indices8Bits,l=o.lenIndices8Bits/3,o.lenIndices8Bits+=s.length):a<=65536?(e=o.indices16Bits,l=o.lenIndices16Bits/3,o.lenIndices16Bits+=s.length):(e=o.indices32Bits,l=o.lenIndices32Bits/3,o.lenIndices32Bits+=s.length),e.push(s)}let c=0;if(r){let e;c=r.length/2,a<=256?(e=o.edgeIndices8Bits,A=o.lenEdgeIndices8Bits/2,o.lenEdgeIndices8Bits+=r.length):a<=65536?(e=o.edgeIndices16Bits,A=o.lenEdgeIndices16Bits/2,o.lenEdgeIndices16Bits+=r.length):(e=o.edgeIndices32Bits,A=o.lenEdgeIndices32Bits/2,o.lenEdgeIndices32Bits+=r.length),e.push(r)}this._state.numVertices+=a,Jh.numberOfGeometries++;return{vertexBase:n,numVertices:a,numTriangles:h,numEdges:c,indicesBase:l,edgeIndicesBase:A}}_createSubPortion(e,t,i,s){const r=e.color;e.metallic,e.roughness;const o=e.colors,n=e.opacity,a=e.meshMatrix,l=e.pickColor,A=this._buffer,h=this._state;A.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),A.perObjectInstancePositioningMatrices.push(a||rc),A.perObjectSolid.push(!!e.solid),o?A.perObjectColors.push([255*o[0],255*o[1],255*o[2],255]):r&&A.perObjectColors.push([r[0],r[1],r[2],n]),A.perObjectPickColors.push(l),A.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?h.numIndices8Bits:t.numVertices<=65536?h.numIndices16Bits:h.numIndices32Bits,A.perObjectIndexBaseOffsets.push(e/3-t.indicesBase)}{let e;e=t.numVertices<=256?h.numEdgeIndices8Bits:t.numVertices<=65536?h.numEdgeIndices16Bits:h.numEdgeIndices32Bits,A.perObjectEdgeIndexBaseOffsets.push(e/2-t.edgeIndicesBase)}const c=this._subPortions.length;if(t.numTriangles>0){let e,i=3*t.numTriangles;t.numVertices<=256?(e=A.perTriangleNumberPortionId8Bits,h.numIndices8Bits+=i,Jh.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(e=A.perTriangleNumberPortionId16Bits,h.numIndices16Bits+=i,Jh.totalPolygons16Bits+=t.numTriangles):(e=A.perTriangleNumberPortionId32Bits,h.numIndices32Bits+=i,Jh.totalPolygons32Bits+=t.numTriangles),Jh.totalPolygons+=t.numTriangles;for(let i=0;i0){let e,i=2*t.numEdges;t.numVertices<=256?(e=A.perEdgeNumberPortionId8Bits,h.numEdgeIndices8Bits+=i,Jh.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(e=A.perEdgeNumberPortionId16Bits,h.numEdgeIndices16Bits+=i,Jh.totalEdges16Bits+=t.numEdges):(e=A.perEdgeNumberPortionId32Bits,h.numEdgeIndices32Bits+=i,Jh.totalEdges32Bits+=t.numEdges),Jh.totalEdges+=t.numEdges;for(let i=0;i0&&(t.texturePerEdgeIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId8Bits)),s.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId16Bits)),s.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId32Bits)),s.lenIndices8Bits>0&&(t.texturePerPolygonIdIndices8Bits=this._dtxTextureFactory.createTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerPolygonIdIndices16Bits=this._dtxTextureFactory.createTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerPolygonIdIndices32Bits=this._dtxTextureFactory.createTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),s.lenEdgeIndices8Bits>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this._dtxTextureFactory.createTextureFor8BitsEdgeIndices(i,s.edgeIndices8Bits,s.lenEdgeIndices8Bits)),s.lenEdgeIndices16Bits>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this._dtxTextureFactory.createTextureFor16BitsEdgeIndices(i,s.edgeIndices16Bits,s.lenEdgeIndices16Bits)),s.lenEdgeIndices32Bits>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this._dtxTextureFactory.createTextureFor32BitsEdgeIndices(i,s.edgeIndices32Bits,s.lenEdgeIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}isEmpty(){return 0===this._numPortions}initFlags(e,t,i){t&ee&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ne&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&oe&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ae&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&se&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&le&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ie&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&te&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ae?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&le?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&se?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dtxState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,tc))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),g.bindTexture(g.TEXTURE_2D,f.texturePerObjectColorsAndFlags._texture),g.texSubImage2D(g.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,g.RGBA_INTEGER,g.UNSIGNED_BYTE,tc))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,tc))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,ic))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,ec))}getEachVertex(e,t){if(!this.model.scene.readableGeometryEnabled)return;const i=this._state,s=this._portionToSubPortionsMap[e];if(s)for(let e=0,r=s.length;e{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==uc[e])return void uc[e].push({onLoad:t,onProgress:i,onError:s});uc[e]=[],uc[e].push({onLoad:t,onProgress:i,onError:s});const o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),n=this.mimeType,a=this.responseType;fetch(o).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;const i=uc[e],s=t.body.getReader(),r=t.headers.get("Content-Length"),o=r?parseInt(r):0,n=0!==o;let a=0;const l=new ReadableStream({start(e){!function t(){s.read().then((({done:s,value:r})=>{if(s)e.close();else{a+=r.byteLength;const s=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=i.length;e{switch(a){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,n)));case"json":return e.json();default:if(void 0===n)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(n),i=t&&t[1]?t[1].toLowerCase():void 0,s=new TextDecoder(i);return e.arrayBuffer().then((e=>s.decode(e)))}}})).then((t=>{lc.add(e,t);const i=uc[e];delete uc[e];for(let e=0,s=i.length;e{const i=uc[e];if(void 0===i)throw this.manager.itemError(e),t;delete uc[e];for(let e=0,s=i.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class pc{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e{const s=this._getIdleWorker();-1!==s?(this._initWorker(s),this.workerStatus|=1<e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let fc=0;class gc{constructor({viewer:e,transcoderPath:t,workerLimit:i}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new pc,this._workerSourceURL="",i&&this._workerPool.setWorkerLimit(i);const s=e.capabilities;this._workerConfig={astcSupported:s.astcSupported,etc1Supported:s.etc1Supported,etc2Supported:s.etc2Supported,dxtSupported:s.dxtSupported,bptcSupported:s.bptcSupported,pvrtcSupported:s.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new dc;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),i=new dc;i.setPath(this._transcoderPath),i.setResponseType("arraybuffer"),i.setWithCredentials(this.withCredentials);const s=i.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,s]).then((([e,t])=>{const i=gc.BasisWorker.toString(),s=["/* constants */","let _EngineFormat = "+JSON.stringify(gc.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(gc.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(gc.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([s])),this._transcoderBinary=t,this._workerPool.setWorkerCreator((()=>{const e=new Worker(this._workerSourceURL),t=this._transcoderBinary.slice(0);return e.postMessage({type:"init",config:this._workerConfig,transcoderBinary:t},[t]),e}))})),fc>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),fc++}return this._transcoderPending}transcode(e,t,i={}){return new Promise(((s,r)=>{const o=i;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const i=e.data,{mipmaps:o,width:n,height:a,format:l,type:A,error:h,dfdTransferFn:c,dfdFlags:u}=i;if("error"===A)return r(h);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?1006:1008,magFilter:1===o.length?1006:1008,encoding:2===c?3001:3e3,premultiplyAlpha:!!(1&u)}}),s()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),fc--}}gc.BasisFormat={ETC1S:0,UASTC_4x4:1},gc.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16},gc.EngineFormat={RGBAFormat:1023,RGBA_ASTC_4x4_Format:37808,RGBA_BPTC_Format:36492,RGBA_ETC2_EAC_Format:37496,RGBA_PVRTC_4BPPV1_Format:35842,RGBA_S3TC_DXT5_Format:33779,RGB_ETC1_Format:36196,RGB_ETC2_Format:37492,RGB_PVRTC_4BPPV1_Format:35840,RGB_S3TC_DXT1_Format:33776},gc.BasisWorker=function(){let e,t,i;const s=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const h=n.data;switch(h.type){case"init":e=h.config,c=h.transcoderBinary,t=new Promise((e=>{i={wasmBinary:c,onRuntimeInitialized:e},BASIS(i)})).then((()=>{i.initializeBasis(),void 0===i.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:c,mipmaps:u,format:d,dfdTransferFn:p,dfdFlags:f}=function(t){const n=new i.KTX2File(new Uint8Array(t));function h(){n.close(),n.delete()}if(!n.isValid())throw h(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const c=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),d=n.getHeight(),p=n.getLevels(),f=n.getHasAlpha(),g=n.getDFDTransferFunc(),m=n.getDFDFlags(),{transcoderFormat:_,engineFormat:v}=function(t,i,n,h){let c,u;const d=t===o.ETC1S?a:l;for(let s=0;s{delete mc[t],i.destroy()}))),i} +class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){let e;if(2===arguments.length){const t=arguments[0];if(e=arguments[1],this.items[t])throw"ID clash: '"+t+"'";return this.items[t]=e,t}for(e=arguments[0]||{};;){const t=this._lastUniqueId++;if(!this.items[t])return this.items[t]=e,t}}removeItem(e){const t=this.items[e];return delete this.items[e],t}}const t=new e;class i{constructor(e){this.id=e,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0}}class s{constructor(){this.items=[]}}class r{constructor(e,t,i,s,r){this.id=e,this.getTitle=t,this.doAction=i,this.getEnabled=s,this.getShown=r,this.itemElement=null,this.subMenu=null,this.enabled=!0}}class o{constructor(e={}){this._id=t.addItem(),this._context=null,this._enabled=!1,this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={},this._shown=!1,this._nextId=0,this._eventSubs={},!1!==e.hideOnMouseDown&&(document.addEventListener("mousedown",(e=>{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),document.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),e.items&&(this.items=e.items),this._hideOnAction=!1!==e.hideOnAction,this.context=e.context,this.enabled=!1!==e.enabled,this.hide()}on(e,t){let 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{const o=this._getNextId(),n=new i(o);for(let i=0,o=e.length;i0,A=this._getNextId(),h=i.getTitle||(()=>i.title||""),c=i.doAction||i.callback||(()=>{}),u=i.getEnabled||(()=>!0),d=i.getShown||(()=>!0),p=new r(A,h,c,u,d);if(p.parentMenu=n,a.items.push(p),l){const e=t(s);p.subMenu=e,e.parentItem=p}this._itemList.push(p),this._itemMap[p.id]=p}}return this._menuList.push(n),this._menuMap[n.id]=n,n};this._rootMenu=t(e)}_getNextId(){return"ContextMenu_"+this._id+"_"+this._nextId++}_createUI(){const e=t=>{this._createMenuUI(t);const i=t.groups;for(let t=0,s=i.length;t'),i.push("
    "),t)for(let e=0,s=t.length;e'+l+""),r===o-1||e')):(i.push('
  • '+l+"
  • "),r===o-1||e'))}}i.push("
"),i.push("");const s=i.join("");document.body.insertAdjacentHTML("beforeend",s);const r=document.querySelector("."+e.id);e.menuElement=r,r.style["border-radius"]="4px",r.style.display="none",r.style["z-index"]=3e5,r.style.background="white",r.style.border="1px solid black",r.style["box-shadow"]="0 4px 5px 0 gray",r.oncontextmenu=e=>{e.preventDefault()};const o=this;let n=null;if(t)for(let e=0,i=t.length;e{e.preventDefault();const i=t.subMenu;if(!i)return void(n&&(o._hideMenu(n.id),n=null));if(n&&n.id!==i.id&&(o._hideMenu(n.id),n=null),!1===t.enabled)return;const s=t.itemElement,r=i.menuElement,a=s.getBoundingClientRect();r.getBoundingClientRect();a.right+200>window.innerWidth?o._showMenu(i.id,a.left-200,a.top-1):o._showMenu(i.id,a.right-5,a.top-1),n=i})),s||(t.itemElement.addEventListener("click",(e=>{e.preventDefault(),o._context&&!1!==t.enabled&&(t.doAction&&t.doAction(o._context),this._hideOnAction?o.hide():(o._updateItemsTitles(),o._updateItemsEnabledStatus()))})),t.itemElement.addEventListener("mouseup",(e=>{3===e.which&&(e.preventDefault(),o._context&&!1!==t.enabled&&(t.doAction&&t.doAction(o._context),this._hideOnAction?o.hide():(o._updateItemsTitles(),o._updateItemsEnabledStatus())))})),t.itemElement.addEventListener("mouseenter",(e=>{e.preventDefault(),!1!==t.enabled&&t.doHover&&t.doHover(o._context)})))):console.error("ContextMenu item element not found: "+t.id)}}}_updateItemsTitles(){if(this._context)for(let e=0,t=this._itemList.length;e{n.subMenu&&(e=n.itemElement,t=e.getBoundingClientRect(),i=n.subMenu.menuElement,s={visibility:i.style.visibility,display:i.style.display},i.style.display="block",i.style.visibility="hidden",o=n.subMenu.menuElement.getBoundingClientRect().width,i.style.visibility=s.visibility,i.style.display=s.display,r=t.right+o>window.innerWidth,e.setAttribute("data-submenuposition",r?"left":"right"))}))}_showMenu(e,t,i){const s=this._menuMap[e];if(!s)return void console.error("Menu not found: "+e);if(s.shown)return;const r=s.menuElement;r&&(this._showMenuElement(r,t,i),s.shown=!0)}_hideMenu(e){const t=this._menuMap[e];if(!t)return void console.error("Menu not found: "+e);if(!t.shown)return;const i=t.menuElement;i&&(this._hideMenuElement(i),t.shown=!1)}_hideAllMenus(){for(let e=0,t=this._menuList.length;ewindow.innerHeight&&(i=window.innerHeight-s),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=i+"px"}_hideMenuElement(e){e.style.display="none"}}class n{constructor(e,t={}){this.viewer=e,this.scene=this.viewer.scene,this._lensCursorDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._lensCursorDiv,this.viewer.scene.canvas.canvas),this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red",this._lensCursorDiv.style.borderRadius="20px",this._lensCursorDiv.style.width="10px",this._lensCursorDiv.style.height="10px",this._lensCursorDiv.style.margin="-200px -200px",this._lensCursorDiv.style.zIndex="100000",this._lensCursorDiv.style.position="absolute",this._lensCursorDiv.style.pointerEvents="none",this._lensContainer=document.createElement("div"),this._lensContainerId=t.containerId||"xeokit-lens",this._lensContainer.setAttribute("id",this._lensContainerId),this._lensContainer.style.border="1px solid black",this._lensContainer.style.background="white",this._lensContainer.style.borderRadius="50%",this._lensContainer.style.width="300px",this._lensContainer.style.height="300px",this._lensContainer.style.zIndex="15000",this._lensContainer.style.position="absolute",this._lensContainer.style.pointerEvents="none",this._lensContainer.style.visibility="hidden",this._lensCanvas=document.createElement("canvas"),this._lensCanvas.id=`${this._lensContainerId}-canvas`,this._lensCanvas.style.borderRadius="50%",this._lensCanvas.style.width="300px",this._lensCanvas.style.height="300px",this._lensCanvas.style.zIndex="15000",this._lensCanvas.style.pointerEvents="none",document.body.appendChild(this._lensContainer),this._lensContainer.appendChild(this._lensCanvas),this._lensCanvasContext=this._lensCanvas.getContext("2d"),this._canvasElement=this.viewer.scene.canvas.canvas,this._canvasPos=null,this._snappedCanvasPos=null,this._lensPosToggle=t.lensPosToggle||!0,this._lensPosToggleAmount=t.lensPosToggleAmount||85,this._lensPosMarginLeft=t.lensPosMarginLeft||85,this._lensPosMarginTop=t.lensPosMarginTop||25,this._lensContainer.style.marginTop=`${this._lensPosMarginTop}px`,this._lensContainer.style.marginLeft=`${this._lensPosMarginLeft}px`,this._zoomLevel=t.zoomLevel||2,this._active=!1!==t.active,this._visible=!1,this._snapped=!1,this._onViewerRendering=this.viewer.scene.on("rendering",(()=>{this._active&&this._visible&&this.update()}))}update(){if(!this._active||!this._visible)return;if(!this._canvasPos)return;const e=this._lensContainer.getBoundingClientRect(),t=this._canvasElement.getBoundingClientRect(),i=this._canvasPos[0]e.left&&this._canvasPos[1]e.top;this._lensContainer.style.marginLeft=`${this._lensPosMarginLeft}px`,i&&(this._lensPosToggle?this._lensContainer.style.marginTop=t.bottom-t.top-this._lensCanvas.height-this._lensPosToggleAmount+"px":this._lensContainer.style.marginTop=`${this._lensPosMarginTop}px`,this._lensPosToggle=!this._lensPosToggle),this._lensCanvasContext.clearRect(0,0,this._lensCanvas.width,this._lensCanvas.height);const s=Math.max(this._lensCanvas.width,this._lensCanvas.height)/this._zoomLevel;this._lensCanvasContext.drawImage(this._canvasElement,this._canvasPos[0]-s/2,this._canvasPos[1]-s/2,s,s,0,0,this._lensCanvas.width,this._lensCanvas.height);const r=[(e.left+e.right)/2-t.left,(e.top+e.bottom)/2-t.top];if(this._snappedCanvasPos){const e=this._snappedCanvasPos[0]-this._canvasPos[0],t=this._snappedCanvasPos[1]-this._canvasPos[1];this._lensCursorDiv.style.marginLeft=r[0]+e*this._zoomLevel-10+"px",this._lensCursorDiv.style.marginTop=r[1]+t*this._zoomLevel-10+"px"}else this._lensCursorDiv.style.marginLeft=r[0]-10+"px",this._lensCursorDiv.style.marginTop=r[1]-10+"px"}set zoomFactor(e){this._zoomFactor=e,this.update()}get zoomFactor(){return this._zoomFactor}set canvasPos(e){this._canvasPos=e,this.update()}get canvasPos(){return this._canvasPos}set snappedCanvasPos(e){this._snappedCanvasPos=e,this.update()}get snappedCanvasPos(){return this._snappedCanvasPos}set snapped(e){this._snapped=e,e?(this._lensCursorDiv.style.background="greenyellow",this._lensCursorDiv.style.border="2px solid green"):(this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red")}get snapped(){return this._snapped}set active(e){this._active=e,this._lensContainer.style.visibility=e&&this._visible?"visible":"hidden",e&&this._visible||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}get active(){return this._active}set visible(e){this._visible=e,this._lensContainer.style.visibility=e&&this._active?"visible":"hidden",e&&this._active||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}get visible(){return this._visible}destroy(){this._destroyed||(this.viewer.scene.off(this._onViewerRendering),this._lensContainer.removeChild(this._lensCanvas),document.body.removeChild(this._lensContainer),this._destroyed=!0)}}let a=!0,l=a?Float64Array:Float32Array;const A=new l(3),h=new l(16),c=new l(16),u=new l(4),d={setDoublePrecisionEnabled(e){a=e,l=a?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>a,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new l(e||2),vec3:e=>new l(e||3),vec4:e=>new l(e||4),mat3:e=>new l(e||9),mat3ToMat4:(e,t=new l(16))=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t),mat4:e=>new l(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,i){const s=new l(2);for(let r=0,o=e.length;r{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,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(ee[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i),addVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i),addVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i),addVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i),subVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i),subVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i),subVec2:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i),geometricMeanVec2(...e){const t=new l(e[0]);for(let i=1;i(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i),subScalarVec4:(e,t,i)=>(i||(i=e),i[0]=t-e[0],i[1]=t-e[1],i[2]=t-e[2],i[3]=t-e[3],i),mulVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]*t[0],i[1]=e[1]*t[1],i[2]=e[2]*t[2],i[3]=e[3]*t[3],i),mulVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i),mulVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i),mulVec2Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i),divVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i),divVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i[3]=e[3]/t[3],i),divScalarVec3:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i),divVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i),divVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i[3]=e[3]/t,i),divScalarVec4:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i[3]=e/t[3],i),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const i=e[0],s=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[s*a-r*n,r*o-i*a,i*n-s*o,0]},cross3Vec3(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return i[0]=r*l-o*a,i[1]=o*n-s*l,i[2]=s*a-r*n,i},sqLenVec4:e=>d.dotVec4(e,e),lenVec4:e=>Math.sqrt(d.sqLenVec4(e)),dotVec3:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],dotVec2:(e,t)=>e[0]*t[0]+e[1]*t[1],sqLenVec3:e=>d.dotVec3(e,e),sqLenVec2:e=>d.dotVec2(e,e),lenVec3:e=>Math.sqrt(d.sqLenVec3(e)),distVec3:(()=>{const e=new l(3);return(t,i)=>d.lenVec3(d.subVec3(t,i,e))})(),lenVec2:e=>Math.sqrt(d.sqLenVec2(e)),distVec2:(()=>{const e=new l(2);return(t,i)=>d.lenVec2(d.subVec2(t,i,e))})(),rcpVec3:(e,t)=>d.divScalarVec3(1,e,t),normalizeVec4(e,t){const i=1/d.lenVec4(e);return d.mulVec4Scalar(e,i,t)},normalizeVec3(e,t){const i=1/d.lenVec3(e);return d.mulVec3Scalar(e,i,t)},normalizeVec2(e,t){const i=1/d.lenVec2(e);return d.mulVec2Scalar(e,i,t)},angleVec3(e,t){let i=d.dotVec3(e,t)/Math.sqrt(d.sqLenVec3(e)*d.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:(()=>{const e=new l(3);return(t,i)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=d.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=d.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=d.lenVec3(e),i)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let i=0,s=(t=Array.prototype.slice.call(t)).length;i({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||d.vec3())[0]=e.x,t[1]=e.y,t[2]=e.z,t),dupMat4:e=>e.slice(0,16),mat4To3:e=>[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]],m4s:e=>[e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e],setMat4ToZeroes:()=>d.m4s(0),setMat4ToOnes:()=>d.m4s(1),diagonalMat4v:e=>new l([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,i,s)=>d.diagonalMat4v([e,t,i,s]),diagonalMat4s:e=>d.diagonalMat4c(e,e,e,e),identityMat4:(e=new l(16))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e),identityMat3:(e=new l(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i),addMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i),addScalarMat4:(e,t,i)=>d.addMat4Scalar(t,e,i),subMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i),subMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i),subScalarMat4:(e,t,i)=>(i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i),mulMat4(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],A=e[6],h=e[7],c=e[8],u=e[9],d=e[10],p=e[11],f=e[12],g=e[13],m=e[14],_=e[15],v=t[0],b=t[1],y=t[2],x=t[3],B=t[4],w=t[5],P=t[6],C=t[7],M=t[8],E=t[9],F=t[10],I=t[11],D=t[12],S=t[13],T=t[14],R=t[15];return i[0]=v*s+b*a+y*c+x*f,i[1]=v*r+b*l+y*u+x*g,i[2]=v*o+b*A+y*d+x*m,i[3]=v*n+b*h+y*p+x*_,i[4]=B*s+w*a+P*c+C*f,i[5]=B*r+w*l+P*u+C*g,i[6]=B*o+w*A+P*d+C*m,i[7]=B*n+w*h+P*p+C*_,i[8]=M*s+E*a+F*c+I*f,i[9]=M*r+E*l+F*u+I*g,i[10]=M*o+E*A+F*d+I*m,i[11]=M*n+E*h+F*p+I*_,i[12]=D*s+S*a+T*c+R*f,i[13]=D*r+S*l+T*u+R*g,i[14]=D*o+S*A+T*d+R*m,i[15]=D*n+S*h+T*p+R*_,i},mulMat3(e,t,i){i||(i=new l(9));const s=e[0],r=e[3],o=e[6],n=e[1],a=e[4],A=e[7],h=e[2],c=e[5],u=e[8],d=t[0],p=t[3],f=t[6],g=t[1],m=t[4],_=t[7],v=t[2],b=t[5],y=t[8];return i[0]=s*d+r*g+o*v,i[3]=s*p+r*m+o*b,i[6]=s*f+r*_+o*y,i[1]=n*d+a*g+A*v,i[4]=n*p+a*m+A*b,i[7]=n*f+a*_+A*y,i[2]=h*d+c*g+u*v,i[5]=h*p+c*m+u*b,i[8]=h*f+c*_+u*y,i},mulMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i),mulMat4v4(e,t,i=d.vec4()){const s=t[0],r=t[1],o=t[2],n=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*n,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*n,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*n,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*n,i},transposeMat4(e,t){const i=e[4],s=e[14],r=e[8],o=e[13],n=e[12],a=e[9];if(!t||e===t){const t=e[1],l=e[2],A=e[3],h=e[6],c=e[7],u=e[11];return e[1]=i,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=h,e[11]=s,e[12]=A,e[13]=c,e[14]=u,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=n,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=o,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4(e){const t=e[0],i=e[1],s=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],A=e[8],h=e[9],c=e[10],u=e[11],d=e[12],p=e[13],f=e[14],g=e[15];return d*h*a*r-A*p*a*r-d*n*c*r+o*p*c*r+A*n*f*r-o*h*f*r-d*h*s*l+A*p*s*l+d*i*c*l-t*p*c*l-A*i*f*l+t*h*f*l+d*n*s*u-o*p*s*u-d*i*a*u+t*p*a*u+o*i*f*u-t*n*f*u-A*n*s*g+o*h*s*g+A*i*a*g-t*h*a*g-o*i*c*g+t*n*c*g},inverseMat4(e,t){t||(t=e);const i=e[0],s=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],A=e[7],h=e[8],c=e[9],u=e[10],d=e[11],p=e[12],f=e[13],g=e[14],m=e[15],_=i*a-s*n,v=i*l-r*n,b=i*A-o*n,y=s*l-r*a,x=s*A-o*a,B=r*A-o*l,w=h*f-c*p,P=h*g-u*p,C=h*m-d*p,M=c*g-u*f,E=c*m-d*f,F=u*m-d*g,I=1/(_*F-v*E+b*M+y*C-x*P+B*w);return t[0]=(a*F-l*E+A*M)*I,t[1]=(-s*F+r*E-o*M)*I,t[2]=(f*B-g*x+m*y)*I,t[3]=(-c*B+u*x-d*y)*I,t[4]=(-n*F+l*C-A*P)*I,t[5]=(i*F-r*C+o*P)*I,t[6]=(-p*B+g*b-m*v)*I,t[7]=(h*B-u*b+d*v)*I,t[8]=(n*E-a*C+A*w)*I,t[9]=(-i*E+s*C-o*w)*I,t[10]=(p*x-f*b+m*_)*I,t[11]=(-h*x+c*b-d*_)*I,t[12]=(-n*M+a*P-l*w)*I,t[13]=(i*M-s*P+r*w)*I,t[14]=(-p*y+f*v-g*_)*I,t[15]=(h*y-c*v+u*_)*I,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const i=t||d.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v(e,t){const i=t||d.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(()=>{const e=new l(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,d.translationMat4v(e,r))})(),translationMat4s:(e,t)=>d.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>d.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,i,s){const r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;const o=s[7];s[4]+=o*e,s[5]+=o*t,s[6]+=o*i;const n=s[11];s[8]+=n*e,s[9]+=n*t,s[10]+=n*i;const a=s[15];return s[12]+=a*e,s[13]+=a*t,s[14]+=a*i,s},setMat4Translation:(e,t,i)=>(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i),rotationMat4v(e,t,i){const s=d.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=s[0],l=s[1],A=s[2];let h,c,u,p,f,g;return h=a*l,c=l*A,u=A*a,p=a*r,f=l*r,g=A*r,(i=i||d.mat4())[0]=n*a*a+o,i[1]=n*h+g,i[2]=n*u-f,i[3]=0,i[4]=n*h-g,i[5]=n*l*l+o,i[6]=n*c+p,i[7]=0,i[8]=n*u+f,i[9]=n*c-p,i[10]=n*A*A+o,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:(e,t,i,s,r)=>d.rotationMat4v(e,[t,i,s],r),scalingMat4v:(e,t=d.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=d.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new l(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,d.scalingMat4v(e,r))})(),scaleMat4c:(e,t,i,s)=>(s[0]*=e,s[4]*=t,s[8]*=i,s[1]*=e,s[5]*=t,s[9]*=i,s[2]*=e,s[6]*=t,s[10]*=i,s[3]*=e,s[7]*=t,s[11]*=i,s),scaleMat4v(e,t){const i=e[0],s=e[1],r=e[2];return t[0]*=i,t[4]*=s,t[8]*=r,t[1]*=i,t[5]*=s,t[9]*=r,t[2]*=i,t[6]*=s,t[10]*=r,t[3]*=i,t[7]*=s,t[11]*=r,t},scalingMat4s:e=>d.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,i=d.mat4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=s+s,l=r+r,A=o+o,h=s*a,c=s*l,u=s*A,p=r*l,f=r*A,g=o*A,m=n*a,_=n*l,v=n*A;return i[0]=1-(p+g),i[1]=c+v,i[2]=u-_,i[3]=0,i[4]=c-v,i[5]=1-(h+g),i[6]=f+m,i[7]=0,i[8]=u+_,i[9]=f-m,i[10]=1-(h+p),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler(e,t,i=d.vec4()){const s=d.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],A=e[9],h=e[2],c=e[6],u=e[10];return"XYZ"===t?(i[1]=Math.asin(s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(-A,u),i[2]=Math.atan2(-o,r)):(i[0]=Math.atan2(c,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(A,-1,1)),Math.abs(A)<.99999?(i[1]=Math.atan2(n,u),i[2]=Math.atan2(a,l)):(i[1]=Math.atan2(-h,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(c,-1,1)),Math.abs(c)<.99999?(i[1]=Math.atan2(-h,u),i[2]=Math.atan2(-o,l)):(i[1]=0,i[2]=Math.atan2(a,r))):"ZYX"===t?(i[1]=Math.asin(-s(h,-1,1)),Math.abs(h)<.99999?(i[0]=Math.atan2(c,u),i[2]=Math.atan2(a,r)):(i[0]=0,i[2]=Math.atan2(-o,l))):"YZX"===t?(i[2]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-A,l),i[1]=Math.atan2(-h,r)):(i[0]=0,i[1]=Math.atan2(n,u))):"XZY"===t&&(i[2]=Math.asin(-s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(c,l),i[1]=Math.atan2(n,r)):(i[0]=Math.atan2(-A,u),i[1]=0)),i},composeMat4:(e,t,i,s=d.mat4())=>(d.quaternionToRotationMat4(t,s),d.scaleMat4v(i,s),d.translateMat4v(e,s),s),decomposeMat4:(()=>{const e=new l(3),t=new l(16);return function(i,s,r,o){e[0]=i[0],e[1]=i[1],e[2]=i[2];let n=d.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];const a=d.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];const l=d.lenVec3(e);d.determinantMat4(i)<0&&(n=-n),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);const A=1/n,h=1/a,c=1/l;return t[0]*=A,t[1]*=A,t[2]*=A,t[4]*=h,t[5]*=h,t[6]*=h,t[8]*=c,t[9]*=c,t[10]*=c,d.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v(e,t,i,s){s||(s=d.mat4());const r=e[0],o=e[1],n=e[2],a=i[0],l=i[1],A=i[2],h=t[0],c=t[1],u=t[2];if(r===h&&o===c&&n===u)return d.identityMat4();let p,f,g,m,_,v,b,y,x,B;return p=r-h,f=o-c,g=n-u,B=1/Math.sqrt(p*p+f*f+g*g),p*=B,f*=B,g*=B,m=l*g-A*f,_=A*p-a*g,v=a*f-l*p,B=Math.sqrt(m*m+_*_+v*v),B?(B=1/B,m*=B,_*=B,v*=B):(m=0,_=0,v=0),b=f*v-g*_,y=g*m-p*v,x=p*_-f*m,B=Math.sqrt(b*b+y*y+x*x),B?(B=1/B,b*=B,y*=B,x*=B):(b=0,y=0,x=0),s[0]=m,s[1]=b,s[2]=p,s[3]=0,s[4]=_,s[5]=y,s[6]=f,s[7]=0,s[8]=v,s[9]=x,s[10]=g,s[11]=0,s[12]=-(m*r+_*o+v*n),s[13]=-(b*r+y*o+x*n),s[14]=-(p*r+f*o+g*n),s[15]=1,s},lookAtMat4c:(e,t,i,s,r,o,n,a,l)=>d.lookAtMat4v([e,t,i],[s,r,o],[n,a,l],[]),orthoMat4c(e,t,i,s,r,o,n){n||(n=d.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2/l,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=-2/A,n[11]=0,n[12]=-(e+t)/a,n[13]=-(s+i)/l,n[14]=-(o+r)/A,n[15]=1,n},frustumMat4v(e,t,i){i||(i=d.mat4());const s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];d.addVec4(r,s,h),d.subVec4(r,s,c);const o=2*s[2],n=c[0],a=c[1],l=c[2];return i[0]=o/n,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=o/a,i[6]=0,i[7]=0,i[8]=h[0]/n,i[9]=h[1]/a,i[10]=-h[2]/l,i[11]=-1,i[12]=0,i[13]=0,i[14]=-o*r[2]/l,i[15]=0,i},frustumMat4(e,t,i,s,r,o,n){n||(n=d.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2*r/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2*r/l,n[6]=0,n[7]=0,n[8]=(t+e)/a,n[9]=(s+i)/l,n[10]=-(o+r)/A,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/A,n[15]=0,n},perspectiveMat4(e,t,i,s,r){const o=[],n=[];return o[2]=i,n[2]=s,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],d.frustumMat4v(o,n,r)},compareMat4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15],transformPoint3(e,t,i=d.vec3()){const s=t[0],r=t[1],o=t[2];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12],i[1]=e[1]*s+e[5]*r+e[9]*o+e[13],i[2]=e[2]*s+e[6]*r+e[10]*o+e[14],i},transformPoint4:(e,t,i=d.vec4())=>(i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i),transformPoints3(e,t,i){const s=i||[],r=t.length;let o,n,a,l;const A=e[0],h=e[1],c=e[2],u=e[3],d=e[4],p=e[5],f=e[6],g=e[7],m=e[8],_=e[9],v=e[10],b=e[11],y=e[12],x=e[13],B=e[14],w=e[15];let P;for(let e=0;e{const e=new l(16),t=new l(16),i=new l(16);return function(s,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),i),s,n)}})(),lerpVec3(e,t,i,s,r,o){const n=o||d.vec3(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n},lerpMat4(e,t,i,s,r,o){const n=o||d.mat4(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n[3]=s[3]+a*(r[3]-s[3]),n[4]=s[4]+a*(r[4]-s[4]),n[5]=s[5]+a*(r[5]-s[5]),n[6]=s[6]+a*(r[6]-s[6]),n[7]=s[7]+a*(r[7]-s[7]),n[8]=s[8]+a*(r[8]-s[8]),n[9]=s[9]+a*(r[9]-s[9]),n[10]=s[10]+a*(r[10]-s[10]),n[11]=s[11]+a*(r[11]-s[11]),n[12]=s[12]+a*(r[12]-s[12]),n[13]=s[13]+a*(r[13]-s[13]),n[14]=s[14]+a*(r[14]-s[14]),n[15]=s[15]+a*(r[15]-s[15]),n},flatten(e){const t=[];let i,s,r,o,n;for(i=0,s=e.length;i(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,i=d.vec4()){const s=e[0]*d.DEGTORAD/2,r=e[1]*d.DEGTORAD/2,o=e[2]*d.DEGTORAD/2,n=Math.cos(s),a=Math.cos(r),l=Math.cos(o),A=Math.sin(s),h=Math.sin(r),c=Math.sin(o);return"XYZ"===t?(i[0]=A*a*l+n*h*c,i[1]=n*h*l-A*a*c,i[2]=n*a*c+A*h*l,i[3]=n*a*l-A*h*c):"YXZ"===t?(i[0]=A*a*l+n*h*c,i[1]=n*h*l-A*a*c,i[2]=n*a*c-A*h*l,i[3]=n*a*l+A*h*c):"ZXY"===t?(i[0]=A*a*l-n*h*c,i[1]=n*h*l+A*a*c,i[2]=n*a*c+A*h*l,i[3]=n*a*l-A*h*c):"ZYX"===t?(i[0]=A*a*l-n*h*c,i[1]=n*h*l+A*a*c,i[2]=n*a*c-A*h*l,i[3]=n*a*l+A*h*c):"YZX"===t?(i[0]=A*a*l+n*h*c,i[1]=n*h*l+A*a*c,i[2]=n*a*c-A*h*l,i[3]=n*a*l-A*h*c):"XZY"===t&&(i[0]=A*a*l-n*h*c,i[1]=n*h*l-A*a*c,i[2]=n*a*c+A*h*l,i[3]=n*a*l+A*h*c),i},mat4ToQuaternion(e,t=d.vec4()){const i=e[0],s=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],A=e[6],h=e[10];let c;const u=i+n+h;return u>0?(c=.5/Math.sqrt(u+1),t[3]=.25/c,t[0]=(A-a)*c,t[1]=(r-l)*c,t[2]=(o-s)*c):i>n&&i>h?(c=2*Math.sqrt(1+i-n-h),t[3]=(A-a)/c,t[0]=.25*c,t[1]=(s+o)/c,t[2]=(r+l)/c):n>h?(c=2*Math.sqrt(1+n-i-h),t[3]=(r-l)/c,t[0]=(s+o)/c,t[1]=.25*c,t[2]=(a+A)/c):(c=2*Math.sqrt(1+h-i-n),t[3]=(o-s)/c,t[0]=(r+l)/c,t[1]=(a+A)/c,t[2]=.25*c),t},vec3PairToQuaternion(e,t,i=d.vec4()){const s=Math.sqrt(d.dotVec3(e,e)*d.dotVec3(t,t));let r=s+d.dotVec3(e,t);return r<1e-8*s?(r=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):d.cross3Vec3(e,t,i),i[3]=r,d.normalizeQuaternion(i)},angleAxisToQuaternion(e,t=d.vec4()){const i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:(()=>{const e=new l(16);return(t,i,s)=>(s=s||d.vec3(),d.quaternionToRotationMat4(t,e),d.mat4ToEuler(e,i,s),s)})(),mulQuaternions(e,t,i=d.vec4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],A=t[2],h=t[3];return i[0]=n*a+s*h+r*A-o*l,i[1]=n*l+r*h+o*a-s*A,i[2]=n*A+o*h+s*l-r*a,i[3]=n*h-s*a-r*l-o*A,i},vec3ApplyQuaternion(e,t,i=d.vec3()){const s=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],A=e[3],h=A*s+a*o-l*r,c=A*r+l*s-n*o,u=A*o+n*r-a*s,p=-n*s-a*r-l*o;return i[0]=h*A+p*-n+c*-l-u*-a,i[1]=c*A+p*-a+u*-n-h*-l,i[2]=u*A+p*-l+h*-a-c*-n,i},quaternionToMat4(e,t){t=d.identityMat4(t);const i=e[0],s=e[1],r=e[2],o=e[3],n=2*i,a=2*s,l=2*r,A=n*o,h=a*o,c=l*o,u=n*i,p=a*i,f=l*i,g=a*s,m=l*s,_=l*r;return t[0]=1-(g+_),t[1]=p+c,t[2]=f-h,t[4]=p-c,t[5]=1-(u+_),t[6]=m+A,t[8]=f+h,t[9]=m-A,t[10]=1-(u+g),t},quaternionToRotationMat4(e,t){const i=e[0],s=e[1],r=e[2],o=e[3],n=i+i,a=s+s,l=r+r,A=i*n,h=i*a,c=i*l,u=s*a,d=s*l,p=r*l,f=o*n,g=o*a,m=o*l;return t[0]=1-(u+p),t[4]=h-m,t[8]=c+g,t[1]=h+m,t[5]=1-(A+p),t[9]=d-f,t[2]=c-g,t[6]=d+f,t[10]=1-(A+u),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const i=d.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>d.normalizeQuaternion(d.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=d.vec4()){const i=(e=d.normalizeQuaternion(e,u))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:e=>new l(e||6),AABB2:e=>new l(e||4),OBB3:e=>new l(e||32),OBB2:e=>new l(e||16),Sphere3:(e,t,i,s)=>new l([e,t,i,s]),transformOBB3(e,t,i=t){let s;const r=t.length;let o,n,a;const l=e[0],A=e[1],h=e[2],c=e[3],u=e[4],d=e[5],p=e[6],f=e[7],g=e[8],m=e[9],_=e[10],v=e[11],b=e[12],y=e[13],x=e[14],B=e[15];for(s=0;s{const e=new l(3),t=new l(3),i=new l(3);return s=>(e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5],d.subVec3(t,e,i),Math.abs(d.lenVec3(i)))})(),getAABB3DiagPoint:(()=>{const e=new l(3),t=new l(3),i=new l(3);return(s,r)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5];const o=d.subVec3(t,e,i),n=r[0]-s[0],a=s[3]-r[0],l=r[1]-s[1],A=s[4]-r[1],h=r[2]-s[2],c=s[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>A?l:A,o[2]+=h>c?h:c,Math.abs(d.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const i=t||d.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center(e,t){const i=t||d.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:(e=d.AABB3())=>(e[0]=d.MAX_DOUBLE,e[1]=d.MAX_DOUBLE,e[2]=d.MAX_DOUBLE,e[3]=d.MIN_DOUBLE,e[4]=d.MIN_DOUBLE,e[5]=d.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=d.OBB3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t),positions3ToAABB3:(()=>{const e=new l(3);return(t,i,s)=>{i=i||d.AABB3();let r,o,n,a=d.MAX_DOUBLE,l=d.MAX_DOUBLE,A=d.MAX_DOUBLE,h=d.MIN_DOUBLE,c=d.MIN_DOUBLE,u=d.MIN_DOUBLE;for(let i=0,p=t.length;ih&&(h=r),o>c&&(c=o),n>u&&(u=n);return i[0]=a,i[1]=l,i[2]=A,i[3]=h,i[4]=c,i[5]=u,i}})(),OBB3ToAABB3(e,t=d.AABB3()){let i,s,r,o=d.MAX_DOUBLE,n=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MIN_DOUBLE,A=d.MIN_DOUBLE,h=d.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToAABB3(e,t=d.AABB3()){let i,s,r,o=d.MAX_DOUBLE,n=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MIN_DOUBLE,A=d.MIN_DOUBLE,h=d.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToSphere3:(()=>{const e=new l(3);return(t,i)=>{i=i||d.vec4();let s,r=0,o=0,n=0;const a=t.length;for(s=0;sA&&(A=l);return i[3]=A,i}})(),positions3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(i,s)=>{s=s||d.vec4();let r,o=0,n=0,a=0;const l=i.length;let A=0;for(r=0;rA&&(A=c);return s[3]=A,s}})(),OBB3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(i,s)=>{s=s||d.vec4();let r,o=0,n=0,a=0;const l=i.length,A=l/4;for(r=0;rc&&(c=h);return s[3]=c,s}})(),getSphere3Center:(e,t=d.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=d.vec3()){let i=0,s=0,r=0;for(var o=0,n=e.length;o(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3](e[0]=d.MAX_DOUBLE,e[1]=d.MAX_DOUBLE,e[2]=d.MIN_DOUBLE,e[3]=d.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]e[0]<=t[0]&&e[3]>=t[0]&&e[1]<=t[1]&&e[4]>=t[1]&&e[2]<=t[2]&&e[5]>=t[2],planeAABB3Intersect(e,t,i){let s,r;e[0]>0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]);if(s<=-t&&r<=-t)return-1;return s>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=d.AABB2()){let i,s,r,o,n=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MIN_DOUBLE,A=d.MIN_DOUBLE;for(let t=0,h=e.length;tl&&(l=i),s>A&&(A=s);return t[0]=n,t[1]=a,t[2]=l,t[3]=A,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]2*(1-e)*(i-t)+2*e*(s-i),tangentQuadraticBezier3:(e,t,i,s,r)=>-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r,tangentSpline:e=>6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e),catmullRomInterpolate(e,t,i,s,r){const o=.5*(i-e),n=.5*(s-t),a=r*r;return(2*t-2*i+o+n)*(r*a)+(-3*t+3*i-2*o-n)*a+o*r+t},b2p0(e,t){const i=1-e;return i*i*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0(e,t){const i=1-e;return i*i*i*t},b3p1(e,t){const i=1-e;return 3*i*i*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal(e,t,i,s=d.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=i[0]-e[0],l=i[1]-e[1],A=i[2]-e[2],h=o*A-n*l,c=n*a-r*A,u=r*l-o*a,p=Math.sqrt(h*h+c*c+u*u);return 0===p?(s[0]=0,s[1]=0,s[2]=0):(s[0]=h/p,s[1]=c/p,s[2]=u/p),s},rayTriangleIntersect:(()=>{const e=new l(3),t=new l(3),i=new l(3),s=new l(3),r=new l(3);return(o,n,a,l,A,h)=>{h=h||d.vec3();const c=d.subVec3(l,a,e),u=d.subVec3(A,a,t),p=d.cross3Vec3(n,u,i),f=d.dotVec3(c,p);if(f<1e-6)return null;const g=d.subVec3(o,a,s),m=d.dotVec3(g,p);if(m<0||m>f)return null;const _=d.cross3Vec3(g,c,r),v=d.dotVec3(n,_);if(v<0||m+v>f)return null;const b=d.dotVec3(u,_)/f;return h[0]=o[0]+b*n[0],h[1]=o[1]+b*n[1],h[2]=o[2]+b*n[2],h}})(),rayPlaneIntersect:(()=>{const e=new l(3),t=new l(3),i=new l(3),s=new l(3);return(r,o,n,a,l,A)=>{A=A||d.vec3(),o=d.normalizeVec3(o,e);const h=d.subVec3(a,n,t),c=d.subVec3(l,n,i),u=d.cross3Vec3(h,c,s);d.normalizeVec3(u,u);const p=-d.dotVec3(n,u),f=-(d.dotVec3(r,u)+p)/d.dotVec3(o,u);return A[0]=r[0]+f*o[0],A[1]=r[1]+f*o[1],A[2]=r[2]+f*o[2],A}})(),cartesianToBarycentric:(()=>{const e=new l(3),t=new l(3),i=new l(3);return(s,r,o,n,a)=>{const l=d.subVec3(n,r,e),A=d.subVec3(o,r,t),h=d.subVec3(s,r,i),c=d.dotVec3(l,l),u=d.dotVec3(l,A),p=d.dotVec3(l,h),f=d.dotVec3(A,A),g=d.dotVec3(A,h),m=c*f-u*u;if(0===m)return null;const _=1/m,v=(f*p-u*g)*_,b=(c*g-u*p)*_;return a[0]=1-v-b,a[1]=b,a[2]=v,a}})(),barycentricInsideTriangle(e){const t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian(e,t,i,s,r=d.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+i[0]*n+s[0]*a,r[1]=t[1]*o+i[1]*n+s[1]*a,r[2]=t[2]*o+i[2]*n+s[2]*a,r},mergeVertices(e,t,i,s){const r={},o=[],n=[],a=t?[]:null,l=i?[]:null,A=[];let h,c,u,d;const p=1e4;let f,g,m=0;for(f=0,g=e.length;f{const e=new l(3),t=new l(3),i=new l(3),s=new l(3),r=new l(3),o=new l(3);return(n,a,l)=>{let A,h;const c=new Array(n.length/3);let u,p,f,g,m,_,v;for(A=0,h=a.length;A{const e=new l(3),t=new l(3),i=new l(3),s=new l(3),r=new l(3),o=new l(3),n=new l(3);return(a,l,A)=>{const h=new Float32Array(a.length);for(let c=0;c>24&255,h=u>>16&255,A=u>>8&255,l=255&u,a=t[i],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+1],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+2],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,i={}){const s=i.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,A,h,c;const u=1e4;let p,f,g,m,_,v;for(f=0,m=e.length;f{const e=new l(4),t=new l(4);return(i,s,r,o,n)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=1,d.transformVec4(i,e,t),o[0]=t[0],o[1]=t[1],o[2]=t[2],e[0]=r[0],e[1]=r[1],e[2]=r[2],d.transformVec3(i,e,t),d.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new l(16),t=new l(4),i=new l(4),s=(t,i,s,r,o)=>{o[0]=t,o[1]=i,o[2]=s,o[3]=1,d.transformVec4(e,o,o),r||d.mulVec4Scalar(o,1/o[3])};return(r,o,n,a,l,A,h)=>{const c="ortho"===a;d.mulMat4(n,o,e),d.inverseMat4(e,e);const u=2*l[0]/r.width-1,p=1-2*l[1]/r.height;s(u,p,-1,c,t),s(u,p,1,c,i),A[0]=t[0],A[1]=t[1],A[2]=t[2],d.subVec3(i,t,h),d.normalizeVec3(h)}})(),canvasPosToLocalRay:(()=>{const e=new l(3),t=new l(3);return(i,s,r,o,n,a,l,A)=>{d.canvasPosToWorldRay(i,s,r,o,a,e,t),d.worldRayToLocalRay(n,e,t,l,A)}})(),worldRayToLocalRay:(()=>{const e=new l(16),t=new l(4),i=new l(4);return(s,r,o,n,a)=>{const l=d.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,d.transformVec4(l,t,i),n[0]=i[0],n[1]=i[1],n[2]=i[2],d.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(i,s,r,o){const n=new l(6),a={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:n};let A,h;for(n[0]=n[1]=n[2]=Number.POSITIVE_INFINITY,n[3]=n[4]=n[5]=Number.NEGATIVE_INFINITY,A=0,h=i.length;An[3]&&(n[3]=r[t]),r[t+1]n[4]&&(n[4]=r[t+1]),r[t+2]n[5]&&(n[5]=r[t+2])}}if(i.length<20||o>10)return a.triangles=i,a.leaf=!0,a;e[0]=n[3]-n[0],e[1]=n[4]-n[1],e[2]=n[5]-n[2];let u=0;e[1]>e[u]&&(u=1),e[2]>e[u]&&(u=2),a.splitDim=u;const d=(n[u]+n[u+3])/2,p=new Array(i.length);let f=0;const g=new Array(i.length);let m=0;for(A=0,h=i.length;A{const s=e.length/3,r=new Array(s);for(let e=0;e=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=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t}};d.buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=d.vec3(),h=d.vec3(),c=d.vec3(),u=d.vec3(),p=d.vec3(),f=d.vec3(),g=d.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;ux)||(T=i[F.index1],R=i[F.index2],(!L&&T>65535||R>65535)&&(L=!0),y.push(T),y.push(R));return L?new Uint32Array(y):new Uint16Array(y)}}(),d.planeClipsPositions3=function(e,t,i,s=3){for(let r=0,o=i.length;r{this._needsRebuild=!0})),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",(e=>{this._needsRebuild=!0}))}get root(){return this._needsRebuild&&this._rebuild(),this._root}_rebuild(){const e=this.viewer.scene;this._root={aabb:e.getAABB()};for(let t in e.objects){const i=e.objects[t];this._insertEntity(this._root,i,1)}this._needsRebuild=!1}_insertEntity(e,t,i){const s=t.aabb;if(i>=this._maxTreeDepth)return e.entities=e.entities||[],void e.entities.push(t);if(e.left&&d.containsAABB3(e.left.aabb,s))return void this._insertEntity(e.left,t,i+1);if(e.right&&d.containsAABB3(e.right.aabb,s))return void this._insertEntity(e.right,t,i+1);const r=e.aabb;p[0]=r[3]-r[0],p[1]=r[4]-r[1],p[2]=r[5]-r[2];let o=0;if(p[1]>p[o]&&(o=1),p[2]>p[o]&&(o=2),!e.left){const n=r.slice();if(n[o+3]=(r[o]+r[o+3])/2,e.left={aabb:n},d.containsAABB3(n,s))return void this._insertEntity(e.left,t,i+1)}if(!e.right){const n=r.slice();if(n[o]=(r[o]+r[o+3])/2,e.right={aabb:n},d.containsAABB3(n,s))return void this._insertEntity(e.right,t,i+1)}e.entities=e.entities||[],e.entities.push(t)}destroy(){const e=this.viewer.scene;e.off(this._onModelLoaded),e.off(this._onModelUnloaded),this._root=null,this._needsRebuild=!0}}class g{constructor(){this._head=[],this._headLength=0,this._tail=[],this._index=0,this._length=0}get length(){return this._length}shift(){if(this._index>=this._headLength){const e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}const e=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,e}push(e){return this._length++,this._tail.push(e),this}unshift(e){return this._head[--this._index]=e,this._length++,this}}const m={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var _=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r{};t=t||s,i=i||s;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var s=e.target.response;if(200===this.status){var r;try{r=JSON.parse(s)}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}t(r)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(s))}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else i(e)}),!1),r.addEventListener("error",(function(e){i(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,i){var s=e=>{};t=t||s,i=i||s;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const e=!!r[2];var o=r[3];o=window.decodeURIComponent(o),e&&(o=window.atob(o));try{const e=new ArrayBuffer(o.length),i=new Uint8Array(e);for(var n=0;n{t(e)}))}catch(e){I.scheduleTask((()=>{i(e)}))}}else{const s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i("loadArrayBuffer error : "+s.response))},s.send(null)}},queryString:b,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"==typeof e&&"number"==typeof e.length},isString:function(e){return"string"==typeof e||e instanceof String},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},isID:function(e){return y.isString(e)||y.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(y.isNumeric(e)||y.isString(e)?`${e}`:e.id)===(y.isNumeric(t)||y.isString(t)?`${t}`:t.id)},isFunction:function(e){return"function"==typeof e},isObject:function(e){const t={}.constructor;return!!e&&e.constructor===t},copy:function(e){return y.apply(e,{})},apply:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t},apply2:function(e,t){for(const i in e)e.hasOwnProperty(i)&&void 0!==e[i]&&null!==e[i]&&(t[i]=e[i]);return t},applyIf:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(void 0!==t[i]&&null!==t[i]||(t[i]=e[i]));return t},isEmptyObject:function(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return y.isNumeric(e)?`${e}`:`'${e}'`},concat:function(e,t){const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},flattenParentChildHierarchy:function(e){var t=[];return function e(i){i.id=i.uuid,delete i.oid,t.push(i);var s=i.children;if(s)for(var r=0,o=s.length;r{B.removeItem(e.id),delete I.scenes[e.id],delete x[e.id],m.components.scenes--}))},this.clear=function(){let e;for(const t in I.scenes)I.scenes.hasOwnProperty(t)&&(e=I.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete I.scenes[e.id]))},this.scheduleTask=function(e,t=null){w.push(e),w.push(t)},this.runTasks=function(e=-1){let t,i,s=(new Date).getTime(),r=0;for(;w.length>0&&(e<0||s0&&M>0){var t=1e3/M;F+=t,C.push(t),C.length>=30&&(F-=C.shift()),m.frame.fps=Math.round(F/C.length)}for(let e in I.scenes)I.scenes[e].compile();T(e),E=e};!function(e,t){let i=Date.now()+t;(function s(){const r=Date.now()-i;e(),i+=t,setTimeout(s,Math.max(0,t-r))})()}((()=>{D()}),100);const S=function(){let e=Date.now();if(M=e-E,E>0&&M>0){var t=1e3/M;F+=t,C.push(t),C.length>=30&&(F-=C.shift()),m.frame.fps=Math.round(F/C.length)}T(e),function(e){for(var t in P.time=e,I.scenes)if(I.scenes.hasOwnProperty(t)){var i=I.scenes[t];P.sceneId=t,P.startTime=i.startTime,P.deltaTime=null!=P.prevTime?P.time-P.prevTime:0,i.fire("tick",P,!0)}P.prevTime=e}(e),function(){const e=I.scenes,t=!1;let i,s,r,o,n;for(n in e)e.hasOwnProperty(n)&&(i=e[n],s=x[n],s||(s=x[n]={}),r=i.ticksPerOcclusionTest,s.ticksPerOcclusionTest!==r&&(s.ticksPerOcclusionTest=r,s.renderCountdown=r),--i.occlusionTestCountdown<=0&&(i.doOcclusionTest(),i.occlusionTestCountdown=r),o=i.ticksPerRender,s.ticksPerRender!==o&&(s.ticksPerRender=o,s.renderCountdown=o),0==--s.renderCountdown&&(i.render(t),s.renderCountdown=o))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(D):requestAnimationFrame(S)};function T(e){const t=I.runTasks(e+10),i=I.getNumTasks();m.frame.tasksRun=t,m.frame.tasksScheduled=i,m.frame.tasksBudget=10}S();class R{get type(){return"Component"}get isComponent(){return!0}constructor(e=null,t={}){if(this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=t.viewer;else{if("Scene"===e.type)this.scene=e;else{if(!(e instanceof R))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+y.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let i=e.component;const s=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(i&&(y.isNumeric(i)||y.isString(i))){const e=i;if(i=this.scene.components[e],!i)return void this.error("Component not found: "+y.inQuotes(e))}if(!i)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){i=e[t];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&(i=this.scene[t],!i))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+y.inQuotes(i.id));if(o&&!i.isType(o))return void this.error("Expected a "+o+" type or subtype: "+i.type+" "+y.inQuotes(i.id))}this._attachments||(this._attachments={});const l=this._attached[t];let A,h,c;if(l){if(i&&l.id===i.id)return;const e=this._attachments[l.id];for(A=e.subs,h=0,c=A.length;h{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():I.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}scheduleTask(e){I.scheduleTask(e,null)}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,i,s,r,o;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(t=this._attachments[e],i=t.component,s=t.subs,r=0,o=s.length;r=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class N{constructor(){this.planes=[new k,new k,new k,new k,new k,new k]}}function Q(e,t,i){const s=d.mulMat4(i,t,O),r=s[0],o=s[1],n=s[2],a=s[3],l=s[4],A=s[5],h=s[6],c=s[7],u=s[8],p=s[9],f=s[10],g=s[11],m=s[12],_=s[13],v=s[14],b=s[15];e.planes[0].set(a-r,c-l,g-u,b-m),e.planes[1].set(a+r,c+l,g+u,b+m),e.planes[2].set(a-o,c-A,g-p,b-_),e.planes[3].set(a+o,c+A,g+p,b+_),e.planes[4].set(a-n,c-h,g-f,b-v),e.planes[5].set(a+n,c+h,g+f,b+v)}function V(e,t){let i=N.INSIDE;const s=L,r=U;s[0]=t[0],s[1]=t[1],s[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[s,r];for(let t=0;t<6;++t){const s=e.planes[t];if(s.normal[0]*o[s.testVertex[0]][0]+s.normal[1]*o[s.testVertex[1]][1]+s.normal[2]*o[s.testVertex[2]][2]+s.offset<0)return N.OUTSIDE;s.normal[0]*o[1-s.testVertex[0]][0]+s.normal[1]*o[1-s.testVertex[1]][1]+s.normal[2]*o[1-s.testVertex[2]][2]+s.offset<0&&(i=N.INTERSECT)}return i}N.INSIDE=0,N.INTERSECT=1,N.OUTSIDE=2;class H extends R{constructor(e={}){if(!e.viewer)throw"[MarqueePicker] Missing config: viewer";if(!e.objectsKdTree3)throw"[MarqueePicker] Missing config: objectsKdTree3";super(e.viewer.scene,e),this.viewer=e.viewer,this._objectsKdTree3=e.objectsKdTree3,this._canvasMarqueeCorner1=d.vec2(),this._canvasMarqueeCorner2=d.vec2(),this._canvasMarquee=d.AABB2(),this._marqueeFrustum=new N,this._marqueeFrustumProjMat=d.mat4(),this._pickMode=!1,this._marqueeElement=document.createElement("div"),document.body.appendChild(this._marqueeElement),this._marqueeElement.style.position="absolute",this._marqueeElement.style["z-index"]="40000005",this._marqueeElement.style.width="8px",this._marqueeElement.style.height="8px",this._marqueeElement.style.visibility="hidden",this._marqueeElement.style.top="0px",this._marqueeElement.style.left="0px",this._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",this._marqueeElement.style.opacity=1,this._marqueeElement.style["pointer-events"]="none"}setMarqueeCorner1(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarqueeCorner2(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarquee(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}setMarqueeVisible(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}getMarqueeVisible(){return this._marqueVisible}setPickMode(e){if(e!==H.PICK_MODE_INSIDE&&e!==H.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===H.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}getPickMode(){return this._pickMode}clear(){this.fire("clear",{})}pick(){this._updateMarquee(),this._buildMarqueeFrustum();const e=[],t=(i,s=N.INTERSECT)=>{if(s===N.INTERSECT&&(s=V(this._marqueeFrustum,i.aabb)),s!==N.OUTSIDE){if(i.entities){const t=i.entities;for(let i=0,s=t.length;i3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&t(this._objectsKdTree3.root),this.fire("picked",e),e}_updateMarquee(){this._canvasMarquee[0]=Math.min(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[1]=Math.min(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._canvasMarquee[2]=Math.max(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[3]=Math.max(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._marqueeElement.style.width=this._canvasMarquee[2]-this._canvasMarquee[0]+"px",this._marqueeElement.style.height=this._canvasMarquee[3]-this._canvasMarquee[1]+"px",this._marqueeElement.style.left=`${this._canvasMarquee[0]}px`,this._marqueeElement.style.top=`${this._canvasMarquee[1]}px`}_buildMarqueeFrustum(){const e=this.viewer.scene.canvas.canvas,t=e.clientWidth,i=e.clientHeight,s=e.clientLeft,r=e.clientTop,o=2/t,n=2/i,a=e.clientHeight/e.clientWidth,l=(this._canvasMarquee[0]-s)*o-1,A=(this._canvasMarquee[2]-s)*o-1,h=-(this._canvasMarquee[3]-r)*n+1,c=-(this._canvasMarquee[1]-r)*n+1,u=this.viewer.scene.camera.frustum.near*(17*a);d.frustumMat4(l,A,h*a,c*a,u,1e4,this._marqueeFrustumProjMat),Q(this._marqueeFrustum,this.viewer.scene.camera.viewMatrix,this._marqueeFrustumProjMat)}destroy(){super.destroy(),this._marqueeElement.parentElement&&(this._marqueeElement.parentElement.removeChild(this._marqueeElement),this._marqueeElement=null,this._objectsKdTree3=null)}}H.PICK_MODE_INTERSECTS=0,H.PICK_MODE_INSIDE=1;class j extends R{constructor(e){super(e.marqueePicker,e);const t=e.marqueePicker,i=t.viewer.scene.canvas.canvas;let s,r,o,n,a,l,A,h=!1,c=!1,u=!1;i.addEventListener("mousedown",(e=>{this.getActive()&&0===e.button&&(A=setTimeout((function(){const o=t.viewer.scene.input;o.keyDown[o.KEY_CTRL]||t.clear(),s=e.pageX,r=e.pageY,a=e.offsetX,t.setMarqueeCorner1([s,r]),h=!0,t.viewer.cameraControl.pointerEnabled=!1,t.setMarqueeVisible(!0),i.style.cursor="crosshair"}),400),c=!0)})),i.addEventListener("mouseup",(e=>{if(!this.getActive())return;if(!h&&!u)return;if(0!==e.button)return;clearTimeout(A),o=e.pageX,n=e.pageY;const i=Math.abs(o-s),a=Math.abs(n-r);h=!1,t.viewer.cameraControl.pointerEnabled=!0,u&&(u=!1),(i>3||a>3)&&t.pick()})),document.addEventListener("mouseup",(e=>{this.getActive()&&0===e.button&&(clearTimeout(A),h&&(t.setMarqueeVisible(!1),h=!1,c=!1,u=!0,t.viewer.cameraControl.pointerEnabled=!0))}),!0),i.addEventListener("mousemove",(e=>{this.getActive()&&0===e.button&&c&&(clearTimeout(A),h&&(o=e.pageX,n=e.pageY,l=e.offsetX,t.setMarqueeVisible(!0),t.setMarqueeCorner2([o,n]),t.setPickMode(a{if(!this._running)return;i||(i=e);const r=e-i,o=Math.min(r/300,1),n=t+(2-t)*o;this._circleRadius=n,this._circleDiv.style.width=`${this._circleRadius}px`,this._circleDiv.style.height=`${this._circleRadius}px`,this._circleDiv.style.marginLeft=this._circlePos[0]-this._circleRadius/2+"px",this._circleDiv.style.marginTop=this._circlePos[1]-this._circleRadius/2+"px",o<1&&requestAnimationFrame(s)};this._running=!0,requestAnimationFrame(s),this._circleDiv.style.visibility="visible"}stop(){this._destroyed||(this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius=`${this._circleRadius}px`,this._circleDiv.style.visibility="hidden")}set durationMs(e){this.stop(),this._durationMs=e}get durationMs(){return this._durationMs}destroy(){this._destroyed||(this.stop(),this._circleDiv.parentElement.removeChild(this._circleDiv),this._destroyed=!0)}}class z{constructor(e,t,i){this.id=i&&i.id?i.id:e,this.viewer=t,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,t.addPlugin(this)}scheduleTask(e){I.scheduleTask(e,null)}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}const W={isIphoneSafari(){const e=window.navigator.userAgent,t=/iPhone/i.test(e),i=/Safari/i.test(e)&&!/Chrome/i.test(e);return t&&i}};class K{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!1!==t.visible,this._culled=!1;var i=this._dot,s=i.style;s["border-radius"]="25px",s.border="solid 2px white",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,s.width="8px",s.height="8px",s.visibility=this._visible?"visible":"hidden",s.top="0px",s.left="0px",s["box-shadow"]="0 2px 5px 0 #182A3D;",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._dotClickable,o=r.style;o["border-radius"]="35px",o.border="solid 10px white",o.position="absolute",o["z-index"]=void 0===t.zIndex?"40000007":t.zIndex+1,o.width="8px",o.height="8px",o.visibility="visible",o.top="0px",o.left="0px",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),r.addEventListener("click",(t=>{e.dispatchEvent(new MouseEvent("mouseover",t))})),t.onMouseOver&&r.addEventListener("mouseover",(i=>{t.onMouseOver(i,this),e.dispatchEvent(new MouseEvent("mouseover",i))})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onTouchstart&&r.addEventListener("touchstart",(e=>{t.onTouchstart(e,this)})),t.onTouchmove&&r.addEventListener("touchmove",(e=>{t.onTouchmove(e,this)})),t.onTouchend&&r.addEventListener("touchend",(e=>{t.onTouchend(e,this)})),t.onContextMenu&&(W.isIphoneSafari()?(r.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),r.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):r.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")}))),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.borderColor)}setPos(e,t){this._x=e,this._y=t;var i=this._dot.style;i.left=Math.round(e)-4+"px",i.top=Math.round(t)-4+"px";var s=this._dotClickable.style;s.left=Math.round(e)-9+"px",s.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}const X=d.vec3(),J=function(){const e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,o){return o=o||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,d.transformVec4(s,t,i),d.setMat4Translation(s,i,o),o.slice()}}();function Y(e,t,i){const s=Float32Array.from([e[0]])[0],r=e[0]-s,o=Float32Array.from([e[1]])[0],n=e[1]-o,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=s,t[1]=o,t[2]=a,i[0]=r,i[1]=n,i[2]=l}function Z(e,t,i,s=1e3){const r=d.getPositionsCenter(e,X),o=Math.round(r[0]/s)*s,n=Math.round(r[1]/s)*s,a=Math.round(r[2]/s)*s;i[0]=o,i[1]=n,i[2]=a;const l=0!==i[0]||0!==i[1]||0!==i[2];if(l)for(let i=0,s=e.length;i0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,i=this.meshes[0]._colorize[3];let s=255;if(t){if(e<0?e=0:e>1&&(e=1),s=Math.floor(255*e),i===s)return}else if(s=255,i===s)return;for(let e=0,t=this.meshes.length;e=0&&(e+=i)}return e>0?e:-1}_getFlag(e){return!!(this._flags&e)}_finalize(){const e=this.model.scene;this._isObject&&(this.visible&&e._objectVisibilityUpdated(this),this.highlighted&&e._objectHighlightedUpdated(this),this.xrayed&&e._objectXRayedUpdated(this),this.selected&&e._objectSelectedUpdated(this));for(let e=0,t=this.meshes.length;e{this._viewPosDirty=!0,this._needUpdate()})),this._onCameraProjMatrix=this.scene.camera.on("projMatrix",(()=>{this._canvasPosDirty=!0,this._needUpdate()})),this._onEntityDestroyed=null,this._onEntityModelDestroyed=null,this._renderer.addMarker(this),this.entity=t.entity,this.worldPos=t.worldPos,this.occludable=t.occludable}_update(){if(this._viewPosDirty&&(d.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){ue.set(this._viewPos),ue[3]=1,d.transformPoint4(this.scene.camera.projMatrix,ue,de);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+de[0]/de[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-de[1]/de[3])*e[3]/2),this._canvasPosDirty=!1,this.fire("canvasPos",this._canvasPos)}}_setVisible(e){this._visible,this._visible=e,this.fire("visible",this._visible)}set entity(e){if(this._entity){if(this._entity===e)return;null!==this._onEntityDestroyed&&(this._entity.model?this._entity.model.off(this._onEntityDestroyed):this._entity.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model&&this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null)}this._entity=e,this._entity&&(this._entity instanceof ce?this._onEntityModelDestroyed=this._entity.model.on("destroyed",(()=>{this._entity=null,this._onEntityModelDestroyed=null})):this._onEntityDestroyed=this._entity.on("destroyed",(()=>{this._entity=null,this._onEntityDestroyed=null}))),this.fire("entity",this._entity,!0)}get entity(){return this._entity}set occludable(e){(e=!!e)!==this._occludable&&(this._occludable=e,this._occludable&&this._renderer.markerWorldPosUpdated(this))}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),Y(this._worldPos,this._origin,this._rtcPos),this._occludable&&this._renderer.markerWorldPosUpdated(this),this._viewPosDirty=!0,this.fire("worldPos",this._worldPos),this._needUpdate()}get worldPos(){return this._worldPos}get origin(){return this._origin}get rtcPos(){return this._rtcPos}get viewPos(){return this._update(),this._viewPos}get canvasPos(){return this._update(),this._canvasPos}get visible(){return!!this._visible}destroy(){this.fire("destroyed",!0),this.scene.camera.off(this._onCameraViewMatrix),this.scene.camera.off(this._onCameraProjMatrix),this._entity&&(null!==this._onEntityDestroyed&&this._entity.model.off(this._onEntityDestroyed),null!==this._onEntityModelDestroyed&&this._entity.model.off(this._onEntityModelDestroyed)),this._renderer.removeMarker(this),super.destroy()}}const fe=()=>{};function ge(e,t,i){const s=e.getBoundingClientRect(),r=t.getBoundingClientRect();i[0]+=s.left-r.left,i[1]+=s.top-r.top}class me extends pe{constructor(e,t,i,s={}){super(e,t);const r=(e,t)=>i=>{e&&e(i),this.fire(t,i,!0)};this._dot=new K(i,{fillColor:s.fillColor,zIndex:s.zIndex,onMouseOver:r(s.onMouseOver,"mouseover"),onMouseLeave:r(s.onMouseLeave,"mouseleave"),onMouseWheel:r(s.onMouseWheel,"wheel"),onMouseDown:r(s.onMouseDown,"mousedown"),onMouseUp:r(s.onMouseUp,"mouseup"),onMouseMove:r(s.onMouseMove,"mousemove"),onTouchstart:r(s.onTouchstart,"touchstart"),onTouchmove:r(s.onTouchmove,"touchmove"),onTouchend:r(s.onTouchend,"touchend"),onContextMenu:r(s.onContextMenu,"contextmenu")});const o=()=>{const t=this.canvasPos.slice();ge(e.canvas.canvas,i,t),this._dot.setPos(t[0],t[1])};this.on("worldPos",o);const n=e.camera.on("viewMatrix",o),a=e.camera.on("projMatrix",o);this._cleanup=()=>{e.camera.off(n),e.camera.off(a),this._dot.destroy()}}setClickable(e){this._dot.setClickable(e)}setCulled(e){this._dot.setCulled(e)}setFillColor(e){this._dot.setFillColor(e)}setHighlighted(e){this._dot.setHighlighted(e)}setOpacity(e){this._dot.setOpacity(e)}setVisible(e){this._dot.setVisible(e)}destroy(){this._cleanup(),super.destroy()}}function _e(e,t){const i=function(e,i){if(e in t)return t[e];if(void 0!==i)return i;throw"config missing: "+e},s=i("viewer"),r=i("ray2WorldPos"),o=i("handleMouseEvents",!1),n=i("handleTouchEvents",!1),a=i("onStart",fe),l=i("onMove",fe),A=i("onEnd",fe),h=s.scene,c=h.canvas.canvas,u=e=>{const t=d.vec2([e.clientX,e.clientY]);ge(c.ownerDocument.documentElement,c,t),l(t,(e=>{const t=d.vec3(),i=d.vec3();return d.canvasPosToWorldRay(c,h.camera.viewMatrix,h.camera.projMatrix,h.camera.projection,e,t,i),r(t,i,e)})(t))};let p=null;const f=function(e){const t=p.matchesEvent(e);t&&u(t)},g=function(t){const i=p.matchesEvent(t);i&&(e.setOpacity(b),p.cleanup(),u(i),A())},m=function(t,i){p&&p.cleanup(),e.setOpacity(1),e.setClickable(!1),s.cameraControl.active=!1,p={matchesEvent:t,cleanup:function(){p=null,e.setClickable(!0),s.cameraControl.active=!0,i()}},a()},_=[],v=function(t,i){const s=e.on(t,i);_.push((()=>e.off(s)))};if(o&&(v("mouseover",(()=>!p&&e.setOpacity(1))),v("mouseleave",(()=>!p&&e.setOpacity(b))),v("mousedown",(e=>{1===e.which&&(c.addEventListener("mousemove",f),c.addEventListener("mouseup",g),m((e=>1===e.which&&e),(()=>{c.removeEventListener("mousemove",f),c.removeEventListener("mouseup",g)})))}))),n){let e;v("touchstart",(t=>{t.preventDefault(),1===t.touches.length&&(e=t.touches[0].identifier,m((t=>[...t.changedTouches].find((t=>t.identifier===e))),(()=>{e=null})))})),v("touchmove",(e=>{e.preventDefault(),f(e)})),v("touchend",(e=>{e.preventDefault(),g(e)}))}const b=.8;return e.setOpacity(b),function(){p&&p.cleanup(),_.forEach((e=>e())),e.setOpacity(1)}}function ve(e){const t=function(t,i){if(t in e)return e[t];if(void 0!==i)return i;throw"config missing: "+t},i=t("viewer"),s=t("handleMouseEvents",!1),r=t("handleTouchEvents",!1),o=t("pointerLens",null),n=t("dots"),a=t("ray2WorldPos"),l=t("onEnd",fe),A=o?function(e){o.visible=!!e,e&&(o.canvasPos=e)}:()=>{},h=n.map((e=>{let t;return _e(e,{handleMouseEvents:s,handleTouchEvents:r,viewer:i,ray2WorldPos:(e,i,s)=>a(e,i,s)||t,onStart:()=>{t=e.worldPos.slice(),c(!1,e)},onMove:(t,i)=>{A(t),e.worldPos=i},onEnd:()=>{l(t,e)||(e.worldPos=t),A(null),c(!0,e)}})})),c=(e,t)=>n.forEach((i=>i!==t&&i.setClickable(e)));return c(!0),function(){h.forEach((e=>e())),A(null)}}const be=function(e,t,i){return function(s,r,o){const n=e.scene,a=n.canvas.canvas,l=(e,t)=>(t[0]=e.clientX,t[1]=e.clientY,ge(a.ownerDocument.documentElement,a,t),t),A=e=>{const t=d.vec3(),s=d.vec3();return d.canvasPosToWorldRay(a,n.camera.viewMatrix,n.camera.projMatrix,n.camera.projection,e,t,s),i(t,s)};let h=null;const c=()=>{};let u,p=c;const f=function(){t.stop(),clearTimeout(h),e.cameraControl.active=!0,p=c,u=null},g=function(){f(),a.removeEventListener("touchstart",m),a.removeEventListener("touchmove",_),a.removeEventListener("touchend",v)},m=function(i){const o=i.touches;if(1!==o.length)f(),s();else{const i=o[0],s=l(i,d.vec2());A(s)&&(u=i.identifier,p=e=>{d.distVec2(s,e)>20&&f()},h=setTimeout((function(){t.start(s),h=setTimeout((function(){t.stop(),e.cameraControl.active=!1,p=e=>{r(e,A(e))},p(s)}),300)}),250))}};a.addEventListener("touchstart",m,{passive:!0});const _=function(e){const t=[...e.changedTouches].find((e=>e.identifier===u));t&&p(l(t,d.vec2()))};a.addEventListener("touchmove",_,{passive:!0});const v=function(e){const t=[...e.changedTouches].find((e=>e.identifier===u));if(t){g();const e=l(t,d.vec2());o(e,A(e))}};return a.addEventListener("touchend",v,{passive:!0}),g}};class ye{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6,this._visible=!0,this._culled=!1;var i=this._wire,s=i.style;s.border="solid "+this._thickness+"px "+this._color,s.position="absolute",s["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,s.width="0px",s.height="0px",s.visibility="visible",s.top="0px",s.left="0px",s["-webkit-transform-origin"]="0 0",s["-moz-transform-origin"]="0 0",s["-ms-transform-origin"]="0 0",s["-o-transform-origin"]="0 0",s["transform-origin"]="0 0",s["-webkit-transform"]="rotate(0deg)",s["-moz-transform"]="rotate(0deg)",s["-ms-transform"]="rotate(0deg)",s["-o-transform"]="rotate(0deg)",s.transform="rotate(0deg)",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._wireClickable,o=r.style;o.border="solid "+this._thicknessClickable+"px "+this._color,o.position="absolute",o["z-index"]=void 0===t.zIndex?"2000002":t.zIndex+1,o.width="0px",o.height="0px",o.visibility="visible",o.top="0px",o.left="0px",o["-webkit-transform-origin"]="0 0",o["-moz-transform-origin"]="0 0",o["-ms-transform-origin"]="0 0",o["-o-transform-origin"]="0 0",o["transform-origin"]="0 0",o["-webkit-transform"]="rotate(0deg)",o["-moz-transform"]="rotate(0deg)",o["-ms-transform"]="rotate(0deg)",o["-o-transform"]="rotate(0deg)",o.transform="rotate(0deg)",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),t.onMouseOver&&r.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&(W.isIphoneSafari()?(r.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),r.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):r.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")}))),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}get visible(){return"visible"===this._wire.style.visibility}_update(){var e=Math.abs(Math.sqrt((this._x1-this._x2)*(this._x1-this._x2)+(this._y1-this._y2)*(this._y1-this._y2))),t=180*Math.atan2(this._y2-this._y1,this._x2-this._x1)/Math.PI,i=this._wire.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)";var s=this._wireClickable.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)"}setStartAndEnd(e,t,i,s){this._x1=e,this._y1=t,this._x2=i,this._y2=s,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class xe{constructor(e,t={}){this._highlightClass="viewer-ruler-label-highlighted",this._prefix=t.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label",this._timeout=null;var i=this._label,s=i.style;s["border-radius"]="5px",s.color="white",s.padding="4px",s.border="solid 1px",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,s.width="auto",s.height="auto",s.visibility="visible",s.top="0px",s.left="0px",s["pointer-events"]="all",s.opacity=1,t.onContextMenu,i.innerText="",e.appendChild(i),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&i.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&i.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&i.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&i.addEventListener("mousedown",(e=>{t.onMouseDown(e,this),e.stopPropagation()})),t.onMouseUp&&i.addEventListener("mouseup",(e=>{t.onMouseUp(e,this),e.stopPropagation()})),t.onMouseMove&&i.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&(W.isIphoneSafari()?(i.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),i.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):i.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")})))}setPos(e,t){this._x=e,this._y=t;var i=this._label.style;i.left=Math.round(e)-20+"px",i.top=Math.round(t)-12+"px"}setPosOnWire(e,t,i,s){var r=e+.5*(i-e),o=t+.5*(s-t),n=this._label.style;n.left=Math.round(r)-20+"px",n.top=Math.round(o)-12+"px"}setPosBetweenWires(e,t,i,s,r,o){var n=(e+i+r)/3,a=(t+s+o)/3,l=this._label.style;l.left=Math.round(n)-20+"px",l.top=Math.round(a)-12+"px"}setText(e){this._label.innerHTML=this._prefix+(e||"")}setFillColor(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}setBorderColor(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}setOpacity(e){this._label.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}setClickable(e){this._label.style["pointer-events"]=e?"all":"none"}setPrefix(e){this._prefix!==e&&(this._prefix=e)}destroy(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}var Be=d.vec3(),we=d.vec3();class Pe extends R{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._color=t.color||e.defaultColor;var i=this.plugin.viewer.scene;this._originWorld=d.vec3(),this._cornerWorld=d.vec3(),this._targetWorld=d.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},l=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))};this._originDot=new me(i,t.origin,this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._cornerDot=new me(i,t.corner,this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetDot=new me(i,t.target,this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._originWire=new ye(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetWire=new ye(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._angleLabel=new xe(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._cornerVisible=!1,this._targetVisible=!1,this._originWireVisible=!1,this._targetWireVisible=!1,this._angleVisible=!1,this._labelsVisible=!1,this._clickable=!1,this._originDot.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._cornerDot.on("worldPos",(e=>{this._cornerWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetDot.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(d.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){const u=-.3,p=this._originDot.viewPos[2],f=this._cornerDot.viewPos[2],g=this._targetDot.viewPos[2];if(p>u||f>u||g>u)return this._originDot.setVisible(!1),this._cornerDot.setVisible(!1),this._targetDot.setVisible(!1),this._originWire.setVisible(!1),this._targetWire.setVisible(!1),void this._angleLabel.setCulled(!0);d.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,i=this._cp,s=e.canvas.canvas.getBoundingClientRect();const m=this._container.getBoundingClientRect();for(var r=s.top-m.top,o=s.left-m.left,n=e.canvas.boundary,a=n[2],l=n[3],A=0,h=0,c=t.length;he.offsetTop+(e.offsetParent&&e.offsetParent!==t.parentNode&&h(e.offsetParent)),c=e=>e.offsetLeft+(e.offsetParent&&e.offsetParent!==t.parentNode&&c(e.offsetParent)),u=d.vec2(),p=e=>{e.snappedToVertex||e.snappedToEdge?(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.canvasPos,s.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red");const i=e.snappedCanvasPos||e.canvasPos;switch(r=!0,o=e.entity,l.set(e.worldPos),A.set(i),this._mouseState){case 0:this._canvasToPagePos?(this._canvasToPagePos(t,i,u),this.markerDiv.style.left=u[0]-5+"px",this.markerDiv.style.top=u[1]-5+"px"):(this.markerDiv.style.left=c(t)+i[0]-5+"px",this.markerDiv.style.top=h(t)+i[1]-5+"px");break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos,this._currentAngleMeasurement.corner.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos,this._currentAngleMeasurement.target.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer"}};this._onHoverSnapOrSurface=i.on("hoverSnapOrSurface",(e=>{this._snapping&&p(e)})),this._onHoverSurface=i.on("hoverSurface",(e=>{this._snapping||p(e)})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(n=e.clientX,a=e.clientY)}),t.addEventListener("mouseup",this._onMouseUp=e=>{if(1===e.which&&!(e.clientX>n+20||e.clientXa+20||e.clientY{if(r=!1,s&&(s.visible=!0,s.pointerPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!1),this.markerDiv.style.left="-100px",this.markerDiv.style.top="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}};this._onHoverSnapOrSurfaceOff=i.on("hoverSnapOrSurfaceOff",(e=>{this._snapping&&f(e)})),this._onHoverOff=i.on("hoverOff",(e=>{this._snapping||f(e)})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onHoverSnapOrSurface),t.off(this._onHoverSurface),t.off(this._onHoverSnapOrSurfaceOff),t.off(this._onHoverOff),this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}get currentMeasurement(){return this._currentAngleMeasurement}destroy(){this.deactivate(),super.destroy()}}class Ee extends z{constructor(e,t={}){super("AngleMeasurements",e),this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.zIndex=t.zIndex||1e4,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,angleMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get control(){return this._defaultControl||(this._defaultControl=new Me(this,{})),this._defaultControl}get measurements(){return this._measurements}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,i=e.corner,s=e.target,r=new Pe(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},corner:{entity:i.entity,worldPos:i.worldPos},target:{entity:s.entity,worldPos:s.worldPos},visible:e.visible,originVisible:!0,originWireVisible:!0,cornerVisible:!0,targetWireVisible:!0,targetVisible:!0,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[r.id]=r,r.on("destroyed",(()=>{delete this._measurements[r.id]})),r.clickable=!0,this.fire("measurementCreated",r),r}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("AngleMeasurement not found: "+e)}setLabelsShown(e){for(const[t,i]of Object.entries(this.measurements))i.labelShown=e}clear(){const e=Object.keys(this._measurements);for(var t=0,i=e.length;t{this.plugin.viewer.cameraControl.active=!1},c=()=>{this.plugin.viewer.cameraControl.active=!0},u=()=>{o&&(clearTimeout(o),o=null),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),c(),this._touchState=0};i.addEventListener("touchstart",this._onCanvasTouchStart=i=>{const l=i.touches.length;if(1!==l)return void(o&&(clearTimeout(o),o=null));const c=i.touches[0],p=c.clientX,f=c.clientY;switch(n.set([p,f]),a.set([p,f]),this._touchState){case 0:if(1!==l&&null!==o)return void u();const i=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping});if(i&&i.snapped)s.set(i.worldPos),this.pointerCircle.start(i.snappedCanvasPos);else{const e=t.pick({canvasPos:a,pickSurface:!0});if(!e||!e.worldPos)return;s.set(e.worldPos),this.pointerCircle.start(e.canvasPos)}o=setTimeout((()=>{1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{if(o=null,1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{if(o=null,1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{this.pointerCircle.stop();const i=e.touches.length;if(1!==i||1!==e.changedTouches.length)return void(o&&(clearTimeout(o),o=null));const r=e.touches[0],n=r.clientX,l=r.clientY;if(r.identifier!==A)return;let h,c;switch(a.set([n,l]),this._touchState){case 2:this.pointerLens&&(this.pointerLens.canvasPos=a),h=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),h&&h.snapped?(this.pointerLens&&(this.pointerLens.snappedCanvasPos=h.snappedCanvasPos,this.pointerLens.snapped=!0),s.set(h.worldPos),this._currentAngleMeasurement.origin.worldPos=h.worldPos):(c=t.pick({canvasPos:a,pickSurface:!0}),c&&c.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=c.canvasPos,this.pointerLens.snapped=!1),s.set(c.worldPos),this._currentAngleMeasurement.origin.worldPos=c.worldPos):this.pointerLens&&(this.pointerLens.cursorPos=null,this.pointerLens.snapped=!1)),this._touchState=2;break;case 5:if(1!==i&&null!==o)return clearTimeout(o),o=null,this.pointerLens&&(this.pointerLens.visible=!1),void(this._touchState=7);this.pointerLens&&(this.pointerLens.canvasPos=a),h=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),h&&h.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=h.snappedCanvasPos,this.pointerLens.snapped=!0),this._currentAngleMeasurement.corner.worldPos=h.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1):(c=t.pick({canvasPos:a,pickSurface:!0}),c&&c.worldPos&&(this.pointerLens&&(this.pointerLens.cursorPos=c.canvasPos,this.pointerLens.snapped=!1),this._currentAngleMeasurement.corner.worldPos=c.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1)),this._touchState=5;break;case 8:if(1!==i&&null!==o)return clearTimeout(o),o=null,this.pointerLens&&(this.pointerLens.visible=!1),void(this._touchState=7);this.pointerLens&&(this.pointerLens.canvasPos=a),h=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),h&&h.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=h.snappedCanvasPos,this.pointerLens.snapped=!0),this._currentAngleMeasurement.target.worldPos=h.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.angleVisible=!0):(c=t.pick({canvasPos:a,pickSurface:!0}),c&&c.worldPos&&(this.pointerLens&&(this.pointerLens.cursorPos=c.canvasPos,this.pointerLens.snapped=!1),this._currentAngleMeasurement.target.worldPos=c.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.angleVisible=!0)),this._touchState=8}}),{passive:!0}),i.addEventListener("touchend",this._onCanvasTouchEnd=i=>{this.pointerCircle.stop();const s=i.changedTouches.length;if(1!==s)return;const h=i.changedTouches[0],u=h.clientX,p=h.clientY;if(h.identifier===A)switch(o&&(clearTimeout(o),o=null),l.set([u,p]),this._touchState){case 1:{if(1!==s||u>n[0]+r||un[1]+r||pn[0]+r||un[1]+r||pn[0]+r||un[1]+r||p{const o=e=>{const t=r.scene.pick({canvasPos:s,snapToEdge:e,snapToVertex:e,pickSurface:!0});return t&&t.worldPos?t.worldPos:e&&o(!1)};return o(!!t.snapping)},onEnd:(e,t)=>{const i=!d.compareVec3(e,t.worldPos);return i&&this.fire("edited"),i}}),n=e.on("destroyed",o);this._deactivate=function(){e.off("destroyed",n),o()}}deactivate(){this._deactivate(),super.destroy()}}class De extends Ie{constructor(e,t){super(e,t,!0,!1)}}class Se extends Ie{constructor(e,t){super(e,t,!1,!0)}}const Te=d.vec3(),Re=d.vec3(),Le=d.vec3();class Ue extends pe{constructor(e,t){if(super(e,t),this.plugin=t.plugin,this._container=t.container,!this._container)throw"config missing: container";if(!t.markerElement&&!t.markerHTML)throw"config missing: need either markerElement or markerHTML";if(!t.labelElement&&!t.labelHTML)throw"config missing: need either labelElement or labelHTML";this._htmlDirty=!1,t.markerElement?(this._marker=t.markerElement,this._marker.addEventListener("click",this._onMouseClickedExternalMarker=()=>{this.plugin.fire("markerClicked",this)}),this._marker.addEventListener("contextmenu",this._onContextMenuExtenalMarker=()=>{this.plugin.fire("contextmenu",this)}),this._marker.addEventListener("mouseenter",this._onMouseEnterExternalMarker=()=>{this.plugin.fire("markerMouseEnter",this)}),this._marker.addEventListener("mouseleave",this._onMouseLeaveExternalMarker=()=>{this.plugin.fire("markerMouseLeave",this)}),this._markerExternal=!0):(this._markerHTML=t.markerHTML,this._htmlDirty=!0,this._markerExternal=!1),t.labelElement?(this._label=t.labelElement,this._labelExternal=!0):(this._labelHTML=t.labelHTML,this._htmlDirty=!0,this._labelExternal=!1),this._markerShown=!!t.markerShown,this._labelShown=!!t.labelShown,this._values=t.values||{},this._layoutDirty=!0,this._visibilityDirty=!0,this._labelPosition=24,this._buildHTML(),this._onTick=this.scene.on("tick",(()=>{this._htmlDirty&&(this._buildHTML(),this._htmlDirty=!1,this._layoutDirty=!0,this._visibilityDirty=!0),(this._layoutDirty||this._visibilityDirty)&&(this._markerShown||this._labelShown)&&(this._updatePosition(),this._layoutDirty=!1),this._visibilityDirty&&(this._marker.style.visibility=this.visible&&this._markerShown?"visible":"hidden",this._label.style.visibility=this.visible&&this._markerShown&&this._labelShown?"visible":"hidden",this._visibilityDirty=!1)})),this.on("canvasPos",(()=>{this._layoutDirty=!0})),this.on("visible",(()=>{this._visibilityDirty=!0})),this.setMarkerShown(!1!==t.markerShown),this.setLabelShown(t.labelShown),this.eye=t.eye?t.eye.slice():null,this.look=t.look?t.look.slice():null,this.up=t.up?t.up.slice():null,this.projection=t.projection}_buildHTML(){if(!this._markerExternal){this._marker&&(this._container.removeChild(this._marker),this._marker=null);let e=this._markerHTML||"

";y.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e.trim());const t=document.createRange().createContextualFragment(e);this._marker=t.firstChild,this._container.appendChild(this._marker),this._marker.style.visibility=this._markerShown?"visible":"hidden",this._marker.addEventListener("click",(()=>{this.plugin.fire("markerClicked",this)})),this._marker.addEventListener("contextmenu",(e=>{e.preventDefault(),this.plugin.fire("contextmenu",this)})),this._marker.addEventListener("mouseenter",(()=>{this.plugin.fire("markerMouseEnter",this)})),this._marker.addEventListener("mouseleave",(()=>{this.plugin.fire("markerMouseLeave",this)})),this._marker.addEventListener("wheel",(e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))}))}if(!this._labelExternal){this._label&&(this._container.removeChild(this._label),this._label=null);let e=this._labelHTML||"

";y.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e.trim());const t=document.createRange().createContextualFragment(e);this._label=t.firstChild,this._container.appendChild(this._label),this._label.style.visibility=this._markerShown&&this._labelShown?"visible":"hidden",this._label.addEventListener("wheel",(e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))}))}}_updatePosition(){const e=e=>e+"px",t=this.scene.canvas.boundary,i=t[0]+this.canvasPos[0],s=t[1]+this.canvasPos[1],r=this._marker.getBoundingClientRect().width,o=i+("right"===this._markerAlign?-1:"center"===this._markerAlign?0:1)*(r/2-12);this._marker.style.left=e(o-r/2),this._marker.style.top=e(s-12),this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;const n=this._label.getBoundingClientRect().width,a=Math.sign(this._labelPosition);this._label.style.left=e(o+a*(r/2+Math.abs(this._labelPosition)+n/2)-n/2),this._label.style.top=e(s-17),this._label.style["z-index"]=90005+Math.floor(this._viewPos[2])+1}_renderTemplate(e){for(var t in this._values)if(this._values.hasOwnProperty(t)){const i=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),i)}return e}setFromPickResult(e){if(e.worldPos&&e.worldNormal){const t=d.normalizeVec3(e.worldNormal,Te),i=this.plugin&&this.plugin.surfaceOffset||0,s=d.mulVec3Scalar(t,i,Re),r=d.addVec3(e.worldPos,s,Le);this.entity=e.entity,this.worldPos=r}else this.error("Param 'pickResult' does not have both worldPos and worldNormal")}setMarkerAlign(e){const t=["left","center","right"];t.includes(e)?(this._markerAlign=e,this._updatePosition()):this.error("Param 'align' should be one of: "+JSON.stringify(t))}setLabelPosition(e){"number"!=typeof e?this.error("Param 'position' is not a number"):0===e?this.error("Param 'position' is zero"):(this._labelPosition=e,this._updatePosition())}setMarkerShown(e){e=!!e,this._markerShown!==e&&(this._markerShown=e,this._visibilityDirty=!0)}getMarkerShown(){return this._markerShown}setLabelShown(e){e=!!e,this._labelShown!==e&&(this._labelShown=e,this._visibilityDirty=!0)}getLabelShown(){return this._labelShown}setField(e,t){this._values[e]=t||"",this._htmlDirty=!0}getField(e){return this._values[e]}setValues(e){for(var t in e)if(e.hasOwnProperty(t)){const i=e[t];this.setField(t,i)}}getValues(){return this._values}destroy(){this._marker&&(this._markerExternal?(this._marker.removeEventListener("click",this._onMouseClickedExternalMarker),this._marker.removeEventListener("contextmenu",this._onContextMenuExtenalMarker),this._marker.removeEventListener("mouseenter",this._onMouseEnterExternalMarker),this._marker.removeEventListener("mouseleave",this._onMouseLeaveExternalMarker),this._marker=null):(this._marker.parentNode.removeChild(this._marker),this._marker=null)),this._label&&(this._labelExternal||this._label.parentNode.removeChild(this._label),this._label=null),this.scene.off(this._onTick),super.destroy()}}class Oe extends z{constructor(e,t){super("Annotations",e),this._labelHTML=t.labelHTML||"
",this._markerHTML=t.markerHTML||"
",this._container=t.container||document.body,this._values=t.values||{},this.annotations={},this.surfaceOffset=t.surfaceOffset}getContainerElement(){return this._container}send(e,t){if("clearAnnotations"===e)this.clear()}set surfaceOffset(e){null==e&&(e=.3),this._surfaceOffset=e}get surfaceOffset(){return this._surfaceOffset}createAnnotation(e){this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id);var t=null;e.markerElementId&&((t=document.getElementById(e.markerElementId))||this.error("Can't find DOM element for 'markerElementId' value '"+e.markerElementId+"' - defaulting to internally-generated empty DIV"));var i=null;e.labelElementId&&((i=document.getElementById(e.labelElementId))||this.error("Can't find DOM element for 'labelElementId' value '"+e.labelElementId+"' - defaulting to internally-generated empty DIV"));const s=new Ue(this.viewer.scene,{id:e.id,plugin:this,container:this._container,markerElement:t,labelElement:i,markerHTML:e.markerHTML||this._markerHTML,labelHTML:e.labelHTML||this._labelHTML,occludable:e.occludable,values:y.apply(e.values,y.apply(this._values,{})),markerShown:e.markerShown,labelShown:e.labelShown,eye:e.eye,look:e.look,up:e.up,projection:e.projection,visible:!1!==e.visible});return e.pickResult=e.pickResult||e.pickRecord,e.pickResult?s.setFromPickResult(e.pickResult):(s.entity=e.entity,s.worldPos=e.worldPos),this.annotations[s.id]=s,s.on("destroyed",(()=>{delete this.annotations[s.id],this.fire("annotationDestroyed",s.id)})),this.fire("annotationCreated",s.id),s}destroyAnnotation(e){var t=this.annotations[e];t?t.destroy():this.log("Annotation not found: "+e)}clear(){const e=Object.keys(this.annotations);for(var t=0,i=e.length;t
',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){const e="xeokit-spinner-css";if(document.getElementById(e))return;const t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}_adjustPosition(){if(this._isCustom)return;const e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const Ne=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class Qe extends R{constructor(e,t={}){super(e,t),this._backgroundColor=d.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const i=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),i.scene._webglContextLost(),i.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){i._initWebGL(),i.gl&&(i.scene._webglContextRestored(i.gl),i.fire("webglcontextrestored",i.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let s=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(s=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{s&&(s=!1,i.canvas.width=Math.round(i.canvas.clientWidth*i._resolutionScale),i.canvas.height=Math.round(i.canvas.clientHeight*i._resolutionScale),i.boundary[0]=i.canvas.offsetLeft,i.boundary[1]=i.canvas.offsetTop,i.boundary[2]=i.canvas.clientWidth,i.boundary[3]=i.canvas.clientHeight,i.fire("boundary",i.boundary))})),this._spinner=new ke(this.scene,{canvas:this.canvas,elementId:t.spinnerElementId})}get type(){return"Canvas"}get backgroundColorFromAmbientLight(){return this._backgroundColorFromAmbientLight}set backgroundColorFromAmbientLight(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}get backgroundColor(){return this._backgroundColor}set backgroundColor(e){e?(this._backgroundColor[0]=e[0],this._backgroundColor[1]=e[1],this._backgroundColor[2]=e[2]):(this._backgroundColor[0]=1,this._backgroundColor[1]=1,this._backgroundColor[2]=1),this.glRedraw()}get resolutionScale(){return this._resolutionScale}set resolutionScale(e){if((e=e||1)===this._resolutionScale)return;this._resolutionScale=e;const t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}get spinner(){return this._spinner}_createCanvas(){const e="xeokit-canvas-"+d.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),s=i.style;s.height="100%",s.width="100%",s.padding="0",s.margin="0",s.background="rgba(0,0,0,0);",s.float="left",s.left="0",s.top="0",s.position="absolute",s.opacity="1.0",s["z-index"]="-10000",i.innerHTML+='',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&&e0?He.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?He.FS_MAX_FLOAT_PRECISION="mediump":He.FS_MAX_FLOAT_PRECISION="lowp":He.FS_MAX_FLOAT_PRECISION="mediump",He.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),He.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),He.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),He.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),He.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),He.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),He.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),He.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),He.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),He.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){He.SUPPORTED_EXTENSIONS[e]=!0})))}class Ge{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get snappedCanvasPos(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null}set snappedCanvasPos(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}get worldPos(){return this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}get snapped(){return this.snappedToEdge||this.snappedToVertex}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}class ze{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;e0&&"/"===i.charAt(s+1)&&(i=i.substring(0,s)),t.push(i);return t.join("\n")}function Ye(e){console.error(e.join("\n"))}class Ze{constructor(e,t){this.id=Xe.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 ze(e,e.VERTEX_SHADER,Je(this.source.vertex)),this._fragmentShader=new ze(e,e.FRAGMENT_SHADER,Je(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void Ye(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void Ye(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void Ye(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void Ye(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 Ye(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;ithis.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}setData(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}bind(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}unbind(){this.allocated&&this._gl.bindBuffer(this.type,null)}destroy(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}class $e{constructor(e,t){this.scene=e,this.aabb=d.AABB3(),this.origin=d.vec3(t),this.originHash=this.origin.join(),this.numMarkers=0,this.markers={},this.markerList=[],this.markerIndices={},this.positions=[],this.indices=[],this.positionsBuf=null,this.lenPositionsBuf=0,this.indicesBuf=null,this.sectionPlanesActive=[],this.culledBySectionPlanes=!1,this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.aabbDirty=!1,this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!1}addMarker(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}markerWorldPosUpdated(e){if(!this.markers[e.id])return;const t=this.markerIndices[e.id];this.positions[3*t+0]=e.worldPos[0],this.positions[3*t+1]=e.worldPos[1],this.positions[3*t+2]=e.worldPos[2],this.positionsDirty=!0}removeMarker(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}update(){this.markerListDirty&&(this._buildMarkerList(),this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0),this.positionsDirty&&(this._buildPositions(),this.positionsDirty=!1,this.aabbDirty=!0,this.vbosDirty=!0),this.aabbDirty&&(this._buildAABB(),this.aabbDirty=!1),this.vbosDirty&&(this._buildVBOs(),this.vbosDirty=!1),this.occlusionTestListDirty&&this._buildOcclusionTestList(),this._updateActiveSectionPlanes()}_buildMarkerList(){for(var e in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(e)&&(this.markerList[this.numMarkers]=this.markers[e],this.markerIndices[e]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers}_buildPositions(){let e=0;for(let t=0;t-t){i._setVisible(!1);continue}const n=i.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>s||l-10>r?i._setVisible(!1):!i.entity||i.entity.visible?i.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=i,this.pixels[o++]=a,this.pixels[o++]=l):i._setVisible(!0):i._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let i=0;i{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i||(i=new $e(this._scene,e.origin),this._occlusionLayers[i.originHash]=i,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return;const i=e.origin.join();if(i!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let s=this._occlusionLayers[i];s||(s=new $e(this._scene,e.origin),this._occlusionLayers[i]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.originHash],this._occlusionLayersListDirty=!0):i.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e0,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):e.markerZOffset<0&&i.push("clipPos.z += "+e.markerZOffset+";"),i.push(" gl_Position = clipPos;"),i.push("}"),i}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// OcclusionTester fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Ze(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e0){const e=s.sectionPlanes;for(let s=0;s{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=d.mat4();return()=>(e&&d.inverseMat4(s.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,i=this._program,s=this._scene,r=s.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=s.camera.project._state,l=a.near,A=a.far,h=a.matrix,c=this._getInverseProjectMat(),u=Math.random(),p="perspective"===s.camera.projection;st[0]=o,st[1]=n,t.viewport(0,0,o,n),t.clearColor(0,0,0,1),t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.frontFace(t.CCW),t.clear(t.COLOR_BUFFER_BIT),i.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,A),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,h),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,c),t.uniform1i(this._uPerspective,p),t.uniform1f(this._uScale,r.scale*(A/5)),t.uniform1f(this._uIntensity,r.intensity),t.uniform1f(this._uBias,r.bias),t.uniform1f(this._uKernelRadius,r.kernelRadius),t.uniform1f(this._uMinResolution,r.minResolution),t.uniform2fv(this._uViewport,st),t.uniform1f(this._uRandomSeed,u);const f=e.getDepthTexture();i.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e)return;const i=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new Ze(i,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),o=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new qe(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new qe(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new qe(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const ot=new Float32Array(ct(17,[0,1])),nt=new Float32Array(ct(17,[1,0])),at=new Float32Array(function(e,t){const i=[];for(let s=0;s<=e;s++)i.push(ht(s,t));return i}(17,4)),lt=new Float32Array(2);class At{constructor(e){this._scene=e,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._uViewport=null,this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new Ze(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS 16\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new qe(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new qe(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new qe(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,i){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=d.mat4();return()=>(e&&d.inverseMat4(o.camera.projMatrix,t),t)})());const s=this._scene.canvas.gl,r=this._program,o=this._scene,n=s.drawingBufferWidth,a=s.drawingBufferHeight,l=o.camera.project._state,A=l.near,h=l.far;s.viewport(0,0,n,a),s.clearColor(0,0,0,1),s.enable(s.DEPTH_TEST),s.disable(s.BLEND),s.frontFace(s.CCW),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),r.bind(),lt[0]=n,lt[1]=a,s.uniform2fv(this._uViewport,lt),s.uniform1f(this._uCameraNear,A),s.uniform1f(this._uCameraFar,h),s.uniform1f(this._uDepthCutoff,.01),0===i?s.uniform2fv(this._uSampleOffsets,nt):s.uniform2fv(this._uSampleOffsets,ot),s.uniform1fv(this._uSampleWeights,at);const c=e.getDepthTexture(),u=t.getTexture();r.bindTexture(this._uDepthTexture,c,0),r.bindTexture(this._uOcclusionTexture,u,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),s.drawElements(s.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function ht(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function ct(e,t){const i=[];for(let s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}class ut{constructor(e,t,i){i=i||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=i.size,this._hasDepthTexture=!!i.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(...e){if(this._touch(...e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}createTexture(e,t,i=null){const s=this.gl,r=s.createTexture();return s.bindTexture(s.TEXTURE_2D,r),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),i?s.texStorage2D(s.TEXTURE_2D,1,i,e,t):s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null),r}_touch(...e){let t,i;const s=this.gl;if(this.size?(t=this.size[0],i=this.size[1]):(t=s.drawingBufferWidth,i=s.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===i)return;this.buffer.textures.forEach((e=>s.deleteTexture(e))),s.deleteFramebuffer(this.buffer.framebuf),s.deleteRenderbuffer(this.buffer.renderbuf)}const r=[];let o;e.length>0?r.push(...e.map((e=>this.createTexture(t,i,e)))):r.push(this.createTexture(t,i)),this._hasDepthTexture&&(o=s.createTexture(),s.bindTexture(s.TEXTURE_2D,o),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,s.DEPTH_COMPONENT32F,t,i,0,s.DEPTH_COMPONENT,s.FLOAT,null));const n=s.createRenderbuffer();s.bindRenderbuffer(s.RENDERBUFFER,n),s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT32F,t,i);const a=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,a);for(let e=0;e0&&s.drawBuffers(r.map(((e,t)=>s.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,o,0):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,n),s.bindTexture(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,a),!s.isFramebuffer(a))throw"Invalid framebuffer";s.bindFramebuffer(s.FRAMEBUFFER,null);const l=s.checkFramebufferStatus(s.FRAMEBUFFER);switch(l){case s.FRAMEBUFFER_COMPLETE:break;case s.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case s.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:a,renderbuf:n,texture:r[0],textures:r,depthTexture:o,width:t,height:i},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,i=null,s=null,r=Uint8Array,o=4,n=0){const a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,A=new r(o),h=this.gl;return h.readBuffer(h.COLOR_ATTACHMENT0+n),h.readPixels(a,l,1,1,i||h.RGBA,s||h.UNSIGNED_BYTE,A,0),A}readArray(e=null,t=null,i=Uint8Array,s=4,r=0){const o=new i(this.buffer.width*this.buffer.height*s),n=this.gl;return n.readBuffer(n.COLOR_ATTACHMENT0+r),n.readPixels(0,0,this.buffer.width,this.buffer.height,e||n.RGBA,t||n.UNSIGNED_BYTE,o,0),o}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),i=t.pixelData,s=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,A=4*n,h=new Uint8Array(4*n);for(let e=0;ee.deleteTexture(t))),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}class dt{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let s=i[e];return s||(s=new ut(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=s),s}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}function pt(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}const ft=function(t,i){i=i||{};const s=new Ve(t),r=t.canvas.canvas,o=t.canvas.gl,n=!!i.transparent,a=i.alphaDepthMask,l=new e({});let A={},h={},c=[],u=[],p=!0,f=!0,g=!0,_=!0,v=!0,b=!0,y=!0,x=!0;const B=new dt(t);let w=!1;const P=new rt(t),C=new At(t);function M(){p&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableMap,s=t.drawableListPreCull;let r=0;for(let e in i)i.hasOwnProperty(e)&&(s[r++]=i[e]);s.length=r}}(),p=!1,f=!0),f&&(!function(){let e=0;for(let t in A)if(A.hasOwnProperty(t)){const i=A[t].drawableListPreCull;for(let t=0,s=i.length;te.renderOrder-t.renderOrder))}(),f=!1,g=!0),g&&function(){let e=0;for(let t=0,i=c.length;t0)for(s.withSAO=!0,S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||H>0||O>0||k>0){if(o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):(o.blendEquation(o.FUNC_ADD),o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA)),s.backfaces=!1,a||o.depthMask(!1),(O>0||k>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),k>0)for(S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||G>0){if(s.lastProgramId=null,t.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),G>0)for(S=0;S0)for(S=0;S0||W>0||j>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),o.enable(o.CULL_FACE),W>0)for(S=0;S0)for(S=0;S0||X>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),X>0)for(S=0;S0)for(S=0;S0||Y>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),Y>0)for(S=0;S0)for(S=0;S0){const t=Math.floor(e/4),i=_.size[0],s=t%i-Math.floor(i/2),r=Math.floor(t/i)-Math.floor(i/2),o=Math.sqrt(Math.pow(s,2)+Math.pow(r,2));U.push({x:s,y:r,dist:o,isVertex:p&&f?x[e+3]>y.length/2:p,result:[x[e+0],x[e+1],x[e+2],x[e+3]],normal:[w[e+0],w[e+1],w[e+2],w[e+3]],id:[P[e+0],P[e+1],P[e+2],P[e+3]]})}let O=null,k=null,N=null,Q=null;if(U.length>0){U.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),Q=U[0].isVertex?"vertex":"edge";const e=U[0].result,t=U[0].normal,i=U[0].id,s=y[e[3]],r=s.origin,o=s.coordinateScale;k=d.normalizeVec3([t[0]/d.MAX_INT,t[1]/d.MAX_INT,t[2]/d.MAX_INT]),O=[e[0]*o[0]+r[0],e[1]*o[1]+r[1],e[2]*o[2]+r[2]],N=l.items[i[0]+(i[1]<<8)+(i[2]<<16)+(i[3]<<24)]}if(null===C&&null==O)return null;let V=null;null!==O&&(V=t.camera.projectWorldPos(O));const H=N&&N.delegatePickedEntity?N.delegatePickedEntity():N;return!H&&E&&(E=E.delegatePickedEntity?E.delegatePickedEntity():E),r.reset(),r.snappedToEdge="edge"===Q,r.snappedToVertex="vertex"===Q,r.worldPos=O||C,r.worldNormal=k||M,r.entity=H||E,r.canvasPos=n||t.camera.projectWorldPos(C||O),r.snappedCanvasPos=V||n,r}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new it(t,B),this._occlusionTester.addMarker(e),t.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){M(),this._occlusionTester.bindRenderBuf(),s.reset(),s.backfaces=!0,s.frontface=!0,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e=0,t=u.length;e{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!0:e.keyCode===this.KEY_ALT?this.altDown=!0:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!0),this.keyDown[e.keyCode]=!0,this.fire("keydown",e.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!1:e.keyCode===this.KEY_ALT?this.altDown=!1:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!1),this.keyDown[e.keyCode]=!1,this.fire("keyup",e.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=e=>{this.enabled&&(this.mouseover=!0,this._getMouseCanvasPos(e),this.fire("mouseenter",this.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=e=>{this.enabled&&(this.mouseover=!1,this._getMouseCanvasPos(e),this.fire("mouseleave",this.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!0;break;case 2:this.mouseDownMiddle=!0;break;case 3:this.mouseDownRight=!0}this._getMouseCanvasPos(e),this.element.focus(),this.fire("mousedown",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownRight=!1}this.fire("mouseup",this.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("click",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("dblclick",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}});const e=this.scene.tickify((()=>this.fire("mousemove",this.mouseCanvasPos,!0)));this.element.addEventListener("mousemove",this._mouseMoveListener=t=>{this.enabled&&(this._getMouseCanvasPos(t),e(),this.mouseover&&t.preventDefault())}),this.element.addEventListener("contextmenu",this._contextmenuListener=e=>{this.enabled&&(this._getMouseCanvasPos(e),this.fire("contextmenu",this.mouseCanvasPos,!0))});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,i)=>{if(!this.enabled)return;const s=Math.max(-1,Math.min(1,40*-e.deltaY));t(s)},{passive:!0});{let e,t;const i=2;this.on("mousedown",(i=>{e=i[0],t=i[1]})),this.on("mouseup",(s=>{e>=s[0]-i&&e<=s[0]+i&&t>=s[1]-i&&t<=s[1]+i&&this.fire("mouseclicked",s,!0)}))}this.element.addEventListener("touchstart",this._touchstartListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchstart",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this.element.addEventListener("touchend",this._touchendListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchend",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this._eventsBound=!0}_unbindEvents(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("contextmenu",this._contextmenuListener),this.element.removeEventListener("wheel",this._mouseWheelListener),this.element.removeEventListener("touchstart",this._touchstartListener),this.element.removeEventListener("touchend",this._touchendListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getTouchCanvasPos(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;return[e.pageX-i,e.pageY-s]}_getMouseCanvasPos(e){if(e){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()}}const mt=new e({});class _t{constructor(e){this.id=mt.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){mt.removeItem(this.id)}}class vt extends R{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new _t({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 bt extends R{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new _t({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.canvas.boundary,t=e[2]/e[3],i=this._fovAxis;let s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),d.perspectiveMat4(s*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class yt extends R{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new _t({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,i=e.canvas.boundary,s=i[2],r=i[3],o=s/r;let n,a,l,A;s>r?(n=-t,a=t,l=t/o,A=-t/o):(n=-t*o,a=t*o,l=t,A=-t),d.orthoMat4c(n,a,A,l,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class xt extends R{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new _t({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._left=-1,this._right=1,this._bottom=-1,this._top=1,this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.left=t.left,this.right=t.right,this.bottom=t.bottom,this.top=t.top,this.near=t.near,this.far=t.far}_update(){d.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set left(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}get left(){return this._left}set right(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}get right(){return this._right}set top(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}get top(){return this._top}set bottom(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}get bottom(){return this._bottom}set near(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}get near(){return this._state.near}set far(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class Bt extends R{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new _t({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4()}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!1,this.matrix=t.matrix}set matrix(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}get matrix(){return this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy()}}const wt=d.vec3(),Pt=d.vec3(),Ct=d.vec3(),Mt=d.vec3(),Et=d.vec3(),Ft=d.vec3(),It=d.vec4(),Dt=d.vec4(),St=d.vec4(),Tt=d.mat4(),Rt=d.mat4(),Lt=d.vec3(),Ut=d.vec3(),Ot=d.vec3(),kt=d.vec3();class Nt extends R{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new _t({deviceMatrix:d.mat4(),hasDeviceMatrix:!1,matrix:d.mat4(),normalMatrix:d.mat4(),inverseMatrix:d.mat4()}),this._perspective=new bt(this),this._ortho=new yt(this),this._frustum=new xt(this),this._customProjection=new Bt(this),this._project=this._perspective,this._eye=d.vec3([0,0,10]),this._look=d.vec3([0,0,0]),this._up=d.vec3([0,1,0]),this._worldUp=d.vec3([0,1,0]),this._worldRight=d.vec3([1,0,0]),this._worldForward=d.vec3([0,0,-1]),this.deviceMatrix=t.deviceMatrix,this.eye=t.eye,this.look=t.look,this.up=t.up,this.worldAxis=t.worldAxis,this.gimbalLock=t.gimbalLock,this.constrainPitch=t.constrainPitch,this.projection=t.projection,this._perspective.on("matrix",(()=>{"perspective"===this._projectionType&&this.fire("projMatrix",this._perspective.matrix)})),this._ortho.on("matrix",(()=>{"ortho"===this._projectionType&&this.fire("projMatrix",this._ortho.matrix)})),this._frustum.on("matrix",(()=>{"frustum"===this._projectionType&&this.fire("projMatrix",this._frustum.matrix)})),this._customProjection.on("matrix",(()=>{"customProjection"===this._projectionType&&this.fire("projMatrix",this._customProjection.matrix)}))}_update(){const e=this._state;let t;"ortho"===this.projection?(d.subVec3(this._eye,this._look,Lt),d.normalizeVec3(Lt,Ut),d.mulVec3Scalar(Ut,1e3,Ot),d.addVec3(this._look,Ot,kt),t=kt):t=this._eye,e.hasDeviceMatrix?(d.lookAtMat4v(t,this._look,this._up,Rt),d.mulMat4(e.deviceMatrix,Rt,e.matrix)):d.lookAtMat4v(t,this._look,this._up,e.matrix),d.inverseMat4(this._state.matrix,this._state.inverseMatrix),d.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}orbitYaw(e){let t=d.subVec3(this._eye,this._look,wt);d.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,Tt),t=d.transformPoint3(Tt,t,Pt),this.eye=d.addVec3(this._look,t,Ct),this.up=d.transformPoint3(Tt,this._up,Mt)}orbitPitch(e){if(this._constrainPitch&&(e=d.dotVec3(this._up,this._worldUp)/d.DEGTORAD)<1)return;let t=d.subVec3(this._eye,this._look,wt);const i=d.cross3Vec3(d.normalizeVec3(t,Pt),d.normalizeVec3(this._up,Ct));d.rotationMat4v(.0174532925*e,i,Tt),t=d.transformPoint3(Tt,t,Mt),this.up=d.transformPoint3(Tt,this._up,Et),this.eye=d.addVec3(t,this._look,Ft)}yaw(e){let t=d.subVec3(this._look,this._eye,wt);d.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,Tt),t=d.transformPoint3(Tt,t,Pt),this.look=d.addVec3(t,this._eye,Ct),this._gimbalLock&&(this.up=d.transformPoint3(Tt,this._up,Mt))}pitch(e){if(this._constrainPitch&&(e=d.dotVec3(this._up,this._worldUp)/d.DEGTORAD)<1)return;let t=d.subVec3(this._look,this._eye,wt);const i=d.cross3Vec3(d.normalizeVec3(t,Pt),d.normalizeVec3(this._up,Ct));d.rotationMat4v(.0174532925*e,i,Tt),this.up=d.transformPoint3(Tt,this._up,Ft),t=d.transformPoint3(Tt,t,Mt),this.look=d.addVec3(t,this._eye,Et)}pan(e){const t=d.subVec3(this._eye,this._look,wt),i=[0,0,0];let s;if(0!==e[0]){const r=d.cross3Vec3(d.normalizeVec3(t,[]),d.normalizeVec3(this._up,Pt));s=d.mulVec3Scalar(r,e[0]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]}0!==e[1]&&(s=d.mulVec3Scalar(d.normalizeVec3(this._up,Ct),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=d.mulVec3Scalar(d.normalizeVec3(t,Mt),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=d.addVec3(this._eye,i,Et),this.look=d.addVec3(this._look,i,Ft)}zoom(e){const t=d.subVec3(this._eye,this._look,wt),i=Math.abs(d.lenVec3(t,Pt)),s=Math.abs(i+e);if(s<.5)return;const r=d.normalizeVec3(t,Ct);this.eye=d.addVec3(this._look,d.mulVec3Scalar(r,s),Mt)}set eye(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}get eye(){return this._eye}set look(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}get look(){return this._look}set up(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}get up(){return this._up}set deviceMatrix(e){this._state.deviceMatrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._state.hasDeviceMatrix=!!e,this._needUpdate(0),this.fire("deviceMatrix",this._state.deviceMatrix)}get deviceMatrix(){return this._state.deviceMatrix}set worldAxis(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=d.vec3(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}get worldAxis(){return this._worldAxis}get worldUp(){return this._worldUp}get xUp(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}get yUp(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}get zUp(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}get worldRight(){return this._worldRight}get worldForward(){return this._worldForward}set gimbalLock(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}get gimbalLock(){return this._gimbalLock}set constrainPitch(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}get eyeLookDist(){return d.lenVec3(d.subVec3(this._look,this._eye,wt))}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get viewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get normalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get viewNormalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get inverseViewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}get projMatrix(){return this[this.projection].matrix}get perspective(){return this._perspective}get ortho(){return this._ortho}get frustum(){return this._frustum}get customProjection(){return this._customProjection}set projection(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}get projection(){return this._projectionType}get project(){return this._project}projectWorldPos(e){const t=It,i=Dt,s=St;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,d.mulMat4v4(this.viewMatrix,t,i),d.mulMat4v4(this.projMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[s[0]*o+o,s[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}class Qt extends R{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class Vt extends Qt{get type(){return"DirLight"}constructor(e,t={}){super(e,t),this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const i=this.scene.camera,s=this.scene.canvas;this._onCameraViewMatrix=i.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=i.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=s.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new _t({type:"dir",dir:d.vec3([1,1,1]),color:d.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=d.identityMat4());const e=this.scene.camera,t=this._state.dir,i=e.look,s=[i[0]-t[0],i[1]-t[1],i[2]-t[2]],r=[0,1,0];d.lookAtMat4v(s,i,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=d.identityMat4()),d.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new ut(this.scene.canvas.canvas,this.scene.canvas.gl,{size:[1024,1024]})),this._shadowRenderBuf)}),this.dir=t.dir,this.color=t.color,this.intensity=t.intensity,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set dir(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get dir(){return this._state.dir}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}class Ht extends Qt{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:d.vec3([.7,.7,.7]),intensity:1},this.color=t.color,this.intensity=t.intensity,this.scene._lightCreated(this)}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}get intensity(){return this._state.intensity}destroy(){super.destroy(),this.scene._lightDestroyed(this)}}class jt extends R{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),m.memory.meshes++}destroy(){super.destroy(),m.memory.meshes--}}var Gt=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=d.vec3(),h=d.vec3(),c=d.vec3(),u=d.vec3(),p=d.vec3(),f=d.vec3(),g=d.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;ux)||(T=i[F.index1],R=i[F.index2],(!L&&T>65535||R>65535)&&(L=!0),y.push(T),y.push(R));return L?new Uint32Array(y):new Uint16Array(y)}}();const zt=function(){const e=d.mat4(),t=d.mat4();return function(i,s){s=s||d.mat4();const r=i[0],o=i[1],n=i[2],a=i[3]-r,l=i[4]-o,A=i[5]-n,h=65535;return d.identityMat4(e),d.translationMat4v(i,e),d.identityMat4(t),d.scalingMat4v([a/h,l/h,A/h],t),d.mulMat4(e,t,s),s}}();var Wt=function(){const e=d.mat4(),t=d.mat4();return function(i,s,r){const o=new Uint16Array(i.length),n=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);let a;for(a=0;a=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 Jt(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 Yt(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}const Zt={getPositionsBounds:function(e){const t=new Float32Array(3),i=new Float32Array(3);let s,r;for(s=0;s<3;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;sn&&(r=i,n=o),i=Xt(e,a,"floor","ceil"),s=Jt(i),o=Yt(e,a,s),o>n&&(r=i,n=o),i=Xt(e,a,"ceil","ceil"),s=Jt(i),o=Yt(e,a,s),o>n&&(r=i,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t},decompressNormal:function(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t}},qt=m.memory,$t=d.AABB3();class ei extends jt{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new _t({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=Zt.getPositionsBounds(t.positions),s=Zt.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=Zt.getUVBounds(t.uv),s=Zt.compressUVs(t.uv,e.min,e.max);i.uv=s.quantized,i.uvDecodeMatrix=s.decodeMatrix}else i.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?i.normals=Zt.compressNormals(t.normals):i.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(i.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)),this._buildHash(),qt.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new qe(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),qt.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new qe(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),qt.positions+=e.positionsBuf.numItems),e.normals){let i=e.compressGeometry;e.normalsBuf=new qe(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),qt.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new qe(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),qt.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new qe(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),qt.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=Gt(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new qe(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),qt.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=d.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new qe(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new qe(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),qt.positions+=this._pickTrianglePositionsBuf.numItems,qt.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),Zt.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=Zt.getPositionsBounds(e),s=Zt.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),Zt.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),Zt.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null}set uv(e){if(this._state.compressGeometry)return void this.error("can't update geometry UVs - quantized geometry is immutable");const t=this._state,i=t.uv;i?i.length===e.length?(i.set(e),t.uvBuf&&t.uvBuf.setData(i),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}get colors(){return this._state.colors}set colors(e){if(this._state.compressGeometry)return void this.error("can't update geometry colors - quantized geometry is immutable");const t=this._state,i=t.colors;i?i.length===e.length?(i.set(e),t.colorsBuf&&t.colorsBuf.setData(i),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}get indices(){return this._state.indices}get aabb(){return this._aabbDirty&&(this._aabb||(this._aabb=d.AABB3()),d.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=d.OBB3()),d.positions3ToAABB3(this._state.positions,$t,this._state.positionsDecodeMatrix),d.AABB3ToOBB3($t,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(),qt.meshes--}}function ti(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return y.apply(e,{positions:[c,u,d,l,u,d,l,A,d,c,A,d,c,u,d,c,A,d,c,A,h,c,u,h,c,u,d,c,u,h,l,u,h,l,u,d,l,u,d,l,u,h,l,A,h,l,A,d,l,A,h,c,A,h,c,A,d,l,A,d,c,A,h,l,A,h,l,u,h,c,u,h],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 ii extends R{get type(){return"Material"}constructor(e,t={}){super(e,t),m.memory.materials++}destroy(){super.destroy(),m.memory.materials--}}const si={opaque:0,mask:1,blend:2},ri=["opaque","mask","blend"];class oi extends ii{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new _t({type:"PhongMaterial",ambient:d.vec3([1,1,1]),diffuse:d.vec3([1,1,1]),specular:d.vec3([1,1,1]),emissive:d.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.ambient=t.ambient,this.diffuse=t.diffuse,this.specular=t.specular,this.emissive=t.emissive,this.alpha=t.alpha,this.shininess=t.shininess,this.reflectivity=t.reflectivity,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,t.ambientMap&&(this._ambientMap=this._checkComponent("Texture",t.ambientMap)),t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.reflectivityMap&&(this._reflectivityMap=this._checkComponent("Texture",t.reflectivityMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.diffuseFresnel&&(this._diffuseFresnel=this._checkComponent("Fresnel",t.diffuseFresnel)),t.specularFresnel&&(this._specularFresnel=this._checkComponent("Fresnel",t.specularFresnel)),t.emissiveFresnel&&(this._emissiveFresnel=this._checkComponent("Fresnel",t.emissiveFresnel)),t.alphaFresnel&&(this._alphaFresnel=this._checkComponent("Fresnel",t.alphaFresnel)),t.reflectivityFresnel&&(this._reflectivityFresnel=this._checkComponent("Fresnel",t.reflectivityFresnel)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this._makeHash()}_makeHash(){const e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}set shininess(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}get shininess(){return this._state.shininess}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set reflectivity(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}get reflectivity(){return this._state.reflectivity}get normalMap(){return this._normalMap}get ambientMap(){return this._ambientMap}get diffuseMap(){return this._diffuseMap}get specularMap(){return this._specularMap}get emissiveMap(){return this._emissiveMap}get alphaMap(){return this._alphaMap}get reflectivityMap(){return this._reflectivityMap}get occlusionMap(){return this._occlusionMap}get diffuseFresnel(){return this._diffuseFresnel}get specularFresnel(){return this._specularFresnel}get emissiveFresnel(){return this._emissiveFresnel}get alphaFresnel(){return this._alphaFresnel}get reflectivityFresnel(){return this._reflectivityFresnel}set alphaMode(e){let t=si[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 ri[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}destroy(){super.destroy(),this._state.destroy()}}const ni={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}};class ai extends ii{get type(){return"EmphasisMaterial"}get presets(){return ni}constructor(e,t={}){super(e,t),this._state=new _t({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),this._preset="default",t.preset?(this.preset=t.preset,void 0!==t.fill&&(this.fill=t.fill),t.fillColor&&(this.fillColor=t.fillColor),void 0!==t.fillAlpha&&(this.fillAlpha=t.fillAlpha),void 0!==t.edges&&(this.edges=t.edges),t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth),void 0!==t.backfaces&&(this.backfaces=t.backfaces),void 0!==t.glowThrough&&(this.glowThrough=t.glowThrough)):(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.backfaces=t.backfaces,this.glowThrough=t.glowThrough)}set fill(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}get fill(){return this._state.fill}set fillColor(e){let t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}get fillColor(){return this._state.fillColor}set fillAlpha(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}get fillAlpha(){return this._state.fillAlpha}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set glowThrough(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}get glowThrough(){return this._state.glowThrough}set preset(e){if(e=e||"default",this._preset===e)return;const t=ni[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(ni).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const li={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 Ai extends ii{get type(){return"EdgeMaterial"}get presets(){return li}constructor(e,t={}){super(e,t),this._state=new _t({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),this._preset="default",t.preset?(this.preset=t.preset,t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth)):(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth),this.edges=!1!==t.edges}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=li[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(li).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const hi={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 ci extends R{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=d.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return hi}set units(e){e||(e="meters");hi[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}get units(){return this._units}set scale(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}get scale(){return this._scale}set origin(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}get origin(){return this._origin}worldToRealPos(e,t=d.vec3(3)){t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}realToWorldPos(e,t=d.vec3(3)){return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}class ui extends R{constructor(e,t={}){super(e,t),this._supported=He.SUPPORTED_EXTENSIONS.OES_standard_derivatives,this.enabled=t.enabled,this.kernelRadius=t.kernelRadius,this.intensity=t.intensity,this.bias=t.bias,this.scale=t.scale,this.minResolution=t.minResolution,this.numSamples=t.numSamples,this.blur=t.blur,this.blendCutoff=t.blendCutoff,this.blendFactor=t.blendFactor}get supported(){return this._supported}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}get enabled(){return this._enabled}get possible(){if(!this._supported)return!1;if(!this._enabled)return!1;const e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}get active(){return this._active}set kernelRadius(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}get kernelRadius(){return this._kernelRadius}set intensity(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}get intensity(){return this._intensity}set bias(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}get bias(){return this._bias}set scale(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}get scale(){return this._scale}set minResolution(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}get minResolution(){return this._minResolution}set numSamples(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}get numSamples(){return this._numSamples}set blur(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}get blur(){return this._blur}set blendCutoff(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}get blendCutoff(){return this._blendCutoff}set blendFactor(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}get blendFactor(){return this._blendFactor}destroy(){super.destroy()}}class di extends R{constructor(e,t={}){super(e,t),this.sliceColor=t.sliceColor,this.sliceThickness=t.sliceThickness}set sliceThickness(e){null==e&&(e=0),this._sliceThickness!==e&&(this._sliceThickness=e,this.glRedraw())}get sliceThickness(){return this._sliceThickness}set sliceColor(e){null==e&&(e=[0,0,0,1]),this._sliceColor!==e&&(this._sliceColor=e,this.glRedraw())}get sliceColor(){return this._sliceColor}destroy(){super.destroy()}}const pi={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class fi extends ii{get type(){return"PointsMaterial"}get presets(){return pi}constructor(e,t={}){super(e,t),this._state=new _t({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),t.preset?(this.preset=t.preset,void 0!==t.pointSize&&(this.pointSize=t.pointSize),void 0!==t.roundPoints&&(this.roundPoints=t.roundPoints),void 0!==t.perspectivePoints&&(this.perspectivePoints=t.perspectivePoints),void 0!==t.minPerspectivePointSize&&(this.minPerspectivePointSize=t.minPerspectivePointSize),void 0!==t.maxPerspectivePointSize&&(this.maxPerspectivePointSize=t.minPerspectivePointSize)):(this._preset="default",this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize),this.filterIntensity=t.filterIntensity,this.minIntensity=t.minIntensity,this.maxIntensity=t.maxIntensity}set pointSize(e){this._state.pointSize=e||2,this.glRedraw()}get pointSize(){return this._state.pointSize}set roundPoints(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}get roundPoints(){return this._state.roundPoints}set perspectivePoints(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}get perspectivePoints(){return this._state.perspectivePoints}set minPerspectivePointSize(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}get minPerspectivePointSize(){return this._state.minPerspectivePointSize}set maxPerspectivePointSize(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}get maxPerspectivePointSize(){return this._state.maxPerspectivePointSize}set filterIntensity(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}get filterIntensity(){return this._state.filterIntensity}set minIntensity(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}get minIntensity(){return this._state.minIntensity}set maxIntensity(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}get maxIntensity(){return this._state.maxIntensity}set preset(e){if(e=e||"default",this._preset===e)return;const t=pi[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(pi).join(", "))}get preset(){return this._preset}get hash(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}destroy(){super.destroy(),this._state.destroy()}}const gi={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class mi extends ii{get type(){return"LinesMaterial"}get presets(){return gi}constructor(e,t={}){super(e,t),this._state=new _t({type:"LinesMaterial",lineWidth:null}),t.preset?(this.preset=t.preset,void 0!==t.lineWidth&&(this.lineWidth=t.lineWidth)):(this._preset="default",this.lineWidth=t.lineWidth)}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=gi[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(gi).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function _i(e,t){const i={};let s,r;for(let o=0,n=t.length;o{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new ft(this,{transparent:s,alphaDepthMask:r}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;let e=null;this.getHash=function(){if(e)return e;const t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";const i=[];for(let e=0,s=t;ethis._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},this._sectionPlanesState.setNumCachedSectionPlanes(t.numCachedSectionPlanes||0),this._lightsState=new function(){const e=d.vec4([0,0,0,0]),t=d.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let i=null,s=null;this.getHash=function(){if(i)return i;const e=[],t=this.lights;let s;for(let i=0,r=t.length;i0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),i=e.join(""),i},this.addLight=function(e){this.lights.push(e),s=null,i=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t{this._renderer.imageDirty()}))}_initDefaults(){}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+y.inQuotes(e.id)+" already exists in Scene - ignoring ID, will randomly-generate instead"),e.id=null),!e.id)for(void 0===window.nextID&&(window.nextID=0),e.id="__"+window.nextID++;this.components[e.id];)e.id=d.createUUID();this.components[e.id]=e;const t=e.type;let i=this.types[e.type];i||(i=this.types[t]={}),i[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,i=e.type;delete this.components[t];const s=this.types[i];s&&(delete s[t],y.isEmptyObject(s)&&delete this.types[i]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_deRegisterVisibleObject(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_deRegisterXRayedObject(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}_objectHighlightedUpdated(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}_deRegisterHighlightedObject(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_deRegisterSelectedObject(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_deRegisterColorizedObject(e){delete this.colorizedObjects[e.id],this._numColorizedObjects--,this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_deRegisterOpacityObject(e){delete this.opacityObjects[e.id],this._numOpacityObjects--,this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_deRegisterOffsetObject(e){delete this.offsetObjects[e.id],this._numOffsetObjects--,this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get readableGeometryEnabled(){return this._readableGeometry}get pickSurfacePrecisionEnabled(){return this._readableGeometry}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set numCachedSectionPlanes(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}get numCachedSectionPlanes(){return this._sectionPlanesState.getNumCachedSectionPlanes()}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}get markerZOffset(){return null==this._markerZOffset?-.001:this._markerZOffset}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&I.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const i=this._passes,s=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),A=!0}A||(t=-100,i=-100,s=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=n,this._aabbDirty=!1,this._center=null}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const i=e.includeEntities||e.include;i&&(e.includeEntityIds=_i(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=_i(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){if(void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),e.canvasPos)return this._renderer.snapPick(e);this.error("Scene.snapPick() canvasPos parameter expected")}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,i=e.length;t{if(e.collidable){const l=e.aabb;l[0]o&&(o=l[3]),l[4]>n&&(n=l[4]),l[5]>a&&(a=l[5]),t=!0}})),t){const e=d.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=o,e[4]=n,e[5]=a,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const i=e.visible!==t;return e.visible=t,i}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const i=e.collidable!==t;return e.collidable=t,i}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const i=e.culled!==t;return e.culled=t,i}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const i=e.selected!==t;return e.selected=t,i}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const i=e.highlighted!==t;return e.highlighted=t,i}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const i=e.xrayed!==t;return e.xrayed=t,i}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const i=e.edges!==t;return e.edges=t,i}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const i=e.opacity!==t;return e.opacity=t,i}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const i=e.pickable!==t;return e.pickable=t,i}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){y.isString(e)&&(e=[e]);let i=!1;for(let s=0,r=e.length;s{r>s&&(s=r,e(...i))}));return this._tickifiedFunctions[t]={tickSubId:n,wrapperFunc:o},o}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const bi=1e3,yi=1001,xi=1002,Bi=1003,wi=1004,Pi=1004,Ci=1005,Mi=1005,Ei=1006,Fi=1007,Ii=1007,Di=1008,Si=1008,Ti=1009,Ri=1010,Li=1011,Ui=1012,Oi=1013,ki=1014,Ni=1015,Qi=1016,Vi=1017,Hi=1018,ji=1020,Gi=1021,zi=1022,Wi=1023,Ki=1024,Xi=1025,Ji=1026,Yi=1027,Zi=1028,qi=1029,$i=1030,es=1031,ts=1033,is=33776,ss=33777,rs=33778,os=33779,ns=35840,as=35841,ls=35842,As=35843,hs=36196,cs=37492,us=37496,ds=37808,ps=37809,fs=37810,gs=37811,ms=37812,_s=37813,vs=37814,bs=37815,ys=37816,xs=37817,Bs=37818,ws=37819,Ps=37820,Cs=37821,Ms=36492,Es=3e3,Fs=3001,Is=1e4,Ds=10001,Ss=10002,Ts=10003,Rs=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene._lightsState,r=e._geometry._state,o=e._state.billboard,n=e._state.stationary,a=i.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,A=[];A.push("#version 300 es"),A.push("// Lambertian drawing vertex shader"),A.push("in vec3 position;"),A.push("uniform mat4 modelMatrix;"),A.push("uniform mat4 viewMatrix;"),A.push("uniform mat4 projMatrix;"),A.push("uniform vec4 colorize;"),A.push("uniform vec3 offset;"),l&&A.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(A.push("uniform float logDepthBufFC;"),A.push("out float vFragDepth;"),A.push("bool isPerspectiveMatrix(mat4 m) {"),A.push(" return (m[2][3] == - 1.0);"),A.push("}"),A.push("out float isPerspective;"));a&&A.push("out vec4 vWorldPosition;");if(A.push("uniform vec4 lightAmbient;"),A.push("uniform vec4 materialColor;"),A.push("uniform vec3 materialEmissive;"),r.normalsBuf){A.push("in vec3 normal;"),A.push("uniform mat4 modelNormalMatrix;"),A.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),A.push(" }"),A.push(" return normalize(v);"),A.push("}"))}A.push("out vec4 vColor;"),"points"===r.primitiveName&&A.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(A.push("void billboard(inout mat4 mat) {"),A.push(" mat[0][0] = 1.0;"),A.push(" mat[0][1] = 0.0;"),A.push(" mat[0][2] = 0.0;"),"spherical"===o&&(A.push(" mat[1][0] = 0.0;"),A.push(" mat[1][1] = 1.0;"),A.push(" mat[1][2] = 0.0;")),A.push(" mat[2][0] = 0.0;"),A.push(" mat[2][1] = 0.0;"),A.push(" mat[2][2] =1.0;"),A.push("}"));A.push("void main(void) {"),A.push("vec4 localPosition = vec4(position, 1.0); "),A.push("vec4 worldPosition;"),l&&A.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?A.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):A.push("vec4 localNormal = vec4(normal, 0.0); "),A.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),A.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));A.push("mat4 viewMatrix2 = viewMatrix;"),A.push("mat4 modelMatrix2 = modelMatrix;"),n&&A.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(A.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),A.push("billboard(modelMatrix2);"),A.push("billboard(viewMatrix2);"),A.push("billboard(modelViewMatrix);"),r.normalsBuf&&(A.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),A.push("billboard(modelNormalMatrix2);"),A.push("billboard(viewNormalMatrix2);"),A.push("billboard(modelViewNormalMatrix);")),A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&A.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(A.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),A.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),A.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=s.lights.length;e0,o=t.gammaOutput,n=[];n.push("#version 300 es"),n.push("// Lambertian drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));if(r){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}"points"===s.primitiveName&&(n.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push("float r = dot(cxy, cxy);"),n.push("if (r > 1.0) {"),n.push(" discard;"),n.push("}"));t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");o?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(e)):(this.vertex=function(e){const t=e.scene;e._material;const i=e._state,s=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=i.billboard,l=i.background,A=i.stationary,h=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),c=Os(e),u=s.getNumAllocatedSectionPlanes()>0,d=Us(e),p=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),p&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),u&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));o.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(c){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(let e=0,t=o.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}h&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),p&&f.push("uniform mat3 uvDecodeMatrix;"));r.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===r.primitiveName&&f.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = 1.0;"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===a&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = 1.0;"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(d){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(let e=0,t=o.lights.length;e0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(let e=0,t=o.lights.length;e0,l=Os(e),A=s.uvBuf,h="PhongMaterial"===n.type,c="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,d=Us(e);t.gammaInput;const p=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));d&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),p&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var g=0;g0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),o.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),h&&((o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = "+Ls[o.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(c||u)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),o.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+Ls[o.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),s.colors&&f.push("in vec4 vColor;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._occlusionMap||i._alphaMap)&&f.push("in vec2 vUV;");l&&(o.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));n.ambient&&f.push("uniform vec3 materialAmbient;");n.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==n.alpha&&null!==n.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");n.emissive&&f.push("uniform vec3 materialEmissive;");n.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==n.glossiness&&null!==n.glossiness&&f.push("uniform float materialGlossiness;");void 0!==n.shininess&&null!==n.shininess&&f.push("uniform float materialShininess;");n.specular&&f.push("uniform vec3 materialSpecular;");void 0!==n.metallic&&null!==n.metallic&&f.push("uniform float materialMetallic;");void 0!==n.roughness&&null!==n.roughness&&f.push("uniform float materialRoughness;");void 0!==n.specularF0&&null!==n.specularF0&&f.push("uniform float materialSpecularF0;");A&&i._ambientMap&&(f.push("uniform sampler2D ambientMap;"),i._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));A&&i._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),i._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));A&&i._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),i._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));A&&i._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),i._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&A&&i._metallicMap&&(f.push("uniform sampler2D metallicMap;"),i._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&A&&i._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),i._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&A&&i._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),i._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&i._normalMap&&(f.push("uniform sampler2D normalMap;"),i._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));A&&i._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),i._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));A&&i._alphaMap&&(f.push("uniform sampler2D alphaMap;"),i._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&A&&i._specularMap&&(f.push("uniform sampler2D specularMap;"),i._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&A&&i._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),i._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&A&&i._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),i._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(i._diffuseFresnel||i._specularFresnel||i._alphaFresnel||i._emissiveFresnel||i._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),i._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),i._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),i._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),i._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),i._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(let e=0,t=o.lights.length;e 0.0) { discard; }"),f.push("}")}"points"===s.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),n.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");n.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):n.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");s.colors&&f.push("diffuseColor *= vColor.rgb;");n.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");n.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==n.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");s.colors&&f.push("alpha *= vColor.a;");void 0!==n.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==n.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==n.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==n.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._occlusionMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));A&&i._ambientMap&&(i._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+Ls[i._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));A&&i._diffuseMap&&(i._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+Ls[i._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));A&&i._baseColorMap&&(i._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+Ls[i._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));A&&i._emissiveMap&&(i._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+Ls[i._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));A&&i._alphaMap&&(i._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));A&&i._occlusionMap&&(i._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(o.lights.length>0||o.lightMaps.length>0||o.reflectionMaps.length>0)){A&&i._normalMap?(i._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),A&&i._specularMap&&(i._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),A&&i._glossinessMap&&(i._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),A&&i._specularGlossinessMap&&(i._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),A&&i._metallicMap&&(i._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),A&&i._roughnessMap&&(i._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),A&&i._metallicRoughnessMap&&(i._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),i._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),i._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),i._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),i._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),h&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),u&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),c&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),o.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),h&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(u||c)&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(let e=0,t=o.lights.length;e0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(h=0,c=o.sectionPlanes.length;h0&&r.lightMaps[0].texture&&this._uLightMap&&(a.bindTexture(this._uLightMap,r.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),r.reflectionMaps.length>0&&r.reflectionMaps[0].texture&&this._uReflectionMap&&(a.bindTexture(this._uReflectionMap,r.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor),this._baseTextureUnit=e.textureUnit};class Hs{constructor(e){this.vertex=function(e){const t=e.scene,i=t._lightsState,s=function(e){const t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),r=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,o=!!e._geometry._state.compressGeometry,n=e._state.billboard,a=e._state.stationary,l=[];l.push("#version 300 es"),l.push("// EmphasisFillShaderSource vertex shader"),l.push("in vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),l.push("uniform vec3 offset;"),o&&l.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;"));r&&l.push("out vec4 vWorldPosition;");if(l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),s){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"))}l.push("out vec4 vColor;"),("spherical"===n||"cylindrical"===n)&&(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = 1.0;"),l.push(" mat[0][1] = 0.0;"),l.push(" mat[0][2] = 0.0;"),"spherical"===n&&(l.push(" mat[1][0] = 0.0;"),l.push(" mat[1][1] = 1.0;"),l.push(" mat[1][2] = 0.0;")),l.push(" mat[2][0] = 0.0;"),l.push(" mat[2][1] = 0.0;"),l.push(" mat[2][2] =1.0;"),l.push("}"));l.push("void main(void) {"),l.push("vec4 localPosition = vec4(position, 1.0); "),l.push("vec4 worldPosition;"),o&&l.push("localPosition = positionsDecodeMatrix * localPosition;");s&&(o?l.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):l.push("vec4 localNormal = vec4(normal, 0.0); "),l.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),l.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));l.push("mat4 viewMatrix2 = viewMatrix;"),l.push("mat4 modelMatrix2 = modelMatrix;"),a&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===n||"cylindrical"===n?(l.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),l.push("billboard(modelMatrix2);"),l.push("billboard(viewMatrix2);"),l.push("billboard(modelViewMatrix);"),s&&(l.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),l.push("billboard(modelNormalMatrix2);"),l.push("billboard(viewNormalMatrix2);"),l.push("billboard(modelViewNormalMatrix);")),l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),s)for(let e=0,t=i.lights.length;e0,o=[];o.push("#version 300 es"),o.push("// Lambertian drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}"points"===e._geometry._state.primitiveName&&(o.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("float r = dot(cxy, cxy);"),o.push("if (r > 1.0) {"),o.push(" discard;"),o.push("}"));t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const js=new e({}),Gs=d.vec3(),zs=function(e,t){this.id=js.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Hs(t),this._allocate(t)},Ws={};zs.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=Ws[t];return i||(i=new zs(t,e),Ws[t]=i,m.memory.programs++),i._useCount++,i},zs.prototype.put=function(){0==--this._useCount&&(js.removeItem(this.id),this._program&&this._program.destroy(),delete Ws[this._hash],m.memory.programs--)},zs.prototype.webglContextRestored=function(){this._program=null},zs.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl,n=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,A=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,A?e.getRTCViewMatrix(a.originHash,A):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Edges drawing vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec4 edgeColor;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));i&&n.push("out vec4 vWorldPosition;");n.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n.push("vColor = edgeColor;"),i&&n.push("vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.getNumAllocatedSectionPlanes()>0,o=[];o.push("#version 300 es"),o.push("// Edges drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const Xs=new e({}),Js=d.vec3(),Ys=function(e,t){this.id=Xs.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Ks(t),this._allocate(t)},Zs={};Ys.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=Zs[t];return i||(i=new Ys(t,e),Zs[t]=i,m.memory.programs++),i._useCount++,i},Ys.prototype.put=function(){0==--this._useCount&&(Xs.removeItem(this.id),this._program&&this._program.destroy(),delete Zs[this._hash],m.memory.programs--)},Ys.prototype.webglContextRestored=function(){this._program=null},Ys.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl;let n;const a=t._state,l=t._geometry,A=l._state,h=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(a.originHash,h):r.viewMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh picking vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("out vec4 vViewPosition;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("uniform vec2 pickClipPos;"),n.push("vec4 remapClipPos(vec4 clipPos) {"),n.push(" clipPos.xy /= clipPos.w;"),n.push(" clipPos.xy -= pickClipPos;"),n.push(" clipPos.xy *= clipPos.w;"),n.push(" return clipPos;"),n.push("}"),n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==r&&"cylindrical"!==r||(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"));n.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = remapClipPos(clipPos);"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(r.push("uniform vec4 pickColor;"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = pickColor; "),r.push("}"),r}(e)}}const $s=d.vec3(),er=function(e,t){this._hash=e,this._shaderSource=new qs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},tr={};er.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=tr[t];if(!i){if(i=new er(t,e),i.errors)return console.log(i.errors.join("\n")),null;tr[t]=i,m.memory.programs++}return i._useCount++,i},er.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete tr[this._hash],m.memory.programs--)},er.prototype.webglContextRestored=function(){this._program=null},er.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t>24&255,h=l>>16&255,c=l>>8&255,u=255&l;s.uniform4f(this._uPickColor,u/255,c/255,h/255,A/255),s.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(s.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&s.drawArrays(s.TRIANGLES,0,n.positions.numItems)},er.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Ze(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0,s=!!e._geometry._state.compressGeometry,r=[];r.push("#version 300 es"),r.push("// Surface picking vertex shader"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),i&&(r.push("uniform bool clippable;"),r.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));r.push("uniform vec2 pickClipPos;"),r.push("vec4 remapClipPos(vec4 clipPos) {"),r.push(" clipPos.xy /= clipPos.w;"),r.push(" clipPos.xy -= pickClipPos;"),r.push(" clipPos.xy *= clipPos.w;"),r.push(" return clipPos;"),r.push("}"),r.push("out vec4 vColor;"),s&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),s&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),i&&r.push(" vWorldPosition = worldPosition;");r.push(" vColor = color;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = remapClipPos(clipPos);"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Surface picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),r.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = vColor;"),r.push("}"),r}(e)}}const sr=d.vec3(),rr=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new ir(t),this._allocate(t)},or={};rr.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=or[t];if(!i){if(i=new rr(t,e),i.errors)return console.log(i.errors.join("\n")),null;or[t]=i,m.memory.programs++}return i._useCount++,i},rr.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete or[this._hash],m.memory.programs--)},rr.prototype.webglContextRestored=function(){this._program=null},rr.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,A=o.backfaces,h=o.frontface,c=i.camera.project,u=n._getPickTrianglePositions(),d=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,i.logarithmicDepthBufferEnabled){const e=2/(Math.log(c.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}if(s.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh occlusion vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push("}"),r}(e)}}const ar=d.vec3(),lr=function(e,t){this._hash=e,this._shaderSource=new nr(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ar={};lr.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let i=Ar[t];if(!i){if(i=new lr(t,e),i.errors)return console.log(i.errors.join("\n")),null;Ar[t]=i,m.memory.programs++}return i._useCount++,i},lr.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ar[this._hash],m.memory.programs--)},lr.prototype.webglContextRestored=function(){this._program=null},lr.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._material._state,o=t._state,n=t._geometry._state,a=t.origin;if(r.alpha<1)return;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){const t=r.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=r.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),this._lastMaterialId=r.id}const l=i.camera;if(s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!e._geometry._state.compressGeometry,s=[];s.push("// Mesh shadow vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),s.push("uniform vec3 offset;"),i&&s.push("uniform mat4 positionsDecodeMatrix;");t&&s.push("out vec4 vWorldPosition;");s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),s.push("vec4 worldPosition;"),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;");s.push("worldPosition = modelMatrix * localPosition;"),s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&s.push("vWorldPosition = worldPosition;");return s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(e)}}const cr=function(e,t){this._hash=e,this._shaderSource=new hr(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},ur={};cr.get=function(e){const t=e.scene,i=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=ur[i];if(!s){if(s=new cr(i,e),s.errors)return console.log(s.errors.join("\n")),null;ur[i]=s,m.memory.programs++}return s._useCount++,s},cr.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete ur[this._hash],m.memory.programs--)},cr.prototype.webglContextRestored=function(){this._program=null},cr.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene.canvas.gl,s=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.id!==this._lastMaterialId){const t=s.backfaces;e.backfaces!==t&&(t?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const r=s.frontface;e.frontface!==r&&(r?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=r),e.lineWidth!==s.lineWidth&&(i.lineWidth(s.lineWidth),e.lineWidth=s.lineWidth),this._uPointSize&&i.uniform1i(this._uPointSize,s.pointSize),this._lastMaterialId=s.id}if(i.uniformMatrix4fv(this._uModelMatrix,i.FALSE,t.worldMatrix),r.combineGeometry){const s=t.vertexBufs;s.id!==this._lastVertexBufsId&&(s.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(s.positionsBuf,s.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),this._lastVertexBufsId=s.id)}this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),i.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(i.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(i.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(i.drawArrays(i.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},cr.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Ze(i,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a0)for(let i=0;i0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const Pr=function(){const e=d.vec3(),t=d.vec3(),i=d.vec3(),s=d.vec3(),r=d.vec3(),o=d.vec3(),n=d.vec4(),a=d.vec3(),l=d.vec3(),A=d.vec3(),h=d.vec3(),c=d.vec3(),u=d.vec3(),p=d.vec3(),f=d.vec3(),g=d.vec3(),m=d.vec4(),_=d.vec4(),v=d.vec4(),b=d.vec3(),y=d.vec3(),x=d.vec3(),B=d.vec3(),w=d.vec3(),P=d.vec3(),C=d.vec3(),M=d.vec3(),E=d.vec3(),F=d.vec3(),I=d.vec3();return function(D,S,T,R,L){var U=L.primIndex;if(null!=U&&U>-1){const Q=D.geometry._state,V=D.scene,H=V.camera,j=V.canvas;if("triangles"===Q.primitiveName){L.primitive="triangle";const V=U,G=Q.indices,z=Q.positions;let W,K,X;if(G){var O=G[V+0],k=G[V+1],N=G[V+2];o[0]=O,o[1]=k,o[2]=N,L.indices=o,W=3*O,K=3*k,X=3*N}else W=3*V,K=W+3,X=K+3;if(i[0]=z[W+0],i[1]=z[W+1],i[2]=z[W+2],s[0]=z[K+0],s[1]=z[K+1],s[2]=z[K+2],r[0]=z[X+0],r[1]=z[X+1],r[2]=z[X+2],Q.compressGeometry){const e=Q.positionsDecodeMatrix;e&&(Zt.decompressPosition(i,e,i),Zt.decompressPosition(s,e,s),Zt.decompressPosition(r,e,r))}L.canvasPos?d.canvasPosToLocalRay(j.canvas,D.origin?J(S,D.origin):S,T,R,D.worldMatrix,L.canvasPos,e,t):L.origin&&L.direction&&d.worldRayToLocalRay(D.worldMatrix,L.origin,L.direction,e,t),d.normalizeVec3(t),d.rayPlaneIntersect(e,t,i,s,r,n),L.localPos=n,L.position=n,m[0]=n[0],m[1]=n[1],m[2]=n[2],m[3]=1,d.transformVec4(D.worldMatrix,m,_),a[0]=_[0],a[1]=_[1],a[2]=_[2],L.canvasPos&&D.origin&&(a[0]+=D.origin[0],a[1]+=D.origin[1],a[2]+=D.origin[2]),L.worldPos=a,d.transformVec4(H.matrix,_,v),l[0]=v[0],l[1]=v[1],l[2]=v[2],L.viewPos=l,d.cartesianToBarycentric(n,i,s,r,A),L.bary=A;const Y=Q.normals;if(Y){if(Q.compressGeometry){const e=3*O,t=3*k,i=3*N;Zt.decompressNormal(Y.subarray(e,e+2),h),Zt.decompressNormal(Y.subarray(t,t+2),c),Zt.decompressNormal(Y.subarray(i,i+2),u)}else h[0]=Y[W],h[1]=Y[W+1],h[2]=Y[W+2],c[0]=Y[K],c[1]=Y[K+1],c[2]=Y[K+2],u[0]=Y[X],u[1]=Y[X+1],u[2]=Y[X+2];const e=d.addVec3(d.addVec3(d.mulVec3Scalar(h,A[0],b),d.mulVec3Scalar(c,A[1],y),x),d.mulVec3Scalar(u,A[2],B),w);L.worldNormal=d.normalizeVec3(d.transformVec3(D.worldNormalMatrix,e,P))}const Z=Q.uv;if(Z){if(p[0]=Z[2*O],p[1]=Z[2*O+1],f[0]=Z[2*k],f[1]=Z[2*k+1],g[0]=Z[2*N],g[1]=Z[2*N+1],Q.compressGeometry){const e=Q.uvDecodeMatrix;e&&(Zt.decompressUV(p,e,p),Zt.decompressUV(f,e,f),Zt.decompressUV(g,e,g))}L.uv=d.addVec3(d.addVec3(d.mulVec2Scalar(p,A[0],C),d.mulVec2Scalar(f,A[1],M),E),d.mulVec2Scalar(g,A[2],F),I)}}}}}();function Cr(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);let s=e.height||1;s<0&&(console.error("negative height not allowed - will invert"),s*=-1);let r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<3&&(r=3);let o=e.heightSegments||1;o<0&&(console.error("negative heightSegments not allowed - will invert"),o*=-1),o<1&&(o=1);const n=!!e.openEnded;let a=e.center;const l=a?a[0]:0,A=a?a[1]:0,h=a?a[2]:0,c=s/2,u=s/o,d=2*Math.PI/r,p=1/r,f=(t-i)/o,g=[],m=[],_=[],v=[];let b,x,B,w,P,C,M,E,F,I,D;const S=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(b=0;b<=o;b++)for(P=t-b*f,C=c-b*u,x=0;x<=r;x++)B=Math.sin(x*d),w=Math.cos(x*d),m.push(P*B),m.push(S),m.push(P*w),_.push(x*p),_.push(1*b/o),g.push(P*B+l),g.push(C+A),g.push(P*w+h);for(b=0;b0){for(F=g.length/3,m.push(0),m.push(1),m.push(0),_.push(.5),_.push(.5),g.push(0+l),g.push(c+A),g.push(0+h),x=0;x<=r;x++)B=Math.sin(x*d),w=Math.cos(x*d),I=.5*Math.sin(x*d)+.5,D=.5*Math.cos(x*d)+.5,m.push(t*B),m.push(1),m.push(t*w),_.push(I),_.push(D),g.push(t*B+l),g.push(c+A),g.push(t*w+h);for(x=0;x0){for(F=g.length/3,m.push(0),m.push(-1),m.push(0),_.push(.5),_.push(.5),g.push(0+l),g.push(0-c+A),g.push(0+h),x=0;x<=r;x++)B=Math.sin(x*d),w=Math.cos(x*d),I=.5*Math.sin(x*d)+.5,D=.5*Math.cos(x*d)+.5,m.push(i*B),m.push(-1),m.push(i*w),_.push(I),_.push(D),g.push(i*B+l),g.push(0-c+A),g.push(i*w+h);for(x=0;x":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function Fr(e={}){var t=e.origin||[0,0,0],i=t[0],s=t[1],r=t[2],o=e.size||1,n=[],a=[],l=e.text;y.isNumeric(l)&&(l=""+l);for(var A,h,c,u,d,p,f,g,m,_=(l||"").split("\n"),v=0,b=0,x=.04,B=0;B<_.length;B++){A=0,c=(h=_[B]).length;for(var w=0;w0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let i=0,s=e.length;i1;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);const o=Jr(i,this.wrapS);o&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,o);const n=Jr(i,this.wrapT);if(n&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,n),this.type===i.TEXTURE_3D||this.type===i.TEXTURE_2D_ARRAY){const e=Jr(i,this.wrapR);e&&i.texParameteri(this.target,i.TEXTURE_WRAP_R,e),i.texParameteri(this.type,i.TEXTURE_WRAP_R,e)}r?(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,$r(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,$r(i,this.magFilter))):(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,Jr(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,Jr(i,this.magFilter)));const a=Jr(i,this.format,this.encoding),l=Jr(i,this.type),A=qr(i,this.internalFormat,a,l,this.encoding,!1);i.texStorage2D(i.TEXTURE_2D,s,A,e[0].width,e[0].height);for(let t=0,s=e.length;t>t;return e+1}class so extends R{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new _t({texture:new Zr({gl:this.scene.canvas.gl}),matrix:d.identityMat4(),hasMatrix:t.translate&&(0!==t.translate[0]||0!==t.translate[1])||!!t.rotate||t.scale&&(0!==t.scale[0]||0!==t.scale[1]),minFilter:this._checkMinFilter(t.minFilter),magFilter:this._checkMagFilter(t.magFilter),wrapS:this._checkWrapS(t.wrapS),wrapT:this._checkWrapT(t.wrapT),flipY:this._checkFlipY(t.flipY),encoding:this._checkEncoding(t.encoding)}),this._src=null,this._image=null,this._translate=d.vec2([0,0]),this._scale=d.vec2([1,1]),this._rotate=d.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),m.memory.textures++}_checkMinFilter(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}_checkMagFilter(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}_checkWrapS(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkWrapT(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this._state.texture=new Zr({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,i;0===this._translate[0]&&0===this._translate[1]||(t=d.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(i=d.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?d.mulMat4(t,i):i),0!==this._rotate&&(i=d.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?d.mulMat4(t,i):i),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=eo(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let i=new Image;i.onload=function(){i=eo(i),t._state.texture.setImage(i,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),m.memory.textures--}}class ro extends R{get type(){return"Fresnel"}constructor(e,t={}){super(e,t),this._state=new _t({edgeColor:d.vec3([0,0,0]),centerColor:d.vec3([1,1,1]),edgeBias:0,centerBias:1,power:1}),this.edgeColor=t.edgeColor,this.centerColor=t.centerColor,this.edgeBias=t.edgeBias,this.centerBias=t.centerBias,this.power=t.power}set edgeColor(e){this._state.edgeColor.set(e||[0,0,0]),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set centerColor(e){this._state.centerColor.set(e||[1,1,1]),this.glRedraw()}get centerColor(){return this._state.centerColor}set edgeBias(e){this._state.edgeBias=e||0,this.glRedraw()}get edgeBias(){return this._state.edgeBias}set centerBias(e){this._state.centerBias=null!=e?e:1,this.glRedraw()}get centerBias(){return this._state.centerBias}set power(e){this._state.power=null!=e?e:1,this.glRedraw()}get power(){return this._state.power}destroy(){super.destroy(),this._state.destroy()}}const oo=m.memory,no=d.AABB3();class ao extends jt{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new _t({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._aabb=null,this._obb=d.OBB3();const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=Zt.getPositionsBounds(t.positions),o=Zt.compressPositions(t.positions,e.min,e.max);r=o.quantized,i.positionsDecodeMatrix=o.decodeMatrix,i.positionsBuf=new qe(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),oo.positions+=i.positionsBuf.numItems,d.positions3ToAABB3(t.positions,this._aabb),d.positions3ToAABB3(r,no,i.positionsDecodeMatrix),d.AABB3ToOBB3(no,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);i.colorsBuf=new qe(s,s.ARRAY_BUFFER,e,e.length,4,s.STATIC_DRAW),oo.colors+=i.colorsBuf.numItems}if(t.uv){const e=Zt.getUVBounds(t.uv),r=Zt.compressUVs(t.uv,e.min,e.max),o=r.quantized;i.uvDecodeMatrix=r.decodeMatrix,i.uvBuf=new qe(s,s.ARRAY_BUFFER,o,o.length,2,s.STATIC_DRAW),oo.uvs+=i.uvBuf.numItems}if(t.normals){const e=Zt.compressNormals(t.normals);let r=i.compressGeometry;i.normalsBuf=new qe(s,s.ARRAY_BUFFER,e,e.length,3,s.STATIC_DRAW,r),oo.normals+=i.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);i.indicesBuf=new qe(s,s.ELEMENT_ARRAY_BUFFER,e,e.length,1,s.STATIC_DRAW),oo.indices+=i.indicesBuf.numItems;const o=Gt(r,e,i.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new qe(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),oo.meshes++}else this.error("Config expected: indices");else this.error("Config expected: positions")}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positionsBuf&&t.push("p"),e.colorsBuf&&t.push("c"),(e.normalsBuf||e.autoVertexNormals)&&t.push("n"),e.uvBuf&&t.push("u"),t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf}get primitive(){return this._state.primitiveName}get aabb(){return this._aabb}get obb(){return this._obb}get numTriangles(){return this._numTriangles}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),e.destroy(),oo.meshes--}}var lo={};function Ao(e,t={}){return new Promise((function(i,s){t.src||(console.error("load3DSGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,y.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("load3DSGeometry: no data loaded"),r.processes--,s());var o=lo.parse.from3DS(e).edit.objects[0].mesh,n=o.vertices,a=o.uvt,l=o.indices;r.processes--,i(y.apply(t,{primitive:"triangles",positions:n,normals:null,uv:a,indices:l}))}),(function(e){console.error("load3DSGeometry: "+e),r.processes--,s()}))}))}function ho(e,t={}){return new Promise((function(i,s){t.src||(console.error("loadOBJGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,y.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("loadOBJGeometry: no data loaded"),r.processes--,s());for(var o=lo.parse.fromOBJ(e),n=lo.edit.unwrap(o.i_verts,o.c_verts,3),a=lo.edit.unwrap(o.i_norms,o.c_norms,3),l=lo.edit.unwrap(o.i_uvt,o.c_uvt,2),A=new Int32Array(o.i_verts.length),h=0;h0?a:null,autoNormals:0===a.length,uv:l,indices:A}))}),(function(e){console.error("loadOBJGeometry: "+e),r.processes--,s()}))}))}function co(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return y.apply(e,{primitive:"lines",positions:[l,A,h,l,A,d,l,u,h,l,u,d,c,A,h,c,A,d,c,u,h,c,u,d],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function uo(e={}){return co({id:e.id,center:[(e.aabb[0]+e.aabb[3])/2,(e.aabb[1]+e.aabb[4])/2,(e.aabb[2]+e.aabb[5])/2],xSize:Math.abs(e.aabb[3]-e.aabb[0])/2,ySize:Math.abs(e.aabb[4]-e.aabb[1])/2,zSize:Math.abs(e.aabb[5]-e.aabb[2])/2})}function po(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let i=e.divisions||1;i<0&&(console.error("negative divisions not allowed - will invert"),i*=-1),i<1&&(i=1),t=t||10,i=i||10;const s=t/i,r=t/2,o=[],n=[];let a=0;for(let e=0,t=-r;e<=i;e++,t+=s)o.push(-r),o.push(0),o.push(t),o.push(r),o.push(0),o.push(t),o.push(t),o.push(0),o.push(-r),o.push(t),o.push(0),o.push(r),n.push(a++),n.push(a++),n.push(a++),n.push(a++);return y.apply(e,{primitive:"lines",positions:o,indices:n})}function fo(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);let s=e.xSegments||1;s<0&&(console.error("negative xSegments not allowed - will invert"),s*=-1),s<1&&(s=1);let r=e.xSegments||1;r<0&&(console.error("negative zSegments not allowed - will invert"),r*=-1),r<1&&(r=1);const o=e.center,n=o?o[0]:0,a=o?o[1]:0,l=o?o[2]:0,A=t/2,h=i/2,c=Math.floor(s)||1,u=Math.floor(r)||1,d=c+1,p=u+1,f=t/c,g=i/u,m=new Float32Array(d*p*3),_=new Float32Array(d*p*3),v=new Float32Array(d*p*2);let b,x,B,w,P,C,M,E=0,F=0;for(b=0;b65535?Uint32Array:Uint16Array)(c*u*6);for(b=0;b360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const A=n?n[2]:0,h=[],c=[],u=[],p=[];let f,g,m,_,v,b,x,B,w,P,C,M;for(B=0;B<=r;B++)for(x=0;x<=s;x++)f=x/s*o,g=.785398+B/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),m=(t+i*Math.cos(g))*Math.cos(f),_=(t+i*Math.cos(g))*Math.sin(f),v=i*Math.sin(g),h.push(m+a),h.push(_+l),h.push(v+A),u.push(1-x/s),u.push(B/r),b=d.normalizeVec3(d.subVec3([m,_,v],[a,l,A],[]),[]),c.push(b[0]),c.push(b[1]),c.push(b[2]);for(B=1;B<=r;B++)for(x=1;x<=s;x++)w=(s+1)*B+x-1,P=(s+1)*(B-1)+x-1,C=(s+1)*(B-1)+x,M=(s+1)*B+x,p.push(w),p.push(P),p.push(C),p.push(C),p.push(M),p.push(w);return y.apply(e,{positions:h,normals:c,uv:u,indices:p})}function mo(e={}){if(e.points.length%3!=0)throw"Size of points array for given polyline should be divisible by 3";let t=e.points.length/3;if(t<2)throw"There should be at least 2 points to create a polyline";let i=[];for(let e=0;e[...e])).flat();return mo({id:e.id,points:t})}function vo(e={}){if(3!==e.startPoint.length)throw"Start point should contain 3 elements in array: x, y and z";if(3!==e.endPoint.length)throw"End point should contain 3 elements in array: x, y and z";let t=[],i=[],s=e.startPoint[0],r=e.startPoint[1],o=e.startPoint[2],n=e.endPoint[0],a=e.endPoint[1],l=e.endPoint[2],A=Math.sqrt((n-s)**2+(a-r)**2+(l-o)**2),h=[(n-s)/A,(a-r)/A,(l-o)/A];if(e.pattern){let c=e.pattern.length,u=!1,d=0,p=0,f=0,g=[s,r,o],m=e.pattern[p];for(i.push(g[0],g[1],g[2]);m<=A-d;){let s=[h[0]*m,h[1]*m,h[2]*m],r=[g[0]+s[0],g[1]+s[1],g[2]+s[2]];i.push(r[0],r[1],r[2]),u||(t.push(f),t.push(f+1)),u=!u,f+=1,g=r,p+=1,p>=c&&(p=0),d+=m,m=e.pattern[p]}e.extendToEnd&&(i.push(n,a,l),t.push(t.length-2),t.push(t.length-1))}else t.push(0),t.push(1),i.push(s,r,o,n,a,l);return y.apply(e,{primitive:"lines",positions:i,indices:t})}lo.load=function(e,t){var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=function(e){t(e.target.response)},i.send()},lo.save=function(e,t){var i="data:application/octet-stream;base64,"+btoa(lo.parse._buffToStr(e));window.location.href=i},lo.clone=function(e){return JSON.parse(JSON.stringify(e))},lo.bin={},lo.bin.f=new Float32Array(1),lo.bin.fb=new Uint8Array(lo.bin.f.buffer),lo.bin.rf=function(e,t){for(var i=lo.bin.f,s=lo.bin.fb,r=0;r<4;r++)s[r]=e[t+r];return i[0]},lo.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},lo.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},lo.bin.rASCII0=function(e,t){for(var i="";0!=e[t];)i+=String.fromCharCode(e[t++]);return i},lo.bin.wf=function(e,t,i){new Float32Array(e.buffer,t,1)[0]=i},lo.bin.wsl=function(e,t,i){e[t]=i,e[t+1]=i>>8},lo.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},lo.parse={},lo.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",s=0;sr&&(r=l),Ao&&(o=A),hn&&(n=h)}return{min:{x:t,y:i,z:s},max:{x:r,y:o,z:n}}};class bo extends R{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=d.vec3(t.pos||[0,0,0]),this._up=d.vec3(t.up||[0,1,0]),this._normal=d.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=d.vec3(),this._rtcPos=d.vec3(),this._imageSize=d.vec2(),this._texture=new so(this,{flipY:!0}),this._image=new Image,"jpg"!==this._type&&"png"!==this._type&&(this.error('Unsupported type - defaulting to "jpg"'),this._type="jpg"),this._node=new Vr(this,{matrix:d.inverseMat4(d.lookAtMat4v(this._pos,d.subVec3(this._pos,this._normal,d.mat4()),this._up,d.mat4())),children:[this._bitmapMesh=new wr(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new ei(this,fo({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new oi(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0})})]}),t.image?this.image=t.image:t.src?this.src=t.src:t.imageData&&(this.imageData=t.imageData),this.scene._bitmapCreated(this)}set visible(e){this._bitmapMesh.visible=e}get visible(){return this._bitmapMesh.visible}set image(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}get image(){return this._image}set src(e){if(e){this._image.onload=()=>{this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale()},this._image.src=e;switch(e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}}get src(){return this._image.src}set imageData(e){this._image.onload=()=>{this._texture.image=image,this._imageSize[0]=image.width,this._imageSize[1]=image.height,this._updateBitmapMeshScale()},this._image.src=e}get imageData(){const e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")}set type(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}get type(){return this._type}get pos(){return this._pos}get normal(){return this._normal}get up(){return this._up}set height(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}get height(){return this._height}set collidable(e){this._bitmapMesh.collidable=!1!==e}get collidable(){return this._bitmapMesh.collidable}set clippable(e){this._bitmapMesh.clippable=!1!==e}get clippable(){return this._bitmapMesh.clippable}set pickable(e){this._bitmapMesh.pickable=!1!==e}get pickable(){return this._bitmapMesh.pickable}set opacity(e){this._bitmapMesh.opacity=e}get opacity(){return this._bitmapMesh.opacity}destroy(){super.destroy(),this.scene._bitmapDestroyed(this)}_updateBitmapMeshScale(){const e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height/e,1,this._height]}}const yo=(e,t)=>{const i=[];let s=[];function r(e,i){let s,r;for(let o=0;o<3;o++)if(s=t[3*e+o],r=t[3*i+o],s!==r)return r-s;return 0}let o=e.slice().sort(r),n=null;for(let e=0,t=o.length;eo&&r>n?o>n?(a=r,l=o,A=n):(a=r,l=n,A=o):o>r&&o>n?r>n?(a=o,l=r,A=n):(a=o,l=n,A=r):n>r&&n>o&&(r>o?(a=n,l=r,A=o):(a=n,l=o,A=r)),s[t+0]=[a,l],s[t+1]=[l,A],a>A){const e=A;A=a,a=e}s[t+2]=[A,a]}function a(e,t){let i,s;for(let r=0;r<2;r++)if(i=e[r],s=t[r],s!==i)return s-i;return 0}s=s.slice(0,e.length),s.sort(a);let l=0;for(let e=0;e0&&2!==l)},xo=d.vec3(),Bo=d.vec3(),wo=d.vec3();class Po{constructor(){this.vertices=[],this.indices=[],this.reset()}reset(){this.lenVertices=0,this.lenIndices=0,this.primitive=null}setPrimitive(e){this.primitive=e}addVertex(e){this.vertices[this.lenVertices++]=e[0],this.vertices[this.lenVertices++]=e[1],this.vertices[this.lenVertices++]=e[2]}addIndex(e){this.indices[this.lenIndices++]=e}get volume(){const e=this.vertices,t=this.indices;if("solid"!==this.primitive&&"surface"!==this.primitive&&"triangles"!==this.primitive)return-1;if("solid"!==this.primitive&&!yo(t,e))return-1;let i=0;for(let s=0;s{Co.addVertex(e)})),this.getEachIndex((e=>{Co.addIndex(e)})),this._volume=Co.volume;break;default:this._volume=0}return this._volume}get surfaceArea(){if(null!==this._surfaceArea)return this._surfaceArea;switch(this.layer.primitive){case"solid":case"surface":case"triangles":Ro.reset(),this.getEachVertex((e=>{Ro.addVertex(e)})),this.getEachIndex((e=>{Ro.addIndex(e)})),this._surfaceArea=Ro.surfaceArea;break;default:this._surfaceArea=0}return this._surfaceArea}set aabb(e){if(this._aabbLocal=e,this.origin){this._aabbLocal=e.slice(0);const t=this.origin;this._aabbLocal[0]+=t[0],this._aabbLocal[1]+=t[1],this._aabbLocal[2]+=t[2],this._aabbLocal[3]+=t[0],this._aabbLocal[4]+=t[1],this._aabbLocal[5]+=t[2]}}get aabb(){return this._aabbWorldDirty&&(d.AABB3ToOBB3(this._aabbLocal,Lo),this.transform?(d.transformOBB3(this.transform.worldMatrix,Lo,Uo),d.transformOBB3(this.model.worldMatrix,Uo,Oo),d.OBB3ToAABB3(Oo,this._aabbWorld)):(d.transformOBB3(this.model.worldMatrix,Lo,Uo),d.OBB3ToAABB3(Uo,this._aabbWorld)),this._aabbWorldDirty=!1),this._aabbWorld}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const No=new class{constructor(){this._uint8Arrays={},this._float32Arrays={}}_clear(){this._uint8Arrays={},this._float32Arrays={}}getUInt8Array(e){let t=this._uint8Arrays[e];return t||(t=new Uint8Array(e),this._uint8Arrays[e]=t),t}getFloat32Array(e){let t=this._float32Arrays[e];return t||(t=new Float32Array(e),this._float32Arrays[e]=t),t}};let Qo=0;const Vo={NOT_RENDERED:0,COLOR_OPAQUE:1,COLOR_TRANSPARENT:2,SILHOUETTE_HIGHLIGHTED:3,SILHOUETTE_SELECTED:4,SILHOUETTE_XRAYED:5,EDGES_COLOR_OPAQUE:6,EDGES_COLOR_TRANSPARENT:7,EDGES_HIGHLIGHTED:8,EDGES_SELECTED:9,EDGES_XRAYED:10,PICK:11},Ho=new Float32Array([1,1,1,1]),jo=new Float32Array([0,0,0,1]),Go=d.vec4(),zo=d.vec3(),Wo=d.vec3(),Ko=d.mat4();class Xo{constructor(e,t=!1,{instancing:i=!1,edges:s=!1,useAlphaCutoff:r=!1}={}){this._scene=e,this._withSAO=t,this._instancing=i,this._edges=s,this._useAlphaCutoff=r,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}_getHash(){return this._scene._sectionPlanesState.getHash()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){return[""]}_buildFragmentShader(){return[""]}_addMatricesUniformBlockLines(e,t=!1){return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}_addRemapClipPosLines(e,t=1){return e.push("uniform vec2 drawingBufferSize;"),e.push("uniform vec2 pickClipPos;"),e.push("vec4 remapClipPos(vec4 clipPos) {"),e.push(" clipPos.xy /= clipPos.w;"),1===t?e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"):e.push(` clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(${t}));`),e.push(" clipPos.xy *= clipPos.w;"),e.push(" return clipPos;"),e.push("}"),e}getValid(){return this._hash===this._getHash()}setSectionPlanesStateUniforms(e){const t=this._scene,{gl:i}=t.canvas,{model:s,layerIndex:r}=e,o=t._sectionPlanesState.getNumAllocatedSectionPlanes(),n=t._sectionPlanesState.sectionPlanes.length;if(o>0){const a=t._sectionPlanesState.sectionPlanes,l=r*n,A=s.renderFlags;t.crossSections&&(i.uniform4fv(this._uSliceColor,t.crossSections.sliceColor),i.uniform1f(this._uSliceThickness,t.crossSections.sliceThickness));for(let t=0;t0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0&&p.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,p.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),p.lightMaps.length>0&&p.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,p.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const i=a.drawingBufferWidth,s=a.drawingBufferHeight;Go[0]=i,Go[1]=s,Go[2]=t.blendCutoff,Go[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,Go),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(this._useAlphaCutoff&&a.uniform1f(this._alphaCutoffLocation,h.alphaCutoff),s){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(i===Vo[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const i=n.xrayMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===Vo[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const i=n.highlightMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===Vo[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const i=n.selectedMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else a.uniform4fv(this._uColor,this._edges?jo:Ho)}this._draw({state:l,frameCtx:e,incrementDrawState:r}),a.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,m.memory.programs--}}class Jo extends Xo{constructor(e,t,{edges:i=!1,useAlphaCutoff:s=!1}={}){super(e,t,{instancing:!1,edges:i,useAlphaCutoff:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;if(this._edges)t.drawElements(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0);else{const e=s.pickElementsCount||i.indicesBuf.numItems,o=s.pickElementsOffset?s.pickElementsOffset*i.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,i.indicesBuf.itemType,o),r&&s.drawElements++}}}class Yo extends Jo{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r;const o=[];o.push("#version 300 es"),o.push("// Triangles batching draw vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;")),o.push("out vec4 vColor;"),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching draw fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class Zo extends Jo{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._lightsState,i=e._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching flat-shading draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),s){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e sliceThickness) { "),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" newColor = sliceColor;"),r.push(" }"),r.push("}")}r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;"),r.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),r.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),r.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,i=t.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching silhouette fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r){for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" newColor = sliceColor;"),o.push(" }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = newColor;"),o.push("}"),o}}class $o extends Jo{constructor(e){super(e,!1,{instancing:!1,edges:!0})}}class en extends $o{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class tn extends $o{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class sn extends Jo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class rn extends Jo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class on extends Jo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec3 worldNormal = octDecode(normal.xy); "),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class nn extends Jo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching occlusion vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class an extends Jo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching depth fragment shader"),s.push("precision highp float;"),s.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),s.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),s.push("}"),s}}class ln extends Jo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class An extends Jo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry shadow vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" int colorFlag = int(flags) & 0xF;"),i.push(" bool visible = (colorFlag > 0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}}class hn extends Jo{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Triangles batching quality draw vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),o.push("vFragDepth = 1.0 + clipPos.w;")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Triangles batching quality draw fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),n.push("uniform sampler2D uAOMap;"),n.push("in vec4 vViewPosition;"),n.push("in vec3 vViewNormal;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("in vec2 vMetallicRoughness;"),s.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick flat normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick flat normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class un extends Jo{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching color texture vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=this._useAlphaCutoff,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching color texture fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const vn=d.vec3(),bn=d.vec3(),yn=d.vec3(),xn=d.vec3(),Bn=d.mat4();class wn extends Xo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=vn;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=bn;if(l){const e=yn;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=J(p,t,Bn),m=xn,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElements(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Pn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._colorTextureRendererAlphaCutoff&&!this._colorTextureRendererAlphaCutoff.getValid()&&(this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererAlphaCutoff=null),this._colorTextureRendererWithSAOAlphaCutoff&&!this._colorTextureRendererWithSAOAlphaCutoff.getValid()&&(this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new qo(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new sn(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new rn(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new _n(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new wn(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Yo(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Yo(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Zo(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Zo(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new un(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new un(this._scene,!0)),this._colorTextureRendererWithSAO}get colorTextureRendererAlphaCutoff(){return this._colorTextureRendererAlphaCutoff||(this._colorTextureRendererAlphaCutoff=new un(this._scene,!1,{useAlphaCutoff:!0})),this._colorTextureRendererAlphaCutoff}get colorTextureRendererWithSAOAlphaCutoff(){return this._colorTextureRendererWithSAOAlphaCutoff||(this._colorTextureRendererWithSAOAlphaCutoff=new un(this._scene,!0,{useAlphaCutoff:!0})),this._colorTextureRendererWithSAOAlphaCutoff}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new hn(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new hn(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new qo(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new an(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new ln(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new en(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new tn(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new sn(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new on(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new cn(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new rn(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new nn(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new An(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new wn(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new _n(this._scene)),this._snapInitRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererAlphaCutoff&&this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff&&this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Cn={};let Mn=65536,En=5e6;class Fn{constructor(){}set doublePrecisionEnabled(e){d.setDoublePrecisionEnabled(e)}get doublePrecisionEnabled(){return d.getDoublePrecisionEnabled()}set maxDataTextureHeight(e){(e=1024*Math.ceil(e/1024))>4096?e=4096:e<1024&&(e=1024),Mn=e}get maxDataTextureHeight(){return Mn}set maxGeometryBatchSize(e){e<1e5?e=1e5:e>5e6&&(e=5e6),En=e}get maxGeometryBatchSize(){return En}}const In=new Fn;class Dn{constructor(e=In.maxGeometryBatchSize){this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const Sn=d.mat4(),Tn=d.mat4();function Rn(e,t,i){const s=e.length,r=new Uint16Array(s),o=t[0],n=t[1],a=t[2],l=t[3]-o,A=t[4]-n,h=t[5]-a,c=65525,u=c/l,p=c/A,f=c/h,g=e=>e>=0?e:0;for(let t=0;t=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 On(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}const kn=d.mat4(),Nn=d.mat4(),Qn=d.vec4([0,0,0,1]),Vn=d.vec3(),Hn=d.vec3(),jn=d.vec3(),Gn=d.vec3(),zn=d.vec3(),Wn=d.vec3(),Kn=d.vec3();class Xn{constructor(e){this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Cn[t];return i||(i=new Pn(e),Cn[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Cn[t],i._destroy()}))),i}(e.model.scene),this._buffer=new Dn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new _t({origin:d.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:e.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=d.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=d.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=d.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.solid=!!e.solid,this.primitive=e.primitive}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)for(let e=0,t=o.length;e0){const e=kn;m?d.inverseMat4(d.transposeMat4(m,Nn),e):d.identityMat4(e,e),function(e,t,i,s,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,A,h,c,u=new Float32Array([0,0,0,0]),p=new Float32Array([0,0,0,0]);for(c=0;ch&&(l=n,h=A),n=Un(p,"floor","ceil"),a=On(n),A=o(p,a),A>h&&(l=n,h=A),n=Un(p,"ceil","ceil"),a=On(n),A=o(p,a),A>h&&(l=n,h=A),s[r+c+0]=l[0],s[r+c+1]=l[1],s[r+c+2]=0}(e,r,r.length,b.normals,b.normals.length)}if(l)for(let e=0,t=l.length;e0)for(let e=0,t=n.length;e0)for(let e=0,t=a.length;e0){const s=this._state.positionsDecodeMatrix?new Uint16Array(i.positions):Rn(i.positions,this._modelAABB,this._state.positionsDecodeMatrix=d.mat4());if(e.positionsBuf=new qe(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this.model.scene.readableGeometryEnabled)for(let e=0,t=this._portions.length;e0){const s=new Int8Array(i.normals);let r=!0;e.normalsBuf=new qe(t,t.ARRAY_BUFFER,s,i.normals.length,3,t.STATIC_DRAW,r)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new qe(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.uv.length>0)if(e.uvDecodeMatrix){let s=!1;e.uvBuf=new qe(t,t.ARRAY_BUFFER,i.uv,i.uv.length,2,t.STATIC_DRAW,s)}else{const s=Zt.getUVBounds(i.uv),r=Zt.compressUVs(i.uv,s.min,s.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=d.mat3(r.decodeMatrix),e.uvBuf=new qe(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(i.metallicRoughness.length>0){const s=new Uint8Array(i.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new qe(t,t.ARRAY_BUFFER,s,i.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s),o=!1;e.flagsBuf=new qe(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new qe(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new qe(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new qe(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){const s=new Uint32Array(i.edgeIndices);e.edgeIndicesBuf=new qe(t,t.ELEMENT_ARRAY_BUFFER,s,i.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,i){t&ee&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ne&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&oe&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ae&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&se&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&le&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ie&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&te&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ae?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&le?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&se?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=e,s=this._portions[i],r=4*s.vertsBaseIndex,o=4*s.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],A=t[2],h=t[3];for(let e=0;e_)&&(_=e,s.set(v),r&&d.triangleNormal(p,f,g,r),m=!0)}}return m&&r&&(d.transformVec3(this.model.worldNormalMatrix,r,r),d.normalizeVec3(r)),m}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}class Jn extends Xo{constructor(e,t,{edges:i=!1,useAlphaCutoff:s=!1}={}){super(e,t,{instancing:!0,edges:i,useAlphaCutoff:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;this._edges?t.drawElementsInstanced(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0,i.numInstances):(t.drawElementsInstanced(t.TRIANGLES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),r&&s.drawElements++)}}class Yn extends Jn{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r,o,n;const a=[];for(a.push("#version 300 es"),a.push("// Instancing geometry drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec2 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;"),r=0,o=i.lights.length;r= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),s&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),a.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),r=0,o=i.lights.length;r0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class Zn extends Jn{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry flat-shading drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState;let s,r;const o=t.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry flat-shading drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),o){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}for(n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),s=0,r=i.lights.length;s0,i=[];return i.push("#version 300 es"),i.push("// Instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing fill fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = newColor;"),s.push("}"),s}}class $n extends Jn{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class ea extends $n{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class ta extends $n{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesColorRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class ia extends Jn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class sa extends Jn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class ra extends Jn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec2 normal;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("in vec4 modelNormalMatrixCol0;"),i.push("in vec4 modelNormalMatrixCol1;"),i.push("in vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class oa extends Jn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class na extends Jn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Instancing geometry depth drawing fragment shader"),o.push("precision highp float;"),o.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),o.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),o.push("}"),o}}class aa extends Jn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class la extends Jn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const Aa={3e3:"linearToLinear",3001:"sRGBToLinear"};class ha extends Jn{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Instancing geometry quality drawing vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),o.push("in vec4 modelMatrixCol0;"),o.push("in vec4 modelMatrixCol1;"),o.push("in vec4 modelMatrixCol2;"),o.push("in vec4 modelNormalMatrixCol0;"),o.push("in vec4 modelNormalMatrixCol1;"),o.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),o.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),o.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Instancing geometry quality drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),n.push("#define PI 3.14159265359"),n.push("#define RECIPROCAL_PI 0.31830988618"),n.push("#define RECIPROCAL_PI2 0.15915494"),n.push("#define EPSILON 1e-6"),n.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),n.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),n.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),n.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),n.push(" return normalize(surf_norm );"),n.push(" }"),n.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),n.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),n.push(" vec2 st0 = dFdx( uv.st );"),n.push(" vec2 st1 = dFdy( uv.st );"),n.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),n.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),n.push(" vec3 N = normalize( surf_norm );"),n.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),n.push(" mat3 tsn = mat3( S, T, N );"),n.push(" return normalize( tsn * mapN );"),n.push("}"),n.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),n.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),n.push("}"),n.push("struct IncidentLight {"),n.push(" vec3 color;"),n.push(" vec3 direction;"),n.push("};"),n.push("struct ReflectedLight {"),n.push(" vec3 diffuse;"),n.push(" vec3 specular;"),n.push("};"),n.push("struct Geometry {"),n.push(" vec3 position;"),n.push(" vec3 viewNormal;"),n.push(" vec3 worldNormal;"),n.push(" vec3 viewEyeDir;"),n.push("};"),n.push("struct Material {"),n.push(" vec3 diffuseColor;"),n.push(" float specularRoughness;"),n.push(" vec3 specularColor;"),n.push(" float shine;"),n.push("};"),n.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),n.push(" float r = ggxRoughness + 0.0001;"),n.push(" return (2.0 / (r * r) - 2.0);"),n.push("}"),n.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),n.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),n.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),n.push("}"),s.reflectionMaps.length>0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = "+Aa[s.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = "+Aa[s.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&i.push("out float vFlags;"),i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&i.push("vFlags = flags;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class ua extends Jn{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=this._useAlphaCutoff,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const va=d.vec3(),ba=d.vec3(),ya=d.vec3(),xa=d.vec3(),Ba=d.mat4();class wa extends Xo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=va;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=ba;if(l){const e=d.transformPoint3(h,l,ya);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=J(p,t,Ba),m=xa,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0,a.numInstances),a.edgeIndicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Pa{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._colorTextureRendererAlphaCutoff&&!this._colorTextureRendererAlphaCutoff.getValid()&&(this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererAlphaCutoff=null),this._colorTextureRendererWithSAOAlphaCutoff&&!this._colorTextureRendererWithSAOAlphaCutoff.getValid()&&(this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new qn(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new ia(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new sa(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new _a(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new wa(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Yn(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Yn(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Zn(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Zn(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new ua(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new ua(this._scene,!0)),this._colorTextureRendererWithSAO}get colorTextureRendererAlphaCutoff(){return this._colorTextureRendererAlphaCutoff||(this._colorTextureRendererAlphaCutoff=new ua(this._scene,!1,{useAlphaCutoff:!0})),this._colorTextureRendererAlphaCutoff}get colorTextureRendererWithSAOAlphaCutoff(){return this._colorTextureRendererWithSAOAlphaCutoff||(this._colorTextureRendererWithSAOAlphaCutoff=new ua(this._scene,!0,{useAlphaCutoff:!0})),this._colorTextureRendererWithSAOAlphaCutoff}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new ha(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new ha(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new qn(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new na(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new aa(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new ea(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new ta(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new ia(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new ra(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new ca(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new sa(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new oa(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new la(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new wa(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new _a(this._scene)),this._snapInitRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererAlphaCutoff&&this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff&&this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Ca={};const Ma=new Uint8Array(4),Ea=new Float32Array(1),Fa=d.vec4([0,0,0,1]),Ia=new Float32Array(3),Da=d.vec3(),Sa=d.vec3(),Ta=d.vec3(),Ra=d.vec3(),La=d.vec3(),Ua=d.vec3(),Oa=d.vec3(),ka=new Float32Array(4);class Na{constructor(e){this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Ca[t];return i||(i=new Pa(e),Ca[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Ca[t],i._destroy()}))),i}(e.model.scene),this._aabb=d.collapseAABB3(),this._state=new _t({numInstances:0,obb:d.OBB3(),origin:d.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrix=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.solid=!!e.solid,this.numIndices=e.geometry.numIndices,this.primitive=e.geometry.primitive}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;e.colorsBuf=new qe(s,s.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,s.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let i=!1;e.metallicRoughnessBuf=new qe(s,s.ARRAY_BUFFER,t,this._metallicRoughness.length,2,s.STATIC_DRAW,i)}if(o>0){let t=!1;e.flagsBuf=new qe(s,s.ARRAY_BUFFER,new Float32Array(o),o,1,s.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new qe(s,s.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,s.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const i=!1;e.positionsBuf=new qe(s,s.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,s.STATIC_DRAW,i),e.positionsDecodeMatrix=d.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const i=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new qe(s,s.ARRAY_BUFFER,i,i.length,4,s.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const i=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new qe(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new qe(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,s.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new qe(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,s.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelMatrixCol1Buf=new qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelMatrixCol2Buf=new qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new qe(s,s.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,s.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&i&&i.colorTexture&&i.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!i&&!!i.colorTexture,this.model.scene.readableGeometryEnabled||(this._state.geometry=null),this._finalized=!0}initFlags(e,t,i){t&ee&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ne&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&oe&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ae&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&se&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&le&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ie&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&te&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ae?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&le?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&se?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";Ma[0]=t[0],Ma[1]=t[1],Ma[2]=t[2],Ma[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(Ma,4*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&ee),r=!!(t&oe),o=!!(t&ne),n=!!(t&ae),a=!!(t&le),l=!!(t&ie),A=!!(t&te);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Vo.NOT_RENDERED:i?Vo.COLOR_TRANSPARENT:Vo.COLOR_OPAQUE,c=!s||A?Vo.NOT_RENDERED:n?Vo.SILHOUETTE_SELECTED:o?Vo.SILHOUETTE_HIGHLIGHTED:r?Vo.SILHOUETTE_XRAYED:Vo.NOT_RENDERED;let u=0;u=!s||A?Vo.NOT_RENDERED:n?Vo.EDGES_SELECTED:o?Vo.EDGES_HIGHLIGHTED:r?Vo.EDGES_XRAYED:a?i?Vo.EDGES_COLOR_TRANSPARENT:Vo.EDGES_COLOR_OPAQUE:Vo.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Vo.PICK:Vo.NOT_RENDERED)<<12,d|=(t&se?1:0)<<16,Ea[0]=d,this._state.flagsBuf&&this._state.flagsBuf.setData(Ea,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Ia[0]=t[0],Ia[1]=t[1],Ia[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(Ia,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.readableGeometryEnabled)return!1;const i=this._state,s=i.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=s.positionsCompressed,n=i.origin,a=n[0],l=n[1],A=n[2],h=Fa,c=r.matrix,u=this.model.matrix,p=i.positionsDecodeMatrix;for(let e=0,i=o.length;ev)&&(v=e,s.set(b),r&&d.triangleNormal(f,g,m,r),_=!0)}}return _&&r&&(d.transformVec3(a.normalMatrix,r,r),d.transformVec3(this.model.worldNormalMatrix,r,r),d.normalizeVec3(r)),_}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}class Qa extends Xo{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawElements(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0),r&&s.drawElements++}}class Va extends Qa{drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Ha extends Qa{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const ja=d.vec3(),Ga=d.vec3(),za=d.vec3(),Wa=d.vec3(),Ka=d.mat4();class Xa extends Xo{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=ja;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Ga;if(l){const e=za;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=J(p,t,Ka),m=Wa,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ja=d.vec3(),Ya=d.vec3(),Za=d.vec3(),qa=d.vec3(),$a=d.mat4();class el extends Xo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Ja;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Ya;if(l){const e=Za;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=J(p,t,$a),m=qa,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class tl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Va(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Ha(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Xa(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new el(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const il={};class sl{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}class rl{constructor(e){this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=il[t];return i||(i=new tl(e),il[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete il[t],i._destroy()}))),i}(e.model.scene),this.model=e.model,this._buffer=new sl(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new _t({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:d.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=d.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=d.vec3(e.origin)),this.primitive=e.primitive}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new qe(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=Rn(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new qe(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new qe(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.colors.length>0){const s=i.colors.length/4,r=new Float32Array(s);let o=!1;e.flagsBuf=new qe(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new qe(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new qe(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&ee&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ne&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&oe&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ae&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&se&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&le&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ie&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&te&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ae?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&le?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&se?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],A=t[3];for(let e=0;e0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 lightAmbient;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Lines instancing color fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),o.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):o.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class al extends ol{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const ll=d.vec3(),Al=d.vec3(),hl=d.vec3();d.vec3();const cl=d.mat4();class ul extends Xo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=ll;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Al;if(l){const e=d.transformPoint3(h,l,hl);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=J(p,t,cl),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),a.indicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const dl=d.vec3(),pl=d.vec3(),fl=d.vec3();d.vec3();const gl=d.mat4();class ml extends Xo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=dl;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=pl;if(l){const e=d.transformPoint3(h,l,fl);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=J(p,t,gl),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class _l{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._snapInitRenderer||(this._snapInitRenderer=new ul(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new ml(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new nl(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new al(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new ul(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new ml(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const vl={};const bl=new Uint8Array(4),yl=new Float32Array(1),xl=new Float32Array(3),Bl=new Float32Array(4);class wl{constructor(e){this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=vl[t];return i||(i=new _l(e),vl[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete vl[t],i._destroy()}))),i}(e.model.scene),this._aabb=d.collapseAABB3(),this._state=new _t({obb:d.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,e.origin&&(this._state.origin=d.vec3(e.origin)),this._finalized=!1,this.primitive=e.primitive}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;this._state.colorsBuf=new qe(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(r>0){let t=!1;this._state.flagsBuf=new qe(e,e.ARRAY_BUFFER,new Float32Array(r),r,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new qe(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.colorsCompressed&&i.colorsCompressed.length>0){const s=new Uint8Array(i.colorsCompressed),r=!1;t.colorsBuf=new qe(e,e.ARRAY_BUFFER,s,s.length,4,e.STATIC_DRAW,r)}if(i.positionsCompressed&&i.positionsCompressed.length>0){const s=!1;t.positionsBuf=new qe(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,s),t.positionsDecodeMatrix=d.mat4(i.positionsDecodeMatrix)}if(i.indices&&i.indices.length>0&&(t.indicesBuf=new qe(e,e.ELEMENT_ARRAY_BUFFER,new Uint32Array(i.indices),i.indices.length,1,e.STATIC_DRAW),t.numIndices=i.indices.length),this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this.model.scene.readableGeometryEnabled||(this._state.geometry=null),this._finalized=!0}initFlags(e,t,i){t&ee&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ne&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&oe&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ae&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&se&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&le&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ie&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&te&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ae?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&le?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&se?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";bl[0]=t[0],bl[1]=t[1],bl[2]=t[2],bl[3]=t[3],this._state.colorsBuf.setData(bl,4*e,4)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&ee),r=!!(t&oe),o=!!(t&ne),n=!!(t&ae),a=!!(t&le),l=!!(t&ie),A=!!(t&te);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Vo.NOT_RENDERED:i?Vo.COLOR_TRANSPARENT:Vo.COLOR_OPAQUE,c=!s||A?Vo.NOT_RENDERED:n?Vo.SILHOUETTE_SELECTED:o?Vo.SILHOUETTE_HIGHLIGHTED:r?Vo.SILHOUETTE_XRAYED:Vo.NOT_RENDERED;let u=0;u=!s||A?Vo.NOT_RENDERED:n?Vo.EDGES_SELECTED:o?Vo.EDGES_HIGHLIGHTED:r?Vo.EDGES_XRAYED:a?i?Vo.EDGES_COLOR_TRANSPARENT:Vo.EDGES_COLOR_OPAQUE:Vo.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Vo.PICK:Vo.NOT_RENDERED)<<12,d|=(t&se?255:0)<<16,yl[0]=d,this._state.flagsBuf.setData(yl,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(xl[0]=t[0],xl[1]=t[1],xl[2]=t[2],this._state.offsetsBuf.setData(xl,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;Bl[0]=t[0],Bl[1]=t[4],Bl[2]=t[8],Bl[3]=t[12],this._state.modelMatrixCol0Buf.setData(Bl,i),Bl[0]=t[1],Bl[1]=t[5],Bl[2]=t[9],Bl[3]=t[13],this._state.modelMatrixCol1Buf.setData(Bl,i),Bl[0]=t[2],Bl[1]=t[6],Bl[2]=t[10],Bl[3]=t[14],this._state.modelMatrixCol2Buf.setData(Bl,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Vo.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Vo.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Vo.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Vo.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Vo.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Vo.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Vo.PICK)}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class Pl extends Xo{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,i.positionsBuf.numItems),r&&s.drawArrays++}}class Cl extends Pl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial,s=[];return s.push("#version 300 es"),s.push("// Points batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Ml extends Pl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points batching silhouette vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = color;"),o.push("}"),o}}class El extends Pl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class Fl extends Pl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batched pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batched pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Il extends Pl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push(" gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}const Dl=d.vec3(),Sl=d.vec3(),Tl=d.vec3(),Rl=d.vec3(),Ll=d.mat4();class Ul extends Xo{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Dl;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Sl;if(l){const e=Tl;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=J(p,t,Ll),m=Rl,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ol=d.vec3(),kl=d.vec3(),Nl=d.vec3(),Ql=d.vec3(),Vl=d.mat4();class Hl extends Xo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Ol;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=kl;if(l){const e=Nl;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=J(p,t,Vl),m=Ql,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class jl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Cl(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Ml(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new El(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Fl(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Il(this._scene)),this._occlusionRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Ul(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Hl(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Gl={};class zl{constructor(e){this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Gl[t];return i||(i=new jl(e),Gl[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Gl[t],i._destroy()}))),i}(e.model.scene);const t=e.maxGeometryBatchSize||5e6,i=function(){const e=[];return{append:function(t,i=1,s=1){e.push({data:t,times:i,denormalizeScale:s})},compileBuffer:function(t){let i=0;e.forEach((e=>{i+=e.times*e.data.length}));const s=new t(i);let r=0;return e.forEach((e=>{const t=e.data,i=e.denormalizeScale,o=s.subarray(r);if(1===i)o.set(t,0);else for(let e=0;ee.length>0?new qe(t,t.ARRAY_BUFFER,e,e.length,i,s):null,r=this._preCompressedPositionsExpected?i.positions.compileBuffer(Uint16Array):Rn(i.positions.compileBuffer(Float32Array),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=s(r,3,t.STATIC_DRAW),e.flagsBuf=s(new Float32Array(this._buffer.vertsIndex),1,t.DYNAMIC_DRAW),e.colorsBuf=s(i.colors.compileBuffer(Uint8Array),4,t.STATIC_DRAW),e.pickColorsBuf=s(i.pickColors.compileBuffer(Uint8Array),4,t.STATIC_DRAW),e.offsetsBuf=this.model.scene.entityOffsetsEnabled?s(new Float32Array(3*this._buffer.vertsIndex),3,t.DYNAMIC_DRAW):null,this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&ee&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ne&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&oe&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ae&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&se&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ie&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&te&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ae?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&se?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Xl extends Wl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 silhouetteColor;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Jl extends Wl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick mesh fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class Yl extends Wl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Zl extends Wl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class ql extends Wl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points instancing depth vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return o.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class $l extends Wl{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("gl_PointSize = pointSize;"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const eA=d.vec3(),tA=d.vec3(),iA=d.vec3();d.vec3();const sA=d.mat4();class rA extends Xo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=eA;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=tA;if(l){const e=d.transformPoint3(h,l,iA);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=J(p,t,sA),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const oA=d.vec3(),nA=d.vec3(),aA=d.vec3();d.vec3();const lA=d.mat4();class AA extends Xo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=oA;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=nA;if(l){const e=d.transformPoint3(h,l,aA);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=J(p,t,lA),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class hA{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Kl(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Xl(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new ql(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Jl(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Yl(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Zl(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new $l(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new rA(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new AA(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const cA={};const uA=new Uint8Array(4),dA=new Float32Array(1),pA=new Float32Array(3),fA=new Float32Array(4);class gA{constructor(e){this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=cA[t];return i||(i=new hA(e),cA[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete cA[t],i._destroy()}))),i}(e.model.scene),this._aabb=d.collapseAABB3(),this._state=new _t({obb:d.OBB3(),numInstances:0,origin:e.origin?d.vec3(e.origin):null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,this.primitive=e.geometry.primitive}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let s=!1;i.flagsBuf=new qe(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,s)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;i.offsetsBuf=new qe(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(s.positionsCompressed&&s.positionsCompressed.length>0){const t=!1;i.positionsBuf=new qe(e,e.ARRAY_BUFFER,s.positionsCompressed,s.positionsCompressed.length,3,e.STATIC_DRAW,t),i.positionsDecodeMatrix=d.mat4(s.positionsDecodeMatrix)}if(s.colorsCompressed&&s.colorsCompressed.length>0){const t=new Uint8Array(s.colorsCompressed),r=!1;i.colorsBuf=new qe(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;i.modelMatrixCol0Buf=new qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),i.modelMatrixCol1Buf=new qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),i.modelMatrixCol2Buf=new qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;i.pickColorsBuf=new qe(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}i.geometry=null,this._finalized=!0}initFlags(e,t,i){t&ee&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ne&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&oe&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ae&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&se&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&le&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ie&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&te&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ae?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&le?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&se?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";uA[0]=t[0],uA[1]=t[1],uA[2]=t[2],this._state.colorsBuf.setData(uA,3*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&ee),r=!!(t&oe),o=!!(t&ne),n=!!(t&ae),a=!!(t&le),l=!!(t&ie),A=!!(t&te);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Vo.NOT_RENDERED:i?Vo.COLOR_TRANSPARENT:Vo.COLOR_OPAQUE,c=!s||A?Vo.NOT_RENDERED:n?Vo.SILHOUETTE_SELECTED:o?Vo.SILHOUETTE_HIGHLIGHTED:r?Vo.SILHOUETTE_XRAYED:Vo.NOT_RENDERED;let u=0;u=!s||A?Vo.NOT_RENDERED:n?Vo.EDGES_SELECTED:o?Vo.EDGES_HIGHLIGHTED:r?Vo.EDGES_XRAYED:a?i?Vo.EDGES_COLOR_TRANSPARENT:Vo.EDGES_COLOR_OPAQUE:Vo.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Vo.PICK:Vo.NOT_RENDERED)<<12,d|=(t&se?255:0)<<16,dA[0]=d,this._state.flagsBuf.setData(dA,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(pA[0]=t[0],pA[1]=t[1],pA[2]=t[2],this._state.offsetsBuf.setData(pA,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;fA[0]=t[0],fA[1]=t[4],fA[2]=t[8],fA[3]=t[12],this._state.modelMatrixCol0Buf.setData(fA,i),fA[0]=t[1],fA[1]=t[5],fA[2]=t[9],fA[3]=t[13],this._state.modelMatrixCol1Buf.setData(fA,i),fA[0]=t[2],fA[1]=t[6],fA[2]=t[10],fA[3]=t[14],this._state.modelMatrixCol2Buf.setData(fA,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Vo.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Vo.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Vo.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Vo.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Vo.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Vo.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Vo.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Vo.PICK)}drawPickNormals(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Vo.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Vo.PICK)}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}const mA=d.vec3(),_A=d.vec3(),vA=d.mat4();class bA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uPerObjectDecodeMatrix,this._uPerVertexPosition,this.uPerObjectColorAndFlags,this._uPerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=mA;if(g){const t=d.transformPoint3(c,A,_A);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=J(p,e,vA)}else f=p;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,8),n.drawArrays(n.LINES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,16),n.drawArrays(n.LINES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,32),n.drawArrays(n.LINES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// LinesDataTextureColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uPerObjectDecodeMatrix;"),i.push("uniform highp sampler2D uPerObjectMatrix;"),i.push("uniform lowp usampler2D uPerObjectColorAndFlags;"),i.push("uniform mediump usampler2D uPerVertexPosition;"),i.push("uniform highp usampler2D uPerLineIndices;"),i.push("uniform mediump usampler2D uPerLineObject;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push(" int lineIndex = gl_VertexID / 2;"),i.push(" int h_packed_object_id_index = (lineIndex >> 3) & 4095;"),i.push(" int v_packed_object_id_index = (lineIndex >> 3) >> 12;"),i.push(" int objectIndex = int(texelFetch(uPerLineObject, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push(" ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" } else {"),i.push(" ivec4 packedVertexBase = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push(" ivec4 packedLineIndexBaseOffset = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push(" int lineIndexBaseOffset = (packedLineIndexBaseOffset.r << 24) + (packedLineIndexBaseOffset.g << 16) + (packedLineIndexBaseOffset.b << 8) + packedLineIndexBaseOffset.a;"),i.push(" int h_index = (lineIndex - lineIndexBaseOffset) & 4095;"),i.push(" int v_index = (lineIndex - lineIndexBaseOffset) >> 12;"),i.push(" ivec3 vertexIndices = ivec3(texelFetch(uPerLineIndices, ivec2(h_index, v_index), 0));"),i.push(" ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push(" int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push(" int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push(" mat4 objectInstanceMatrix = mat4 (texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" vec3 position = vec3(texelFetch(uPerVertexPosition, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" uvec4 color = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push(" if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" };"),i.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push(" vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push(" vFragDepth = 1.0 + clipPos.w;"),i.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push(" gl_Position = clipPos;"),i.push(" vec4 rgb = vec4(color.rgba);"),i.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// LinesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class yA{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null)}eagerCreateRenders(){}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new bA(this._scene,!1)),this._colorRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy()}}const xA={};class BA{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perLineNumberPortionId8Bits=[],this.perLineNumberPortionId16Bits=[],this.perLineNumberPortionId32Bits=[]}}class wA{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerLineIdPortionIds8Bits=null,this.texturePerLineIdPortionIds16Bits=null,this.texturePerLineIdPortionIds32Bits=null,this.texturePerLineIdIndices8Bits=null,this.texturePerLineIdIndices16Bits=null,this.texturePerLineIdIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerLineIdIndices8Bits,16:this.texturePerLineIdIndices16Bits,32:this.texturePerLineIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerLineIdPortionIds8Bits,16:this.texturePerLineIdPortionIds16Bits,32:this.texturePerLineIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindLineIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}}class PA{constructor(e,t,i,s,r=null){this._gl=e,this._texture=t,this._textureWidth=i,this._textureHeight=s,this._textureData=r}bindTexture(e,t,i){return e.bindTexture(t,this,i)}bind(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}unbind(e){}}const CA={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalLines:0,totalLines8Bits:0,totalLines16Bits:0,totalLines32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(CA,null,4));let e=0;Object.keys(CA).forEach((t=>{t.startsWith("size")&&(e+=CA[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/CA.totalLines).toFixed(2)}`);let t={};Object.keys(CA).forEach((i=>{i.startsWith("size")&&(t[i]=`${(CA[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class MA{disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}generateTextureForColorsAndFlags(e,t,i,s,r){const o=t.length;this.numPortions=o;const n=4096,a=Math.ceil(o/512);if(0===a)throw"texture height===0";const l=new Uint8Array(16384*a);CA.sizeDataColorsAndFlags+=l.byteLength,CA.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),l.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20);const A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,n,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,a,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new PA(e,A,n,a,l)}generateTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);CA.sizeDataTextureOffsets+=r.byteLength,CA.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new PA(e,o,i,s,r)}generateTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);CA.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete xA[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new BA,this._dataTextureState=new wA,this._dataTextureGenerator=new MA,this._state=new _t({origin:d.vec3(t.origin),textureState:this._dataTextureState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this.primitive=t.primitive,this._finalized=!1}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&CA.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/2})),(this._state.numVertices+s>4096*FA||t+r>4096*FA)&&CA.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*FA&&t+r<=4096*FA}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/2/8)*2;CA.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}const i=t.positionsCompressed,s=t.indices,r=this._buffer;r.positionsCompressed.push(i);const o=r.lenPositionsCompressed/3,n=i.length/3;let a;r.lenPositionsCompressed+=i.length;let l=0;if(s){let e;l=s.length/2,n<=256?(e=r.indices8Bits,a=r.lenIndices8Bits/2,r.lenIndices8Bits+=s.length):n<=65536?(e=r.indices16Bits,a=r.lenIndices16Bits/2,r.lenIndices16Bits+=s.length):(e=r.indices32Bits,a=r.lenIndices32Bits/2,r.lenIndices32Bits+=s.length),e.push(s)}this._state.numVertices+=n,CA.numberOfGeometries++;return{vertexBase:o,numVertices:n,numLines:l,indicesBase:a}}_createSubPortion(e,t){const i=e.color,s=e.colors,r=e.opacity,o=e.meshMatrix,n=e.pickColor,a=this._buffer,l=this._state;a.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),a.perObjectInstancePositioningMatrices.push(o||RA),a.perObjectSolid.push(!!e.solid),s?a.perObjectColors.push([255*s[0],255*s[1],255*s[2],255]):i&&a.perObjectColors.push([i[0],i[1],i[2],r]),a.perObjectPickColors.push(n),a.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?l.numIndices8Bits:t.numVertices<=65536?l.numIndices16Bits:l.numIndices32Bits,a.perObjectIndexBaseOffsets.push(e/2-t.indicesBase)}const A=this._subPortions.length;if(t.numLines>0){let e,i=2*t.numLines;t.numVertices<=256?(e=a.perLineNumberPortionId8Bits,l.numIndices8Bits+=i,CA.totalLines8Bits+=t.numLines):t.numVertices<=65536?(e=a.perLineNumberPortionId16Bits,l.numIndices16Bits+=i,CA.totalLines16Bits+=t.numLines):(e=a.perLineNumberPortionId32Bits,l.numIndices32Bits+=i,CA.totalLines32Bits+=t.numLines),CA.totalLines+=t.numLines;for(let i=0;i0&&(t.texturePerLineIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerLineIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerLineIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}initFlags(e,t,i){t&ee&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ne&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&oe&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ae&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&se&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ie&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&te&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ae?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&se?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,DA))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),c.bindTexture(c.TEXTURE_2D,h.texturePerObjectColorsAndFlags._texture),c.texSubImage2D(c.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,c.RGBA_INTEGER,c.UNSIGNED_BYTE,DA))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,DA))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,SA))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,IA))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Vo.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Vo.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){}drawSilhouetteHighlighted(e,t){}drawSilhouetteSelected(e,t){}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}setPickMatrices(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawSnapInit(e,t){}drawSnap(e,t){}drawPickNormals(e,t){}destroy(){if(this._destroyed)return;const e=this._state;this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}const UA=d.vec3(),OA=d.vec3(),kA=d.vec3();d.vec3();const NA=d.vec4(),QA=d.mat4();class VA{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=UA;if(g){const t=d.transformPoint3(c,A,OA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=J(r.viewMatrix,e,QA),f=kA,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(let e=0,t=r.length;e0;let r;const o=[];o.push("#version 300 es"),o.push("// TrianglesDataTextureColorRenderer vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("uniform mat4 sceneModelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),o.push("uniform highp sampler2D uTexturePerObjectMatrix;"),o.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),o.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),o.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),o.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),o.push("uniform vec3 uCameraEyeRtc;"),o.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("out float isPerspective;")),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e> 3) & 4095;"),o.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),o.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),o.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),o.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),o.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),o.push("if (int(flags.x) != renderPass) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("} else {"),o.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),o.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),o.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),o.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),o.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),o.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),o.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),o.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),o.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),o.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),o.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),o.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),o.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),o.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),o.push("if (color.a == 0u) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("};"),o.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),o.push("vec3 position;"),o.push("position = positions[gl_VertexID % 3];"),o.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),o.push("if (solid != 1u) {"),o.push("if (isPerspectiveMatrix(projMatrix)) {"),o.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),o.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("} else {"),o.push("if (viewNormal.z < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("}"),o.push("}"),o.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const HA=new Float32Array([1,1,1]),jA=d.vec3(),GA=d.vec3(),zA=d.vec3();d.vec3();const WA=d.mat4();class KA{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=jA;if(A){const t=GA;d.transformPoint3(c,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=J(p,e,WA),g=zA,g[0]=r.eye[0]-e[0],g[1]=r.eye[1]-e[1],g[2]=r.eye[2]-e[2]}else f=p,g=r.eye;if(n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),i===Vo.SILHOUETTE_XRAYED){const e=s.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Vo.SILHOUETTE_HIGHLIGHTED){const e=s.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Vo.SILHOUETTE_SELECTED){const e=s.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,HA);if(s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(m>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,r=o.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = color;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const XA=new Float32Array([0,0,0,1]),JA=d.vec3(),YA=d.vec3();d.vec3();const ZA=d.mat4();class qA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=JA;if(g){const t=d.transformPoint3(c,A,YA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=J(p,e,ZA)}else f=p;if(n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),i===Vo.EDGES_XRAYED){const e=r.xrayMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Vo.EDGES_HIGHLIGHTED){const e=r.highlightMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Vo.EDGES_SELECTED){const e=r.selectedMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,XA);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const $A=d.vec3(),eh=d.vec3(),th=d.mat4();class ih{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=$A;if(g){const t=d.transformPoint3(c,A,eh);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=J(p,e,th)}else f=p;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uObjectPerObjectOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const sh=d.vec3(),rh=d.vec3(),oh=d.vec3(),nh=d.mat4();class ah{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=e.pickViewMatrix||o.viewMatrix,f=e.pickProjMatrix||o.projMatrix,g=e.pickOrigin||o.eye,m=e.pickProjMatrix?e.pickZFar:o.project.far;let _,v;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const b=0!==A[0]||0!==A[1]||0!==A[2],y=0!==h[0]||0!==h[1]||0!==h[2];if(b||y){const e=sh;if(b){const t=d.transformPoint3(c,A,rh);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],_=J(p,e,nh),v=oh,v[0]=g[0]-e[0],v[1]=g[1]-e[1],v[2]=g[2]-e[2]}else _=p,v=g;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,_),n.uniformMatrix4fv(this._uProjMatrix,!1,f),n.uniform3fv(this._uCameraEyeRtc,v),n.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(m+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const x=r._sectionPlanesState.getNumAllocatedSectionPlanes(),B=r._sectionPlanesState.sectionPlanes.length;if(x>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*B,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var s=0;s 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const lh=d.vec3(),Ah=d.vec3(),hh=d.vec3();d.vec3();const ch=d.mat4();class uh{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=e.pickViewMatrix||o.viewMatrix,f=e.pickProjMatrix||o.projMatrix,g=e.pickOrigin||o.eye,m=e.pickProjMatrix?e.pickZFar:o.project.far;let _,v;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const t=lh;if(A){const e=Ah;d.transformPoint3(c,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],_=J(p,t,ch),v=hh,v[0]=g[0]-t[0],v[1]=g[1]-t[1],v[2]=g[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else _=p,v=g,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(n.uniform3fv(this._uCameraEyeRtc,v),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniform1f(this._uPickZNear,e.pickZNear),n.uniform1f(this._uPickZFar,e.pickZFar),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,_),n.uniformMatrix4fv(this._uProjMatrix,!1,f),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(m+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const b=r._sectionPlanesState.getNumAllocatedSectionPlanes(),y=r._sectionPlanesState.sectionPlanes.length;if(b>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*y,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0;s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outPackedDepth = packDepth(zNormalizedDepth); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const dh=d.vec3(),ph=d.vec3(),fh=d.vec3(),gh=d.vec3();d.vec3();const mh=d.mat4();class _h{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=dh;let m,_;g[0]=d.safeInv(p[3]-p[0])*d.MAX_INT,g[1]=d.safeInv(p[4]-p[1])*d.MAX_INT,g[2]=d.safeInv(p[5]-p[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(g[0]),e.snapPickCoordinateScale[1]=d.safeInv(g[1]),e.snapPickCoordinateScale[2]=d.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=ph;if(v){const e=d.transformPoint3(c,A,fh);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=J(f,t,mh),_=gh,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),x=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*x,o=s.renderFlags;for(let t=0;t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(B,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(B,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(B,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uSnapVectorA;"),i.push("uniform vec2 uSnapInvVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),i.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("}"),i.push("{"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vViewPosition = clipPos;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const vh=d.vec3(),bh=d.vec3(),yh=d.vec3(),xh=d.vec3();d.vec3();const Bh=d.mat4();class wh{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=vh;let m,_;g[0]=d.safeInv(p[3]-p[0])*d.MAX_INT,g[1]=d.safeInv(p[4]-p[1])*d.MAX_INT,g[2]=d.safeInv(p[5]-p[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(g[0]),e.snapPickCoordinateScale[1]=d.safeInv(g[1]),e.snapPickCoordinateScale[2]=d.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=bh;if(v){const e=yh;d.transformPoint3(c,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=J(f,t,Bh),_=xh,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this._uVectorA,e.snapVectorA),n.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),x=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*x,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uVectorAB;"),i.push("uniform vec2 uInverseVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),i.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("}"),i.push("{"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" } else {"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ph=d.vec3(),Ch=d.vec3(),Mh=d.vec3();d.vec3();const Eh=d.mat4();class Fh{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=e.pickViewMatrix||o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=Ph;if(A){const t=Ch;d.transformPoint3(c,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=J(p,e,Eh),g=Mh,g[0]=o.eye[0]-e[0],g[1]=o.eye[1]-e[1],g[2]=o.eye[2]-e[2]}else f=p,g=o.eye;n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureOcclusionRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" } else {"),i.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureColorRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ih=d.vec3(),Dh=d.vec3(),Sh=d.vec3();d.vec3();const Th=d.mat4();class Rh{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=Ih;if(g){const t=d.transformPoint3(c,A,Dh);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=J(r.viewMatrix,e,Th),f=Sh,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Lh=d.vec3(),Uh=d.vec3(),Oh=d.vec3();d.vec3();const kh=d.mat4();class Nh{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));const g=0!==l[0]||0!==l[1]||0!==l[2],m=0!==A[0]||0!==A[1]||0!==A[2];if(g||m){const e=Lh;if(g){const t=Uh;d.transformPoint3(h,l,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=A[0],e[1]+=A[1],e[2]+=A[2],p=J(u,e,kh),f=Oh,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=u,f=o.eye;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,c),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),n.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&He.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),He.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out vec4 vFlags2;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(He.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&He.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&He.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&He.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Qh=d.vec3(),Vh=d.vec3(),Hh=d.vec3();d.vec3(),d.vec4();const jh=d.mat4();class Gh{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a));const p=e.pickViewMatrix||r.viewMatrix,f=e.pickProjMatrix||r.projMatrix,g=e.pickOrigin||r.eye,m=e.pickProjMatrix?e.pickZFar:r.project.far;let _,v;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const b=0!==A[0]||0!==A[1]||0!==A[2],y=0!==h[0]||0!==h[1]||0!==h[2];if(b||y){const e=Qh;if(b){const t=d.transformPoint3(c,A,Vh);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],_=J(p,e,jh),v=Hh,v[0]=g[0]-e[0],v[1]=g[1]-e[1],v[2]=g[2]-e[2]}else _=p,v=g;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,_),n.uniformMatrix4fv(this._uProjMatrix,!1,f),n.uniform3fv(this._uCameraEyeRtc,v),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const e=2/(Math.log(m+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const x=s._sectionPlanesState.getNumAllocatedSectionPlanes(),B=s._sectionPlanesState.sectionPlanes.length;if(x>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*B,r=o.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ze(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// trianglesDatatextureNormalsRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTexturePickNormalsRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class zh{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new KA(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new ah(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new uh(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new Gh(this._scene)),this._snapRenderer||(this._snapRenderer=new _h(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new wh(this._scene)),this._snapRenderer||(this._snapRenderer=new _h(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new VA(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new VA(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new KA(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Rh(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Nh(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new qA(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new ih(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new ah(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Gh(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Gh(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new uh(this._scene)),this._pickDepthRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new _h(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new wh(this._scene)),this._snapInitRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Fh(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const Wh={};class Kh{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}class Xh{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindTriangleIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}bindEdgeIndicesTextures(e,t,i,s){this.edgeIndicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[s].bindTexture(e,i,6)}}const Jh={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(Jh,null,4));let e=0;Object.keys(Jh).forEach((t=>{t.startsWith("size")&&(e+=Jh[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/Jh.totalPolygons).toFixed(2)}`);let t={};Object.keys(Jh).forEach((i=>{i.startsWith("size")&&(t[i]=`${(Jh[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class Yh{constructor(){}disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}createTextureForColorsAndFlags(e,t,i,s,r,o,n){const a=t.length;this.numPortions=a;const l=4096,A=Math.ceil(a/512);if(0===A)throw"texture height===0";const h=new Uint8Array(16384*A);Jh.sizeDataColorsAndFlags+=h.byteLength,Jh.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),h.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20),h.set([o[e]>>24&255,o[e]>>16&255,o[e]>>8&255,255&o[e]],32*e+24),h.set([n[e]?1:0,0,0,0],32*e+28);const c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,A),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,A,e.RGBA_INTEGER,e.UNSIGNED_BYTE,h,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new PA(e,c,l,A,h)}createTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);Jh.sizeDataTextureOffsets+=r.byteLength,Jh.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new PA(e,o,i,s,r)}createTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);Jh.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Wh[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new Kh,this._dtxState=new Xh,this._dtxTextureFactory=new Yh,this._state=new _t({origin:d.vec3(t.origin),metallicRoughnessBuf:null,textureState:this._dtxState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numEdgeIndices8Bits:0,numEdgeIndices16Bits:0,numEdgeIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this.model.scene.readableGeometryEnabled&&(this._subPortionReadableGeometries={}),this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this.primitive=t.primitive,this._finalized=!1}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&Jh.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/3})),(this._state.numVertices+s>4096*qh||t+r>4096*qh)&&Jh.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*qh&&t+r<=4096*qh}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/3/8)*3;Jh.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}if(t.edgeIndices){const e=8*Math.ceil(t.edgeIndices.length/2/8)*2;Jh.overheadSizeAlignementEdgeIndices+=2*(e-t.edgeIndices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.edgeIndices),t.edgeIndices=i}const i=t.positionsCompressed,s=t.indices,r=t.edgeIndices,o=this._buffer;o.positionsCompressed.push(i);const n=o.lenPositionsCompressed/3,a=i.length/3;let l;o.lenPositionsCompressed+=i.length;let A,h=0;if(s){let e;h=s.length/3,a<=256?(e=o.indices8Bits,l=o.lenIndices8Bits/3,o.lenIndices8Bits+=s.length):a<=65536?(e=o.indices16Bits,l=o.lenIndices16Bits/3,o.lenIndices16Bits+=s.length):(e=o.indices32Bits,l=o.lenIndices32Bits/3,o.lenIndices32Bits+=s.length),e.push(s)}let c=0;if(r){let e;c=r.length/2,a<=256?(e=o.edgeIndices8Bits,A=o.lenEdgeIndices8Bits/2,o.lenEdgeIndices8Bits+=r.length):a<=65536?(e=o.edgeIndices16Bits,A=o.lenEdgeIndices16Bits/2,o.lenEdgeIndices16Bits+=r.length):(e=o.edgeIndices32Bits,A=o.lenEdgeIndices32Bits/2,o.lenEdgeIndices32Bits+=r.length),e.push(r)}this._state.numVertices+=a,Jh.numberOfGeometries++;return{vertexBase:n,numVertices:a,numTriangles:h,numEdges:c,indicesBase:l,edgeIndicesBase:A}}_createSubPortion(e,t,i,s){const r=e.color;e.metallic,e.roughness;const o=e.colors,n=e.opacity,a=e.meshMatrix,l=e.pickColor,A=this._buffer,h=this._state;A.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),A.perObjectInstancePositioningMatrices.push(a||rc),A.perObjectSolid.push(!!e.solid),o?A.perObjectColors.push([255*o[0],255*o[1],255*o[2],255]):r&&A.perObjectColors.push([r[0],r[1],r[2],n]),A.perObjectPickColors.push(l),A.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?h.numIndices8Bits:t.numVertices<=65536?h.numIndices16Bits:h.numIndices32Bits,A.perObjectIndexBaseOffsets.push(e/3-t.indicesBase)}{let e;e=t.numVertices<=256?h.numEdgeIndices8Bits:t.numVertices<=65536?h.numEdgeIndices16Bits:h.numEdgeIndices32Bits,A.perObjectEdgeIndexBaseOffsets.push(e/2-t.edgeIndicesBase)}const c=this._subPortions.length;if(t.numTriangles>0){let e,i=3*t.numTriangles;t.numVertices<=256?(e=A.perTriangleNumberPortionId8Bits,h.numIndices8Bits+=i,Jh.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(e=A.perTriangleNumberPortionId16Bits,h.numIndices16Bits+=i,Jh.totalPolygons16Bits+=t.numTriangles):(e=A.perTriangleNumberPortionId32Bits,h.numIndices32Bits+=i,Jh.totalPolygons32Bits+=t.numTriangles),Jh.totalPolygons+=t.numTriangles;for(let i=0;i0){let e,i=2*t.numEdges;t.numVertices<=256?(e=A.perEdgeNumberPortionId8Bits,h.numEdgeIndices8Bits+=i,Jh.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(e=A.perEdgeNumberPortionId16Bits,h.numEdgeIndices16Bits+=i,Jh.totalEdges16Bits+=t.numEdges):(e=A.perEdgeNumberPortionId32Bits,h.numEdgeIndices32Bits+=i,Jh.totalEdges32Bits+=t.numEdges),Jh.totalEdges+=t.numEdges;for(let i=0;i0&&(t.texturePerEdgeIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId8Bits)),s.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId16Bits)),s.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId32Bits)),s.lenIndices8Bits>0&&(t.texturePerPolygonIdIndices8Bits=this._dtxTextureFactory.createTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerPolygonIdIndices16Bits=this._dtxTextureFactory.createTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerPolygonIdIndices32Bits=this._dtxTextureFactory.createTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),s.lenEdgeIndices8Bits>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this._dtxTextureFactory.createTextureFor8BitsEdgeIndices(i,s.edgeIndices8Bits,s.lenEdgeIndices8Bits)),s.lenEdgeIndices16Bits>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this._dtxTextureFactory.createTextureFor16BitsEdgeIndices(i,s.edgeIndices16Bits,s.lenEdgeIndices16Bits)),s.lenEdgeIndices32Bits>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this._dtxTextureFactory.createTextureFor32BitsEdgeIndices(i,s.edgeIndices32Bits,s.lenEdgeIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}isEmpty(){return 0===this._numPortions}initFlags(e,t,i){t&ee&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ne&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&oe&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ae&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&se&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&le&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ie&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&te&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ae?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&le?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&se?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dtxState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,tc))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),g.bindTexture(g.TEXTURE_2D,f.texturePerObjectColorsAndFlags._texture),g.texSubImage2D(g.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,g.RGBA_INTEGER,g.UNSIGNED_BYTE,tc))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,tc))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,ic))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,ec))}getEachVertex(e,t){if(!this.model.scene.readableGeometryEnabled)return;const i=this._state,s=this._portionToSubPortionsMap[e];if(s)for(let e=0,r=s.length;e{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==uc[e])return void uc[e].push({onLoad:t,onProgress:i,onError:s});uc[e]=[],uc[e].push({onLoad:t,onProgress:i,onError:s});const o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),n=this.mimeType,a=this.responseType;fetch(o).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;const i=uc[e],s=t.body.getReader(),r=t.headers.get("Content-Length"),o=r?parseInt(r):0,n=0!==o;let a=0;const l=new ReadableStream({start(e){!function t(){s.read().then((({done:s,value:r})=>{if(s)e.close();else{a+=r.byteLength;const s=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=i.length;e{switch(a){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,n)));case"json":return e.json();default:if(void 0===n)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(n),i=t&&t[1]?t[1].toLowerCase():void 0,s=new TextDecoder(i);return e.arrayBuffer().then((e=>s.decode(e)))}}})).then((t=>{lc.add(e,t);const i=uc[e];delete uc[e];for(let e=0,s=i.length;e{const i=uc[e];if(void 0===i)throw this.manager.itemError(e),t;delete uc[e];for(let e=0,s=i.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class pc{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e{const s=this._getIdleWorker();-1!==s?(this._initWorker(s),this.workerStatus|=1<e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let fc=0;class gc{constructor({viewer:e,transcoderPath:t,workerLimit:i}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new pc,this._workerSourceURL="",i&&this._workerPool.setWorkerLimit(i);const s=e.capabilities;this._workerConfig={astcSupported:s.astcSupported,etc1Supported:s.etc1Supported,etc2Supported:s.etc2Supported,dxtSupported:s.dxtSupported,bptcSupported:s.bptcSupported,pvrtcSupported:s.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new dc;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),i=new dc;i.setPath(this._transcoderPath),i.setResponseType("arraybuffer"),i.setWithCredentials(this.withCredentials);const s=i.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,s]).then((([e,t])=>{const i=gc.BasisWorker.toString(),s=["/* constants */","let _EngineFormat = "+JSON.stringify(gc.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(gc.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(gc.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([s])),this._transcoderBinary=t,this._workerPool.setWorkerCreator((()=>{const e=new Worker(this._workerSourceURL),t=this._transcoderBinary.slice(0);return e.postMessage({type:"init",config:this._workerConfig,transcoderBinary:t},[t]),e}))})),fc>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),fc++}return this._transcoderPending}transcode(e,t,i={}){return new Promise(((s,r)=>{const o=i;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const i=e.data,{mipmaps:o,width:n,height:a,format:l,type:A,error:h,dfdTransferFn:c,dfdFlags:u}=i;if("error"===A)return r(h);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?1006:1008,magFilter:1===o.length?1006:1008,encoding:2===c?3001:3e3,premultiplyAlpha:!!(1&u)}}),s()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),fc--}}gc.BasisFormat={ETC1S:0,UASTC_4x4:1},gc.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16},gc.EngineFormat={RGBAFormat:1023,RGBA_ASTC_4x4_Format:37808,RGBA_BPTC_Format:36492,RGBA_ETC2_EAC_Format:37496,RGBA_PVRTC_4BPPV1_Format:35842,RGBA_S3TC_DXT5_Format:33779,RGB_ETC1_Format:36196,RGB_ETC2_Format:37492,RGB_PVRTC_4BPPV1_Format:35840,RGB_S3TC_DXT1_Format:33776},gc.BasisWorker=function(){let e,t,i;const s=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const h=n.data;switch(h.type){case"init":e=h.config,c=h.transcoderBinary,t=new Promise((e=>{i={wasmBinary:c,onRuntimeInitialized:e},BASIS(i)})).then((()=>{i.initializeBasis(),void 0===i.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:c,mipmaps:u,format:d,dfdTransferFn:p,dfdFlags:f}=function(t){const n=new i.KTX2File(new Uint8Array(t));function h(){n.close(),n.delete()}if(!n.isValid())throw h(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const c=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),d=n.getHeight(),p=n.getLevels(),f=n.getHasAlpha(),g=n.getDFDTransferFunc(),m=n.getDFDFlags(),{transcoderFormat:_,engineFormat:v}=function(t,i,n,h){let c,u;const d=t===o.ETC1S?a:l;for(let s=0;s{delete mc[t],i.destroy()}))),i} /** * @author https://github.com/tmarti, with support from https://tribia.com/ * @license MIT @@ -14,7 +14,7 @@ class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){ /** * @author https://github.com/tmarti, with support from https://tribia.com/ * @license MIT - **/let Bc=null;function wc(e,t){const i=3*e,s=3*t;let r,o,n,a,l,A;const h=Math.min(r=Bc[i],o=Bc[i+1],n=Bc[i+2]),c=Math.min(a=Bc[s],l=Bc[s+1],A=Bc[s+2]);if(h!==c)return h-c;const u=Math.max(r,o,n),d=Math.max(a,l,A);return u!==d?u-d:0}let Pc=null;function Cc(e,t){let i=Pc[2*e]-Pc[2*t];return 0!==i?i:Pc[2*e+1]-Pc[2*t+1]}function Mc(e,t,i=!1){const s=e.positionsCompressed||[],r=function(e,t){const i=new Int32Array(e.length/3);for(let e=0,t=i.length;e>t;i.sort(wc);const s=new Int32Array(e.length);for(let t=0,r=i.length;te[t+1]){let i=e[t];e[t]=e[t+1],e[t+1]=i}Pc=new Int32Array(e),t.sort(Cc);const i=new Int32Array(e.length);for(let s=0,r=t.length;st){let i=e;e=t,t=i}function i(i,s){return i!==e?e-i:s!==t?t-s:0}let s=0,r=(o.length>>1)-1;for(;s<=r;){const e=r+s>>1,t=i(o[2*e],o[2*e+1]);if(t>0)s=e+1;else{if(!(t<0))return e;r=e-1}}return-s-1}const a=new Int32Array(o.length/2);a.fill(0);const l=s.length/3;if(l>8*(1<u.maxNumPositions&&(u=c()),u.bucketNumber>8)return[e];let p;-1===A[l]&&(A[l]=u.numPositions++,u.positionsCompressed.push(s[3*l]),u.positionsCompressed.push(s[3*l+1]),u.positionsCompressed.push(s[3*l+2])),-1===A[h]&&(A[h]=u.numPositions++,u.positionsCompressed.push(s[3*h]),u.positionsCompressed.push(s[3*h+1]),u.positionsCompressed.push(s[3*h+2])),-1===A[d]&&(A[d]=u.numPositions++,u.positionsCompressed.push(s[3*d]),u.positionsCompressed.push(s[3*d+1]),u.positionsCompressed.push(s[3*d+2])),u.indices.push(A[l]),u.indices.push(A[h]),u.indices.push(A[d]),(p=n(l,h))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(l,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(h,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]]))}const d=t/8*2,p=t/8,f=2*s.length+(r.length+o.length)*d;let g=0,m=-s.length/3;return h.forEach((e=>{g+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*p,m+=e.positionsCompressed.length/3})),g>f?[e]:(i&&function(e,t){const i={},s={};let r=0;e.forEach((e=>{const t=e.indices,o=e.edgeIndices,n=e.positionsCompressed;for(let e=0,s=t.length;e0){const e=t._meshes;for(let t=0,i=e.length;t0){const e=this._meshes;for(let t=0,i=e.length;t{this._viewMatrixDirty=!0})),this._meshesWithDirtyMatrices=[],this._numMeshesWithDirtyMatrices=0,this._onTick=this.scene.on("tick",(()=>{for(;this._numMeshesWithDirtyMatrices>0;)this._meshesWithDirtyMatrices[--this._numMeshesWithDirtyMatrices]._updateMatrix()})),this._createDefaultTextureSet(),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.backfaces=t.backfaces}_meshMatrixDirty(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}_createDefaultTextureSet(){const e=new ac({id:"defaultColorTexture",texture:new Zr({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new ac({id:"defaultMetalRoughTexture",texture:new Zr({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new ac({id:"defaultNormalsTexture",texture:new Zr({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),s=new ac({id:"defaultEmissiveTexture",texture:new Zr({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new ac({id:"defaultOcclusionTexture",texture:new Zr({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=s,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new nc({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:s,occlusionTexture:r})}get isPerformanceModel(){return!0}get transforms(){return this._transforms}get textures(){return this._textures}get textureSets(){return this._textureSets}get meshes(){return this._meshes}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),d.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||Hc),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),d.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),d.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get matrix(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),d.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),d.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}get rotationMatrixConjugate(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0,this._aabbDirty=!0}_transformDirty(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}_sceneModelDirty(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(let e=0,t=this._entityList.length;e0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,i=this._entityList.length;t0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._entityList.length;t0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._entityList.length;t0}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._entityList.length;t0}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._entityList.length;t0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._entityList.length;t0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,i=new Uint8Array(t.length);for(let e=0,s=t.length;e{l.setImage(A,{minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a}),this.glRedraw()},A.src=e.src;break;default:this._textureTranscoder?y.loadArraybuffer(e.src,(e=>{e.byteLength?this._textureTranscoder.transcode([e],l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'src': file data is zero length")}),(function(e){this.error(`[createTexture] Can't create texture from 'src': ${e}`)})):this.error(`[createTexture] Can't create texture from 'src' - SceneModel needs to be configured with a TextureTranscoder for this file type ('${t}')`)}}else e.buffers&&(this._textureTranscoder?this._textureTranscoder.transcode(e.buffers,l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'buffers' - SceneModel needs to be configured with a TextureTranscoder for this option"));this._textures[t]=new ac({id:t,texture:l})}createTextureSet(e){const t=e.id;if(null==t)return void this.error("[createTextureSet] Config missing: id");if(this._textureSets[t])return void this.error(`[createTextureSet] Texture set already created: ${t}`);let i,s,r,o,n;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(i=this._textures[e.colorTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.colorTextureId} - ensure that you create it first with createTexture()`)}else i=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(s=this._textures[e.metallicRoughnessTextureId],!s)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else s=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(r=this._textures[e.normalsTextureId],!r)return void this.error(`[createTextureSet] Texture not found: ${e.normalsTextureId} - ensure that you create it first with createTexture()`)}else r=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(o=this._textures[e.emissiveTextureId],!o)return void this.error(`[createTextureSet] Texture not found: ${e.emissiveTextureId} - ensure that you create it first with createTexture()`)}else o=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(n=this._textures[e.occlusionTextureId],!n)return void this.error(`[createTextureSet] Texture not found: ${e.occlusionTextureId} - ensure that you create it first with createTexture()`)}else n=this._textures.defaultOcclusionTexture;const a=new nc({id:t,model:this,colorTexture:i,alphaCutoff:e.alphaCutoff,metallicRoughnessTexture:s,normalsTexture:r,emissiveTexture:o,occlusionTexture:n});return this._textureSets[t]=a,a}createTransform(e){if(void 0===e.id||null===e.id)return void this.error("[createTransform] SceneModel.createTransform() config missing: id");if(this._transforms[e.id])return void this.error(`[createTransform] SceneModel already has a transform with this ID: ${e.id}`);let t;if(e.parentTransformId&&(t=this._transforms[e.parentTransformId],!t))return void this.error("[createTransform] SceneModel.createTransform() config missing: id");const i=new Lc({id:e.id,model:this,parent:t,matrix:e.matrix,position:e.position,scale:e.scale,rotation:e.rotation,quaternion:e.quaternion});return this._transforms[i.id]=i,i}createMesh(e){if(void 0===e.id||null===e.id)return this.error("[createMesh] SceneModel.createMesh() config missing: id"),!1;if(this._meshes[e.id])return this.error(`[createMesh] SceneModel already has a mesh with this ID: ${e.id}`),!1;if(!(void 0!==e.geometryId)){if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"!==e.primitive&&"lines"!==e.primitive&&"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)return this.error(`Unsupported value for 'primitive': '${primitive}' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.`),!1;if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),!1;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),!1;if(!(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){const t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return e.indices=this._createDefaultIndices(numIndices),this.error(`Param expected: indices (required for '${e.primitive}' primitive type)`),!1;if((e.matrix||e.position||e.rotation||e.scale)&&(e.positionsCompressed||e.positionsDecodeBoundary))return this.error("Unexpected params: 'matrix', 'rotation', 'scale', 'position' not allowed with 'positionsCompressed'"),!1;const t=!(!this._dtxEnabled||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||e.textureSetId);if(e.origin=e.origin?d.addVec3(this._origin,e.origin,d.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){const t=e.scale||Nc,i=e.position||Qc;e.rotation?(d.eulerToQuaternion(e.rotation,"XYZ",Oc),e.meshMatrix=d.composeMat4(i,Oc,t,d.mat4())):e.meshMatrix=d.composeMat4(i,e.quaternion||Vc,t,d.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Ln(e.positionsDecodeBoundary,d.mat4())),t){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):jc,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=d.vec3(),i=[];Z(e.positions,i,t)&&(e.positions=i,e.origin=d.addVec3(e.origin,t,t))}if(e.positions){const t=d.collapseAABB3();e.positionsDecodeMatrix=d.mat4(),d.expandAABB3Points3(t,e.positions),e.positionsCompressed=Rn(e.positions,t,e.positionsDecodeMatrix),e.aabb=t}else if(e.positionsCompressed){const t=d.collapseAABB3();d.expandAABB3Points3(t,e.positionsCompressed),Zt.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.buckets){const t=d.collapseAABB3();for(let i=0,s=e.buckets.length;i>24&255,r=i>>16&255,o=i>>8&255,n=255&i;switch(e.pickColor=new Uint8Array([n,o,r,s]),e.solid="solid"===e.primitive,t.origin=d.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),t.numPrimitives=e.numPrimitives,this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}_getNumPrimitives(e){let t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i>>0).toString(16)}_getVBOInstancingLayer(e){const t=this,i=e.origin,s=e.textureSetId||"-",r=e.geometryId,o=`${Math.round(i[0])}.${Math.round(i[1])}.${Math.round(i[2])}.${s}.${r}`;let n=this._vboInstancingLayers[o];if(n)return n;let a=e.textureSet;const l=e.geometry;for(;!n;)switch(l.primitive){case"triangles":case"surface":n=new Na({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":n=new Na({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":n=new wl({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":n=new gA({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[o]=n,this.layerList.push(n),this._layersToFinalize.push(n),n}createEntity(e){if(void 0===e.id?e.id=d.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=d.createUUID()),void 0===e.meshIds)return void this.error("Config missing: meshIds");let t=0;return this._visible&&!1!==e.visible&&(t|=ee),this._pickable&&!1!==e.pickable&&(t|=ie),this._culled&&!1!==e.culled&&(t|=te),this._clippable&&!1!==e.clippable&&(t|=se),this._collidable&&!1!==e.collidable&&(t|=re),this._edges&&!1!==e.edges&&(t|=le),this._xrayed&&!1!==e.xrayed&&(t|=oe),this._highlighted&&!1!==e.highlighted&&(t|=ne),this._selected&&!1!==e.selected&&(t|=ae),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];for(let i=0,s=e.meshIds.length;ie.sortIdt.sortId?1:0));for(let e=0,t=this.layerList.length;e0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}_updateRenderFlagsVisibleLayers(){const e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(let t=0,i=this.layerList.length;t0){const t=`${this.id}-${d.createUUID()}`;this.warn(`Creating dummy SceneModelEntity "${t}" for unused SceneMeshes: [${e.join(",")}]`),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}_getActiveSectionPlanesForLayer(e){const t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,s=i.length,r=e.layerIndex*s;if(s>0)for(let e=0;e0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0){this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions0&&(e.edgesTransparent=!0))}if(this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){const t=this.scene.highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}drawColorOpaque(e,t){const i=this.renderFlags;for(let t=0,s=i.visibleLayers.length;t65536?16:8)}else n=[{positionsCompressed:s,indices:r,edgeIndices:o}];return n}class Wc extends R{constructor(e,t={}){if(super(e,t),this._positions=t.positions||[],t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;ep.has(e.id)||g.has(e.id)||f.has(e.id))).reduce(((e,i)=>{let s,r=function(e){let t="";return t+=Math.round(255*e[0]).toString(16).padStart(2,"0"),t+=Math.round(255*e[1]).toString(16).padStart(2,"0"),t+=Math.round(255*e[2]).toString(16).padStart(2,"0"),t}(i.colorize);i.xrayed?(s=0===t.xrayMaterial.fillAlpha&&0!==t.xrayMaterial.edgeAlpha?.1:t.xrayMaterial.fillAlpha,s=Math.round(255*s).toString(16).padStart(2,"0"),r=s+r):p.has(i.id)&&(s=Math.round(255*i.opacity).toString(16).padStart(2,"0"),r=s+r),e[r]||(e[r]=[]);const o=i.id,n=i.originalSystemId,a={ifc_guid:n,originating_system:this.originatingSystem};return n!==o&&(a.authoring_tool_id=o),e[r].push(a),e}),{}),_=Object.entries(m).map((([e,t])=>({color:e,components:t})));o.components.coloring=_;const v=t.objectIds,b=t.visibleObjects,y=t.visibleObjectIds,x=v.filter((e=>!b[e])),B=t.selectedObjectIds;return e.defaultInvisible||y.length0&&e.clipping_planes.forEach((function(e){let t=$c(e.location,Kc),i=$c(e.direction,Kc);A&&d.negateVec3(i),d.subVec3(t,l),r.yUp&&(t=tu(t),i=tu(i)),new Dr(s,{pos:t,dir:i})})),s.clearLines(),e.lines&&e.lines.length>0){const t=[],i=[];let r=0;e.lines.forEach((e=>{e.start_point&&e.end_point&&(t.push(e.start_point.x),t.push(e.start_point.y),t.push(e.start_point.z),t.push(e.end_point.x),t.push(e.end_point.y),t.push(e.end_point.z),i.push(r++),i.push(r++))})),new Wc(s,{positions:t,indices:i,clippable:!1,collidable:!0})}if(s.clearBitmaps(),e.bitmaps&&e.bitmaps.length>0&&e.bitmaps.forEach((function(e){const t=e.bitmap_type||"jpg",i=e.bitmap_data;let o=$c(e.location,Xc),n=$c(e.normal,Jc),a=$c(e.up,Yc),l=e.height||1;t&&i&&o&&n&&a&&(r.yUp&&(o=tu(o),n=tu(n),a=tu(a)),new bo(s,{src:i,type:t,pos:o,normal:n,up:a,clippable:!1,collidable:!0,height:l}))})),a&&(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=>this._withBCFComponent(t,e,(e=>e.visible=!1))))):(s.setObjectsVisible(s.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!0)))));const r=e.components.visibility.view_setup_hints;r&&(!1===r.spaces_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcSpace"),!1),void 0!==r.spaces_translucent&&s.setObjectsXRayed(i.metaScene.getObjectIDsByType("IfcSpace"),!0),r.space_boundaries_visible,!1===r.openings_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcOpening"),!0),r.space_boundaries_translucent,void 0!==r.openings_translucent&&s.setObjectsXRayed(i.metaScene.getObjectIDsByType("IfcOpening"),!0))}e.components.selection&&(s.setObjectsSelected(s.selectedObjectIds,!1),e.components.selection.forEach((e=>this._withBCFComponent(t,e,(e=>e.selected=!0))))),e.components.translucency&&(s.setObjectsXRayed(s.xrayedObjectIds,!1),e.components.translucency.forEach((e=>this._withBCFComponent(t,e,(e=>e.xrayed=!0))))),e.components.coloring&&e.components.coloring.forEach((e=>{let i=e.color,s=0,r=!1;8===i.length&&(s=parseInt(i.substring(0,2),16)/256,s<=1&&s>=.95&&(s=1),i=i.substring(2),r=!0);const o=[parseInt(i.substring(0,2),16)/256,parseInt(i.substring(2,4),16)/256,parseInt(i.substring(4,6),16)/256];e.components.map((e=>this._withBCFComponent(t,e,(e=>{e.colorize=o,r&&(e.opacity=s)}))))}))}if(e.perspective_camera||e.orthogonal_camera){let a,A,h,c;if(e.perspective_camera?(a=$c(e.perspective_camera.camera_view_point,Kc),A=$c(e.perspective_camera.camera_direction,Kc),h=$c(e.perspective_camera.camera_up_vector,Kc),r.perspective.fov=e.perspective_camera.field_of_view,c="perspective"):(a=$c(e.orthogonal_camera.camera_view_point,Kc),A=$c(e.orthogonal_camera.camera_direction,Kc),h=$c(e.orthogonal_camera.camera_up_vector,Kc),r.ortho.scale=e.orthogonal_camera.view_to_world_scale,c="ortho"),d.subVec3(a,l),r.yUp&&(a=tu(a),A=tu(A),h=tu(h)),o){const e=s.pick({pickSurface:!0,origin:a,direction:A});A=e?e.worldPos:d.addVec3(a,A,Kc)}else A=d.addVec3(a,A,Kc);n?(r.eye=a,r.look=A,r.up=h,r.projection=c):i.cameraFlight.flyTo({eye:a,look:A,up:h,duration:t.duration,projection:c})}}_withBCFComponent(e,t,i){const s=this.viewer,r=s.scene;if(t.authoring_tool_id&&t.originating_system===this.originatingSystem){const o=t.authoring_tool_id,n=r.objects[o];if(n)return void i(n);if(e.updateCompositeObjects){if(s.metaScene.metaObjects[o])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(o),i)}}if(t.ifc_guid){const o=t.ifc_guid,n=r.objects[o];if(n)return void i(n);if(e.updateCompositeObjects){if(s.metaScene.metaObjects[o])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(o),i)}Object.keys(r.models).forEach((t=>{const n=d.globalizeObjectId(t,o),a=r.objects[n];if(a)i(a);else if(e.updateCompositeObjects){s.metaScene.metaObjects[n]&&r.withObjects(s.metaScene.getObjectIDsInSubtree(n),i)}}))}}destroy(){super.destroy()}}function qc(e){return{x:e[0],y:e[1],z:e[2]}}function $c(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function eu(e){return new Float64Array([e[0],-e[2],e[1]])}function tu(e){return new Float64Array([e[0],e[2],-e[1]])}const iu=d.vec3(),su=d.vec3(),ru=(e,t,i,s)=>{var r=e-i,o=t-s;return Math.sqrt(r*r+o*o)};class ou extends R{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var i=this.plugin.viewer.scene;this._originWorld=d.vec3(),this._targetWorld=d.vec3(),this._wp=new Float64Array(24),this._vp=new Float64Array(24),this._pp=new Float64Array(24),this._cp=new Float64Array(8),this._xAxisLabelCulled=!1,this._yAxisLabelCulled=!1,this._zAxisLabelCulled=!1,this._color=t.color||this.plugin.defaultColor;const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))},l=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new me(i,t.origin,this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._targetDot=new me(i,t.target,this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthWire=new ye(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisWire=new ye(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisWire=new ye(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisWire=new ye(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthLabel=new xe(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisLabel=new xe(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisLabel=new xe(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisLabel=new xe(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._measurementOrientation="Horizontal",this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._sectionPlanesDirty=!0,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._useRotationAdjustment=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._xLabelEnabled=!1,this._yLabelEnabled=!1,this._zLabelEnabled=!1,this._lengthLabelEnabled=!1,this._labelsVisible=!1,this._labelsOnWires=!1,this._clickable=!1,this._originDot.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetDot.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=i.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=i.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=i.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.xLabelEnabled=t.xLabelEnabled,this.yLabelEnabled=t.yLabelEnabled,this.zLabelEnabled=t.zLabelEnabled,this.lengthLabelEnabled=t.lengthLabelEnabled,this.labelsVisible=t.labelsVisible,this.labelsOnWires=t.labelsOnWires,this._useRotationAdjustment=t.useRotationAdjustment,this._axesBasis=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}set axesBasis(e){this._axesBasis=e.slice(),this._wpDirty=!0,this._needUpdate(0)}get axesBasis(){return this._axesBasis}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty){const e=d.subVec3(this._targetWorld,this._originWorld,su);this._factors=d.transformVec3(this._axesBasis,e),this._measurementOrientation=function(e,t,i){return Math.abs(t[1]-e[1])>i?"Vertical":"Horizontal"}(this._originWorld,this._targetWorld,0),"Vertical"===this._measurementOrientation&&this._useRotationAdjustment?(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._originWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._originWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1):(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._originWorld[0]+this._axesBasis[0]*this._factors[0],this._wp[5]=this._originWorld[1]+this._axesBasis[4]*this._factors[0],this._wp[6]=this._originWorld[2]+this._axesBasis[8]*this._factors[0],this._wp[7]=1,this._wp[8]=this._originWorld[0]+this._axesBasis[0]*this._factors[0]+this._axesBasis[1]*this._factors[1],this._wp[9]=this._originWorld[1]+this._axesBasis[4]*this._factors[0]+this._axesBasis[5]*this._factors[1],this._wp[10]=this._originWorld[2]+this._axesBasis[8]*this._factors[0]+this._axesBasis[9]*this._factors[1],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1),this._wpDirty=!1,this._vpDirty=!0}if(this._vpDirty&&(d.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._originWorld)||this._isSliced(this._targetWorld))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}const t=this._originDot.viewPos[2],i=this._targetDot.viewPos[2];if(t>-.3||i>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){d.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var s=this._pp,r=this._cp,o=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var n=o.top-t.top,a=o.left-t.left,l=e.canvas.boundary,A=l[2],h=l[3],c=0;const i=this.plugin.viewer.scene.metrics,f=i.scale,g=i.units,m=i.unitsInfo[g].abbrev;for(var u=0,p=s.length;ue.offsetTop+(e.offsetParent&&e.offsetParent!==s.parentNode&&h(e.offsetParent)),c=e=>e.offsetLeft+(e.offsetParent&&e.offsetParent!==s.parentNode&&c(e.offsetParent)),u=d.vec2(),p=e=>{const t=e.snappedCanvasPos||e.canvasPos;r=!0,o.set(e.worldPos),n.set(e.canvasPos),0===this._mouseState?(this._canvasToPagePos?(this._canvasToPagePos(s,t,u),this._markerDiv.style.left=u[0]-5+"px",this._markerDiv.style.top=u[1]-5+"px"):(this._markerDiv.style.left=c(s)+t[0]-5+"px",this._markerDiv.style.top=h(s)+t[1]-5+"px"),this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,this.pointerLens.snapped=!0),this._markerDiv.style.background="greenyellow",this._markerDiv.style.border="2px solid green"):(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red"),A=e.entity):(this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px"),s.style.cursor="pointer",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=this._currentDistanceMeasurementInitState.wireVisible,this._currentDistanceMeasurement.axisVisible=this._currentDistanceMeasurementInitState.axisVisible&&this.distanceMeasurementsPlugin.defaultAxisVisible,this._currentDistanceMeasurement.xAxisVisible=this._currentDistanceMeasurementInitState.xAxisVisible&&this.distanceMeasurementsPlugin.defaultXAxisVisible,this._currentDistanceMeasurement.yAxisVisible=this._currentDistanceMeasurementInitState.yAxisVisible&&this.distanceMeasurementsPlugin.defaultYAxisVisible,this._currentDistanceMeasurement.zAxisVisible=this._currentDistanceMeasurementInitState.zAxisVisible&&this.distanceMeasurementsPlugin.defaultZAxisVisible,this._currentDistanceMeasurement.targetVisible=this._currentDistanceMeasurementInitState.targetVisible,this._currentDistanceMeasurement.target.worldPos=o.slice(),this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px")};this._onHoverSnapOrSurface=i.on("hoverSnapOrSurface",(e=>{this._snapping&&p(e)})),this._onHoverSurface=i.on("hoverSurface",(e=>{this._snapping||p(e)})),s.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(a=e.clientX,l=e.clientY)}),s.addEventListener("mouseup",this._onMouseUp=t=>{1===t.which&&(t.clientX>a+20||t.clientXl+20||t.clientY{this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos),r=!1,this._markerDiv.style.left="-100px",this._markerDiv.style.top="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),s.style.cursor="default"};this._onHoverSnapOrSurfaceOff=i.on("hoverSnapOrSurfaceOff",(e=>{this._snapping&&f(e)})),this._onHoverOff=i.on("hoverOff",(e=>{this._snapping||f(e)})),this._active=!0}deactivate(){if(!this._active)return;this.fire("activated",!1),this.pointerLens&&(this.pointerLens.visible=!1),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onHoverSnapOrSurface),t.off(this._onHoverSurface),t.off(this._onHoverSnapOrSurfaceOff),t.off(this._onHoverOff),this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._mouseState=0)}get currentMeasurement(){return this._currentDistanceMeasurement}destroy(){this.deactivate(),super.destroy()}}class lu extends z{constructor(e,t={}){super("DistanceMeasurements",e),this._pointerLens=t.pointerLens,this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.labelMinAxisLength=t.labelMinAxisLength,this.defaultVisible=!1!==t.defaultVisible,this.defaultOriginVisible=!1!==t.defaultOriginVisible,this.defaultTargetVisible=!1!==t.defaultTargetVisible,this.defaultWireVisible=!1!==t.defaultWireVisible,this.defaultXLabelEnabled=!1!==t.defaultXLabelEnabled,this.defaultYLabelEnabled=!1!==t.defaultYLabelEnabled,this.defaultZLabelEnabled=!1!==t.defaultZLabelEnabled,this.defaultLengthLabelEnabled=!1!==t.defaultLengthLabelEnabled,this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.defaultAxisVisible=!1!==t.defaultAxisVisible,this.defaultXAxisVisible=!1!==t.defaultXAxisVisible,this.defaultYAxisVisible=!1!==t.defaultYAxisVisible,this.defaultZAxisVisible=!1!==t.defaultZAxisVisible,this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.zIndex=t.zIndex||1e4,this.defaultLabelsOnWires=!1!==t.defaultLabelsOnWires,this.useRotationAdjustment=void 0!==t.useRotationAdjustment&&!1!==t.useRotationAdjustment,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,distanceMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get pointerLens(){return this._pointerLens}get control(){return this._defaultControl||(this._defaultControl=new au(this,{})),this._defaultControl}get measurements(){return this._measurements}set labelMinAxisLength(e){e<1&&(this.error("labelMinAxisLength must be >= 1; defaulting to 25"),e=25),this._labelMinAxisLength=e||25}get labelMinAxisLength(){return this._labelMinAxisLength}set useRotationAdjustment(e){e=void 0!==e&&Boolean(e),this._useRotationAdjustment=e}get useRotationAdjustment(){return this._useRotationAdjustment}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,i=e.target,s=new ou(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},target:{entity:i.entity,worldPos:i.worldPos},visible:e.visible,wireVisible:e.wireVisible,axisVisible:!1!==e.axisVisible&&!1!==this.defaultAxisVisible,xAxisVisible:!1!==e.xAxisVisible&&!1!==this.defaultXAxisVisible,yAxisVisible:!1!==e.yAxisVisible&&!1!==this.defaultYAxisVisible,zAxisVisible:!1!==e.zAxisVisible&&!1!==this.defaultZAxisVisible,xLabelEnabled:!1!==e.xLabelEnabled&&!1!==this.defaultXLabelEnabled,yLabelEnabled:!1!==e.yLabelEnabled&&!1!==this.defaultYLabelEnabled,zLabelEnabled:!1!==e.zLabelEnabled&&!1!==this.defaultZLabelEnabled,lengthLabelEnabled:!1!==e.lengthLabelEnabled&&!1!==this.defaultLengthLabelEnabled,labelsVisible:!1!==e.labelsVisible&&!1!==this.defaultLabelsVisible,useRotationAdjustment:this.useRotationAdjustment,originVisible:e.originVisible,targetVisible:e.targetVisible,color:e.color,labelsOnWires:!1!==e.labelsOnWires&&!1!==this.defaultLabelsOnWires,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[s.id]=s,s.clickable=!0,s.on("destroyed",(()=>{delete this._measurements[s.id]})),this.fire("measurementCreated",s),s}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("DistanceMeasurement not found: "+e)}setLabelsShown(e){for(const[t,i]of Object.entries(this.measurements))i.labelShown=e}setAxisVisible(e){for(const[t,i]of Object.entries(this.measurements))i.axisVisible=e;this.defaultAxisVisible=e}getAxisVisible(){return this.defaultAxisVisible}clear(){const e=Object.keys(this._measurements);for(var t=0,i=e.length;t{this.plugin.viewer.cameraControl.active=!1},c=()=>{this.plugin.viewer.cameraControl.active=!0},u=()=>{o&&(clearTimeout(o),o=null),this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),c(),this._touchState=0};i.addEventListener("touchstart",this._onCanvasTouchStart=l=>{const c=l.touches.length;if(1!==c)return void(o&&(clearTimeout(o),o=null));const p=l.touches[0],f=i.getBoundingClientRect(),g=p.clientX-f.left,m=p.clientY-f.top;switch(n.set([g,m]),a.set([g,m]),this._touchState){case 0:if(1!==c&&null!==o)return void u();const i=t.pick({canvasPos:a,snapping:this._snapping,snapToEdge:this._snapping});if(i&&i.snapped)s.set(i.worldPos),this.pointerCircle.start(i.snappedCanvasPos);else{const e=t.pick({canvasPos:a,pickSurface:!0});if(!e||!e.worldPos)return;s.set(e.worldPos),this.pointerCircle.start(e.canvasPos)}o=setTimeout((()=>{1!==c||a[0]>n[0]+r||a[0]n[1]+r||a[1]{if(o=null,1!==c||a[0]>n[0]+r||a[0]n[1]+r||a[1]{this.pointerCircle.stop();const n=r.touches.length;if(1!==n||1!==r.changedTouches.length)return void(o&&(clearTimeout(o),o=null));const l=r.touches[0],h=i.getBoundingClientRect(),c=l.clientX-h.left,u=l.clientY-h.top;if(l.identifier!==A)return;let p,f;switch(a.set([c,u]),this._touchState){case 2:this.pointerLens&&(this.pointerLens.canvasPos=a),p=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),p&&p.snapped?(this.pointerLens&&(this.pointerLens.snappedCanvasPos=p.snappedCanvasPos,this.pointerLens.snapped=!0),s.set(p.worldPos),this._currentDistanceMeasurement?this._currentDistanceMeasurement.origin.worldPos=p.worldPos:(this._currentDistanceMeasurement=e.createMeasurement({id:d.createUUID(),origin:{worldPos:p.worldPos,entity:p.entity},target:{worldPos:p.worldPos,entity:p.entity}}),this._currentDistanceMeasurement.labelsVisible=!1,this._currentDistanceMeasurement.xAxisVisible=!1,this._currentDistanceMeasurement.yAxisVisible=!1,this._currentDistanceMeasurement.zAxisVisible=!1,this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.originVisible=!0,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.clickable=!1),this.distanceMeasurementsPlugin.fire("measurementStart",this._currentDistanceMeasurement)):(f=t.pick({canvasPos:a,pickSurface:!0}),f&&f.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=f.canvasPos,this.pointerLens.snapped=!1),s.set(f.worldPos),this._currentDistanceMeasurement?this._currentDistanceMeasurement.origin.worldPos=f.worldPos:(this._currentDistanceMeasurement=e.createMeasurement({id:d.createUUID(),origin:{worldPos:f.worldPos,entity:f.entity},target:{worldPos:f.worldPos,entity:f.entity}}),this._currentDistanceMeasurement.labelsVisible=!1,this._currentDistanceMeasurement.xAxisVisible=!1,this._currentDistanceMeasurement.yAxisVisible=!1,this._currentDistanceMeasurement.zAxisVisible=!1,this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.originVisible=!0,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.clickable=!1),this.distanceMeasurementsPlugin.fire("measurementStart",this._currentDistanceMeasurement)):this.pointerLens&&(this.pointerLens.cursorPos=null,this.pointerLens.snapped=!1)),this._touchState=2;break;case 5:if(1!==n&&null!==o)return clearTimeout(o),o=null,this.pointerLens&&(this.pointerLens.visible=!1),void(this._touchState=7);this.pointerLens&&(this.pointerLens.canvasPos=a),p=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),p&&p.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=p.snappedCanvasPos,this.pointerLens.snapped=!0),this._currentDistanceMeasurement.target.worldPos=p.worldPos,this._currentDistanceMeasurement.target.entity=p.entity,this._currentDistanceMeasurement.targetVisible=!0,this._currentDistanceMeasurement.wireVisible=!0,this._currentDistanceMeasurement.labelsVisible=!0):(f=t.pick({canvasPos:a,pickSurface:!0}),f&&f.worldPos&&(this.pointerLens&&(this.pointerLens.cursorPos=f.canvasPos,this.pointerLens.snapped=!1),this._currentDistanceMeasurement.target.worldPos=f.worldPos,this._currentDistanceMeasurement.target.entity=f.entity,this._currentDistanceMeasurement.targetVisible=!0,this._currentDistanceMeasurement.wireVisible=!0,this._currentDistanceMeasurement.labelsVisible=!0)),this._touchState=5}}),{passive:!0}),i.addEventListener("touchend",this._onCanvasTouchEnd=s=>{this.pointerCircle.stop();const h=s.changedTouches.length;if(1!==h)return;const u=s.changedTouches[0],p=i.getBoundingClientRect(),f=u.clientX-p.left,g=u.clientY-p.top;if(u.identifier===A)switch(o&&(clearTimeout(o),o=null),l.set([f,g]),this._touchState){case 1:{if(1!==h||f>n[0]+r||fn[1]+r||gn[0]+r||fn[1]+r||g{const o=e=>{const t=r.scene.pick({canvasPos:s,snapToEdge:e,snapToVertex:e,pickSurface:!0});return t&&t.worldPos?t.worldPos:e&&o(!1)};return o(!!t.snapping)},onEnd:(e,t)=>{const i=!d.compareVec3(e,t.worldPos);return i&&this.fire("edited"),i}}),n=e.on("destroyed",o);this._deactivate=function(){e.off("destroyed",n),o()}}deactivate(){this._deactivate(),super.destroy()}}class cu extends hu{constructor(e,t){super(e,t,!0,!1)}}class uu extends hu{constructor(e,t){super(e,t,!1,!0)}}class du extends z{constructor(e,t={}){super("FastNav",e),this._hideColorTexture=!1!==t.hideColorTexture,this._hidePBR=!1!==t.hidePBR,this._hideSAO=!1!==t.hideSAO,this._hideEdges=!1!==t.hideEdges,this._hideTransparentObjects=!!t.hideTransparentObjects,this._scaleCanvasResolution=!!t.scaleCanvasResolution,this._defaultScaleCanvasResolutionFactor=t.defaultScaleCanvasResolutionFactor||1,this._scaleCanvasResolutionFactor=t.scaleCanvasResolutionFactor||.6,this._delayBeforeRestore=!1!==t.delayBeforeRestore,this._delayBeforeRestoreSeconds=t.delayBeforeRestoreSeconds||.5;let i=1e3*this._delayBeforeRestoreSeconds,s=!1;const r=()=>{i=1e3*this._delayBeforeRestoreSeconds,s||(e.scene._renderer.setColorTextureEnabled(!this._hideColorTexture),e.scene._renderer.setPBREnabled(!this._hidePBR),e.scene._renderer.setSAOEnabled(!this._hideSAO),e.scene._renderer.setTransparentEnabled(!this._hideTransparentObjects),e.scene._renderer.setEdgesEnabled(!this._hideEdges),this._scaleCanvasResolution?e.scene.canvas.resolutionScale=this._scaleCanvasResolutionFactor:e.scene.canvas.resolutionScale=this._defaultScaleCanvasResolutionFactor,s=!0)},o=()=>{e.scene.canvas.resolutionScale=this._defaultScaleCanvasResolutionFactor,e.scene._renderer.setEdgesEnabled(!0),e.scene._renderer.setColorTextureEnabled(!0),e.scene._renderer.setPBREnabled(!0),e.scene._renderer.setSAOEnabled(!0),e.scene._renderer.setTransparentEnabled(!0),s=!1};this._onCanvasBoundary=e.scene.canvas.on("boundary",r),this._onCameraMatrix=e.scene.camera.on("matrix",r),this._onSceneTick=e.scene.on("tick",(e=>{s&&(i-=e.deltaTime,(!this._delayBeforeRestore||i<=0)&&o())}));let n=!1;this._onSceneMouseDown=e.scene.input.on("mousedown",(()=>{n=!0})),this._onSceneMouseUp=e.scene.input.on("mouseup",(()=>{n=!1})),this._onSceneMouseMove=e.scene.input.on("mousemove",(()=>{n&&r()}))}get hideColorTexture(){return this._hideColorTexture}set hideColorTexture(e){this._hideColorTexture=e}get hidePBR(){return this._hidePBR}set hidePBR(e){this._hidePBR=e}get hideSAO(){return this._hideSAO}set hideSAO(e){this._hideSAO=e}get hideEdges(){return this._hideEdges}set hideEdges(e){this._hideEdges=e}get hideTransparentObjects(){return this._hideTransparentObjects}set hideTransparentObjects(e){this._hideTransparentObjects=!1!==e}get scaleCanvasResolution(){return this._scaleCanvasResolution}set scaleCanvasResolution(e){this._scaleCanvasResolution=e}get defaultScaleCanvasResolutionFactor(){return this._defaultScaleCanvasResolutionFactor}set defaultScaleCanvasResolutionFactor(e){this._defaultScaleCanvasResolutionFactor=e||1}get scaleCanvasResolutionFactor(){return this._scaleCanvasResolutionFactor}set scaleCanvasResolutionFactor(e){this._scaleCanvasResolutionFactor=e||.6}get delayBeforeRestore(){return this._delayBeforeRestore}set delayBeforeRestore(e){this._delayBeforeRestore=e}get delayBeforeRestoreSeconds(){return this._delayBeforeRestoreSeconds}set delayBeforeRestoreSeconds(e){this._delayBeforeRestoreSeconds=null!=e?e:.5}send(e,t){}destroy(){this.viewer.scene.camera.off(this._onCameraMatrix),this.viewer.scene.canvas.off(this._onCanvasBoundary),this.viewer.scene.input.off(this._onSceneMouseDown),this.viewer.scene.input.off(this._onSceneMouseUp),this.viewer.scene.input.off(this._onSceneMouseMove),this.viewer.scene.off(this._onSceneTick),super.destroy()}}class pu{constructor(e={}){this.cacheBuster=!1!==e.cacheBuster}_cacheBusterURL(e){if(!this.cacheBuster)return e;const t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}getMetaModel(e,t,i){y.loadJSON(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getGLTF(e,t,i){y.loadArraybuffer(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getGLB(e,t,i){y.loadArraybuffer(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getArrayBuffer(e,t,i,s){!function(e,t,i,s){var r=()=>{};i=i||r,s=s||r;const o=/^data:(.*?)(;base64)?,(.*)$/,n=t.match(o);if(n){const e=!!n[2];var a=n[3];a=window.decodeURIComponent(a),e&&(a=window.atob(a));try{const e=new ArrayBuffer(a.length),t=new Uint8Array(e);for(var l=0;l{i(e)}),(function(e){s(e)}))}}class fu{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const i=this._messages[this._locale];if(!i)return null;const s=gu(e,i);return s?t?mu(s,t):s:null}translatePlurals(e,t,i){const s=this._messages[this._locale];if(!s)return null;let r=gu(e,s);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=mu(r,[t]),i&&(r=mu(r,i)),r):null}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];if(s)for(const e in s)if(s.hasOwnProperty(e)){s[e].callback(t)}}on(t,i){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let s=this._eventSubs[t];s||(s={},this._eventSubs[t]=s);const r=this._eventSubIDMap.addItem();s[r]={callback:i},this._eventSubEvents[r]=t;const o=this._events[t];return void 0!==o&&i(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const i=this._eventSubs[t];i&&delete i[e],this._eventSubIDMap.removeItem(e)}}}function gu(e,t){if(t[e])return t[e];const i=e.split(".");let s=t;for(let e=0,t=i.length;s&&e1?1:e}get t(){return this._t}get tangent(){return this.getTangent(this._t)}get length(){var e=this._getLengths();return e[e.length-1]}getTangent(e){var t=1e-4;void 0===e&&(e=this._t);var i=e-t,s=e+t;i<0&&(i=0),s>1&&(s=1);var r=this.getPoint(i),o=this.getPoint(s),n=d.subVec3(o,r,[]);return d.normalizeVec3(n,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,i=[];for(t=0;t<=e;t++)i.push(this.getPoint(t/e));return i}_getLengths(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,i,s=[],r=this.getPoint(0),o=0;for(s.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),o+=d.lenVec3(d.subVec3(t,r,[])),s.push(o),r=t;return this.cacheArcLengths=s,s}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var i,s=this._getLengths(),r=0,o=s.length;i=t||e*s[o-1];for(var n,a=0,l=o-1;a<=l;)if((n=s[r=Math.floor(a+(l-a)/2)]-i)<0)a=r+1;else{if(!(n>0)){l=r;break}l=r-1}if(s[r=l]===i)return r/(o-1);var A=s[r];return(r+(i-A)/(s[r+1]-A))/(o-1)}}class vu extends _u{constructor(e,t={}){super(e,t),this.points=t.points,this.t=t.t}set points(e){this._points=e||[]}get points(){return this._points}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=this.points;if(!(t.length<3)){var i=(t.length-1)*e,s=Math.floor(i),r=i-s,o=t[0===s?s:s-1],n=t[s],a=t[s>t.length-2?t.length-1:s+1],l=t[s>t.length-3?t.length-1:s+2],A=d.vec3();return A[0]=d.catmullRomInterpolate(o[0],n[0],a[0],l[0],r),A[1]=d.catmullRomInterpolate(o[1],n[1],a[1],l[1],r),A[2]=d.catmullRomInterpolate(o[2],n[2],a[2],l[2],r),A}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}getJSON(){return{points:points,t:this._t}}}const bu=d.vec3();class yu extends R{get type(){return"CameraPath"}constructor(e,t={}){super(e,t),this._frames=[],this._eyeCurve=new vu(this),this._lookCurve=new vu(this),this._upCurve=new vu(this),t.frames&&(this.addFrames(t.frames),this.smoothFrameTimes(1))}get frames(){return this._frames}get eyeCurve(){return this._eyeCurve}get lookCurve(){return this._lookCurve}get upCurve(){return this._upCurve}saveFrame(e){const t=this.scene.camera;this.addFrame(e,t.eye,t.look,t.up)}addFrame(e,t,i,s){const r={t:e,eye:t.slice(0),look:i.slice(0),up:s.slice(0)};this._frames.push(r),this._eyeCurve.points.push(r.eye),this._lookCurve.points.push(r.look),this._upCurve.points.push(r.up)}addFrames(e){let t;for(let i=0,s=e.length;i1?1:e,t.eye=this._eyeCurve.getPoint(e,bu),t.look=this._lookCurve.getPoint(e,bu),t.up=this._upCurve.getPoint(e,bu)}sampleFrame(e,t,i,s){e=e<0?0:e>1?1:e,this._eyeCurve.getPoint(e,t),this._lookCurve.getPoint(e,i),this._upCurve.getPoint(e,s)}smoothFrameTimes(e){if(0===this._frames.length)return;const t=d.vec3();var i=0;this._frames[0].t=0;const s=[];for(let e=1,o=this._frames.length;e=1;e>1&&(e=1);const i=this.easing?Mu._ease(e,0,1,1):e,s=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(d.subVec3(s.eye,s.look,Cu),s.eye=d.lerpVec3(i,0,1,this._eye1,this._eye2,wu),s.look=d.subVec3(wu,Cu,Bu)):this._flyingLook&&(s.look=d.lerpVec3(i,0,1,this._look1,this._look2,Bu),s.up=d.lerpVec3(i,0,1,this._up1,this._up2,Pu)):this._flyingEyeLookUp&&(s.eye=d.lerpVec3(i,0,1,this._eye1,this._eye2,wu),s.look=d.lerpVec3(i,0,1,this._look1,this._look2,Bu),s.up=d.lerpVec3(i,0,1,this._up1,this._up2,Pu)),this._projection2){const t="ortho"===this._projection2?Mu._easeOutExpo(e,0,1,1):Mu._easeInCubic(e,0,1,1);s.customProjection.matrix=d.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else s.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return s.ortho.scale=this._orthoScale2,void this.stop();I.scheduleTask(this._update,this)}static _ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}static _easeInCubic(e,t,i,s){return i*(e/=s)*e*e+t}static _easeOutExpo(e,t,i,s){return i*(1-Math.pow(2,-10*e/s))+t}stop(){if(!this._flying)return;this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);const e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}cancel(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}set duration(e){this._duration=e?1e3*e:500,this.stop()}get duration(){return this._duration/1e3}set fit(e){this._fit=!1!==e}get fit(){return this._fit}set fitFOV(e){this._fitFOV=e||45}get fitFOV(){return this._fitFOV}set trail(e){this._trail=!!e}get trail(){return this._trail}destroy(){this.stop(),super.destroy()}}class Eu extends R{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new Mu(this),this._t=0,this.state=Eu.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,i;const s=performance.now(),r=this._lastTime?.001*(s-this._lastTime):0;if(this._lastTime=s,0!==r)switch(this.state){case Eu.SCRUBBING:return;case Eu.PLAYING:if(this._t+=this._playingRate*r,t=this._cameraPath.frames.length,0===t||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=Eu.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case Eu.PLAYING_TO:i=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&i<=this._playingToT||this._playingDir>0&&i>=this._playingToT)&&(i=this._playingToT,this.state=Eu.SCRUBBING,this.fire("stopped")),this._t=i,e.loadFrame(this._t)}}_ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}set cameraPath(e){this._cameraPath=e}get cameraPath(){return this._cameraPath}set rate(e){this._playingRate=e}get rate(){return this._playingRate}play(){this._cameraPath&&(this._lastTime=null,this.state=Eu.PLAYING)}playToT(e){this._cameraPath&&(this._playingFromT=this._t,this._playingToT=e,this._playingDir=this._playingToT-this._playingFromT<0?-1:1,this._lastTime=null,this.state=Eu.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const i=t.frames[e];i?this.playToT(i.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const i=this._cameraPath;if(!i)return;const s=i.frames[e];s?(this.state=Eu.SCRUBBING,this._cameraFlightAnimation.flyTo(s,t)):this.error("flyToFrame - frame index out of range: "+e)}scrubToT(e){const t=this._cameraPath;if(!t)return;this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=Eu.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=Eu.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=Eu.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}Eu.STOPPED=0,Eu.SCRUBBING=1,Eu.PLAYING=2,Eu.PLAYING_TO=3;const Fu=d.vec3(),Iu=d.vec3();d.vec3();const Du=d.vec3([0,-1,0]),Su=d.vec4([0,0,0,1]);class Tu extends R{constructor(e,t={}){super(e,t),this._src=null,this._image=null,this._pos=d.vec3(),this._origin=d.vec3(),this._rtcPos=d.vec3(),this._dir=d.vec3(),this._size=1,this._imageSize=d.vec2(),this._texture=new so(this),this._plane=new wr(this,{geometry:new ei(this,fo({center:[0,0,0],xSize:1,zSize:1,xSegments:10,zSegments:10})),material:new oi(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0}),clippable:t.clippable}),this._grid=new wr(this,{geometry:new ei(this,po({size:1,divisions:10})),material:new oi(this,{diffuse:[0,0,0],ambient:[0,0,0],emissive:[.2,.8,.2]}),position:[0,.001,0],clippable:t.clippable}),this._node=new Vr(this,{rotation:[0,0,0],position:[0,0,0],scale:[1,1,1],clippable:!1,children:[this._plane,this._grid]}),this._gridVisible=!1,this.visible=!0,this.gridVisible=t.gridVisible,this.position=t.position,this.rotation=t.rotation,this.dir=t.dir,this.size=t.size,this.collidable=t.collidable,this.clippable=t.clippable,this.pickable=t.pickable,this.opacity=t.opacity,t.image?this.image=t.image:this.src=t.src}set visible(e){this._plane.visible=e,this._grid.visible=this._gridVisible&&e}get visible(){return this._plane.visible}set gridVisible(e){e=!1!==e,this._gridVisible=e,this._grid.visible=this._gridVisible&&this.visible}get gridVisible(){return this._gridVisible}set image(e){this._image=e,this._image&&(this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}get image(){return this._image}set src(e){if(this._src=e,this._src){this._image=null;const e=new Image;e.onload=()=>{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set position(e){this._pos.set(e||[0,0,0]),Y(this._pos,this._origin,this._rtcPos),this._node.origin=this._origin,this._node.position=this._rtcPos}get position(){return this._pos}set rotation(e){this._node.rotation=e}get rotation(){return this._node.rotation}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set dir(e){if(this._dir.set(e||[0,0,-1]),e){const t=this.scene.center,i=[-this._dir[0],-this._dir[1],-this._dir[2]];d.subVec3(t,this.position,Fu);const s=-d.dotVec3(i,Fu);d.normalizeVec3(i),d.mulVec3Scalar(i,s,Iu),d.vec3PairToQuaternion(Du,e,Su),this._node.quaternion=Su}}get dir(){return this._dir}set collidable(e){this._node.collidable=!1!==e}get collidable(){return this._node.collidable}set clippable(e){this._node.clippable=!1!==e}get clippable(){return this._node.clippable}set pickable(e){this._node.pickable=!1!==e}get pickable(){return this._node.pickable}set opacity(e){this._node.opacity=e}get opacity(){return this._node.opacity}destroy(){super.destroy()}_updatePlaneSizeFromImage(){const e=this._size,t=this._imageSize[0],i=this._imageSize[1];if(t>i){const s=i/t;this._node.scale=[e,1,e*s]}else{const s=t/i;this._node.scale=[e*s,1,e]}}}class Ru extends Qt{get type(){return"PointLight"}constructor(e,t={}){super(e,t);const i=this;this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const s=this.scene.camera,r=this.scene.canvas;this._onCameraViewMatrix=s.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=s.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=r.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new _t({type:"point",pos:d.vec3([1,1,1]),color:d.vec3([.7,.7,.8]),intensity:1,attenuation:[0,0,0],space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(i._shadowViewMatrixDirty){i._shadowViewMatrix||(i._shadowViewMatrix=d.identityMat4());const e=i._state.pos,t=s.look,r=s.up;d.lookAtMat4v(e,t,r,i._shadowViewMatrix),i._shadowViewMatrixDirty=!1}return i._shadowViewMatrix},getShadowProjMatrix:()=>{if(i._shadowProjMatrixDirty){i._shadowProjMatrix||(i._shadowProjMatrix=d.identityMat4());const e=i.scene.canvas.canvas;d.perspectiveMat4(Math.PI/180*70,e.clientWidth/e.clientHeight,.1,500,i._shadowProjMatrix),i._shadowProjMatrixDirty=!1}return i._shadowProjMatrix},getShadowRenderBuf:()=>(i._shadowRenderBuf||(i._shadowRenderBuf=new ut(i.scene.canvas.canvas,i.scene.canvas.gl,{size:[1024,1024]})),i._shadowRenderBuf)}),this.pos=t.pos,this.color=t.color,this.intensity=t.intensity,this.constantAttenuation=t.constantAttenuation,this.linearAttenuation=t.linearAttenuation,this.quadraticAttenuation=t.quadraticAttenuation,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set pos(e){this._state.pos.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get pos(){return this._state.pos}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set constantAttenuation(e){this._state.attenuation[0]=e||0,this.glRedraw()}get constantAttenuation(){return this._state.attenuation[0]}set linearAttenuation(e){this._state.attenuation[1]=e||0,this.glRedraw()}get linearAttenuation(){return this._state.attenuation[1]}set quadraticAttenuation(e){this._state.attenuation[2]=e||0,this.glRedraw()}get quadraticAttenuation(){return this._state.attenuation[2]}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}function Lu(e){if(!Uu(e.width)||!Uu(e.height)){const t=document.createElement("canvas");t.width=ku(e.width),t.height=ku(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function Uu(e){return 0==(e&e-1)}function ku(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class Ou extends R{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const i=this.scene.canvas.gl;this._state=new _t({texture:new Zr({gl:i,target:i.TEXTURE_CUBE_MAP}),flipY:this._checkFlipY(t.minFilter),encoding:this._checkEncoding(t.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),this._src=t.src,this._images=[],this._loadSrc(t.src),m.memory.textures++}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}_loadSrc(e){const t=this,i=this.scene.canvas.gl;this._images=[];let s=!1,r=0;for(let o=0;o{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set collidable(e){this._mesh.collidable=!1!==e}get collidable(){return this._mesh.collidable}set clippable(e){this._mesh.clippable=!1!==e}get clippable(){return this._mesh.clippable}set pickable(e){this._mesh.pickable=!1!==e}get pickable(){return this._mesh.pickable}set opacity(e){this._mesh.opacity=e}get opacity(){return this._mesh.opacity}_updatePlaneSizeFromImage(){const e=.5*this._size,t=this._imageSize[0],i=this._imageSize[1],s=i/t;this._geometry.positions=t>i?[e,e*s,0,-e,e*s,0,-e,-e*s,0,e,-e*s,0]:[e/s,e,0,-e/s,e,0,-e/s,-e,0,e/s,-e,0]}}class Hu{constructor(e){this._eye=d.vec3(),this._look=d.vec3(),this._up=d.vec3(),this._projection={},e&&this.saveCamera(e)}saveCamera(e){const t=e.camera,i=t.project;switch(this._eye.set(t.eye),this._look.set(t.look),this._up.set(t.up),t.projection){case"perspective":this._projection={projection:"perspective",fov:i.fov,fovAxis:i.fovAxis,near:i.near,far:i.far};break;case"ortho":this._projection={projection:"ortho",scale:i.scale,near:i.near,far:i.far};break;case"frustum":this._projection={projection:"frustum",left:i.left,right:i.right,top:i.top,bottom:i.bottom,near:i.near,far:i.far};break;case"custom":this._projection={projection:"custom",matrix:i.matrix.slice()}}}restoreCamera(e,t){const i=e.camera,s=this._projection;function r(){switch(s.type){case"perspective":i.perspective.fov=s.fov,i.perspective.fovAxis=s.fovAxis,i.perspective.near=s.near,i.perspective.far=s.far;break;case"ortho":i.ortho.scale=s.scale,i.ortho.near=s.near,i.ortho.far=s.far;break;case"frustum":i.frustum.left=s.left,i.frustum.right=s.right,i.frustum.top=s.top,i.frustum.bottom=s.bottom,i.frustum.near=s.near,i.frustum.far=s.far;break;case"custom":i.customProjection.matrix=s.matrix}}t?e.viewer.cameraFlight.flyTo({eye:this._eye,look:this._look,up:this._up,orthoScale:s.scale,projection:s.projection},(()=>{r(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,r(),i.projection=s.projection)}}const ju=d.vec3();class Gu{constructor(e){if(this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsOpacity=[],this.numObjects=0,e){const t=e.metaScene.scene;this.saveObjects(t,e)}}saveObjects(e,t,i){this.numObjects=0,this._mask=i?y.apply(i,{}):null;const s=!i||i.visible,r=!i||i.edges,o=!i||i.xrayed,n=!i||i.highlighted,a=!i||i.selected,l=!i||i.clippable,A=!i||i.pickable,h=!i||i.colorize,c=!i||i.opacity,u=t.metaObjects,d=e.objects;for(let e=0,t=u.length;e1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=d.vec3();return t[0]=d.b3(e,this._v0[0],this._v1[0],this._v2[0],this._v3[0]),t[1]=d.b3(e,this._v0[1],this._v1[1],this._v2[1],this._v3[1]),t[2]=d.b3(e,this._v0[2],this._v1[2],this._v2[2],this._v3[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,v3:this._v3,t:this._t}}}class Xu extends _u{constructor(e,t={}){super(e,t),this._cachedLengths=[],this._dirty=!0,this._curves=[],this._t=0,this._dirtySubs=[],this._destroyedSubs=[],this.curves=t.curves||[],this.t=t.t}addCurve(e){this._curves.push(e),this._dirty=!0}set curves(e){var t,i,s;for(e=e||[],i=0,s=this._curves.length;i1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}get length(){var e=this._getCurveLengths();return e[e.length-1]}getPoint(e){for(var t,i=e*this.length,s=this._getCurveLengths(),r=0;r=i){var o=1-(s[r]-i)/(t=this._curves[r]).length;return t.getPointAt(o)}r++}return null}_getCurveLengths(){if(!this._dirty)return this._cachedLengths;var e,t=[],i=0,s=this._curves.length;for(e=0;e1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=d.vec3();return t[0]=d.b2(e,this._v0[0],this._v1[0],this._v2[0]),t[1]=d.b2(e,this._v0[1],this._v1[1],this._v2[1]),t[2]=d.b2(e,this._v0[2],this._v1[2],this._v2[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,t:this._t}}}class Yu extends Gc{constructor(e,t={}){super(e,t)}}class Zu extends R{constructor(e,t={}){super(e,t),this._skyboxMesh=new wr(this,{geometry:new ei(this,{primitive:"triangles",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]}),background:!0,scale:[2e3,2e3,2e3],rotation:[0,-90,0],material:new oi(this,{ambient:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],emissive:[1,1,1],emissiveMap:new so(this,{src:t.src,flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge",encoding:t.encoding||"sRGB"}),backfaces:!0}),visible:!1,pickable:!1,clippable:!1,collidable:!1}),this.size=t.size,this.active=t.active}set size(e){this._size=e||1e3,this._skyboxMesh.scale=[this._size,this._size,this._size]}get size(){return this._size}set active(e){this._skyboxMesh.visible=e}get active(){return this._skyboxMesh.visible}}class qu{transcode(e,t,i={}){}destroy(){}}const $u=d.vec4(),ed=d.vec4(),td=d.vec3(),id=d.vec3(),sd=d.vec3(),rd=d.vec4(),od=d.vec4(),nd=d.vec4();class ad{constructor(e){this._scene=e}dollyToCanvasPos(e,t,i){let s=!1;const r=this._scene.camera;if(e){const t=d.subVec3(e,r.eye,td);s=d.lenVec3(t){this._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(()=>{this._cameraDirty=!0})),this._onTick=this._scene.on("tick",(()=>{this.updatePivotElement(),this.updatePivotSphere()}))}createPivotSphere(){const e=this.getPivotPos(),t=d.vec3();d.decomposeMat4(d.inverseMat4(this._scene.viewer.camera.viewMatrix,d.mat4()),t,d.vec4(),d.vec3());const i=d.distVec3(t,e);let s=Math.tan(Math.PI/500)*i*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(s/=this._scene.camera.ortho.scale/2),Y(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new ao(this._scene,Mr({radius:s})),this._pivotSphere=new wr(this._scene,{geometry:this._pivotSphereGeometry,material:this._pivotSphereMaterial,pickable:!1,position:this._rtcPos,rtcCenter:this._rtcCenter})}destroyPivotSphere(){this._pivotSphere&&(this._pivotSphere.destroy(),this._pivotSphere=null),this._pivotSphereGeometry&&(this._pivotSphereGeometry.destroy(),this._pivotSphereGeometry=null)}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){d.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,d.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const i=t.boundary,s=i[2],r=i[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*s/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*r/2);let o=t._lastBoundingClientRect;if(!o||t._canvasSizeChanged){const e=t.canvas;o=t._lastBoundingClientRect=e.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(o.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(o.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}updatePivotSphere(){this._pivoting&&this._pivotSphere&&(Y(this.getPivotPos(),this._rtcCenter,this._rtcPos),d.compareVec3(this._rtcPos,this._pivotSphere.position)||(this.destroyPivotSphere(),this.createPivotSphere()))}setPivotElement(e){this._pivotElement=e}enablePivotSphere(e={}){this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);const t=e.color||[1,0,0];this._pivotSphereMaterial=new oi(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}disablePivotSphere(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}startPivot(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;const e=this._scene.camera;let t=d.lookAtMat4v(e.eye,e.look,e.worldUp);d.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const i=this.getPivotPos();this._cameraOffset[2]+=d.distVec3(e.eye,i),t=d.inverseMat4(t);const s=d.transformVec3(t,this._cameraOffset),r=d.vec3();if(d.subVec3(e.eye,i,r),d.addVec3(r,s),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=d.lenVec3(r),this._polar=Math.acos(r[1]/this._radius),this._azimuth=Math.atan2(r[0],r[2]),this._pivoting=!0}_cameraLookingDownwards(){const e=this._scene.camera,t=d.normalizeVec3(d.subVec3(e.look,e.eye,ld)),i=d.cross3Vec3(t,e.worldUp,Ad);return d.sqLenVec3(i)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}setCanvasPivotPos(e){const t=this._scene.camera,i=Math.abs(d.distVec3(this._scene.center,t.eye)),s=t.project.transposedMatrix,r=s.subarray(8,12),o=s.subarray(12),n=[0,0,-1,1],a=d.dotVec4(n,r)/d.dotVec4(n,o),l=cd;t.project.unproject(e,a,ud,dd,l);const A=d.normalizeVec3(d.subVec3(l,t.eye,ld)),h=d.addVec3(t.eye,d.mulVec3Scalar(A,i,Ad),hd);this.setPivotPos(h)}getPivotPos(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const i=this._scene.camera;var s=-e;const r=-t;1===i.worldUp[2]&&(s=-s),this._azimuth+=.01*-s,this._polar+=.01*r,this._polar=d.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 n=d.lenVec3(d.subVec3(i.look,i.eye,d.vec3())),a=this.getPivotPos();d.addVec3(o,a);let l=d.lookAtMat4v(o,a,i.worldUp);l=d.inverseMat4(l);const A=d.transformVec3(l,this._cameraOffset);l[12]-=A[0],l[13]-=A[1],l[14]-=A[2];const h=[l[8],l[9],l[10]];i.eye=[l[12],l[13],l[14]],d.subVec3(i.eye,d.mulVec3Scalar(h,n),i.look),i.up=[l[4],l[5],l[6]],this.showPivot()}showPivot(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}hidePivot(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}endPivot(){this._pivoting=!1}destroy(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}class fd{constructor(e,t){this._scene=e.scene,this._cameraControl=e,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=t,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=d.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;const e=`${~~this.pickCursorPos[0]}-${~~this.pickCursorPos[1]}-${this.scheduleSnapOrPick}-${this.schedulePickSurface}-${this.schedulePickEntity}`;if(this._lastHash===e)return;this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;const t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){const e=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});e&&(e.snappedToEdge||e.snappedToVertex)?(this.snapPickResult=e,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const e=this.pickResult.canvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){const e=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){const e=new Ge;e.entity=this.snapPickResult.entity,e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){const e=this.pickResult.entity.id;this._lastPickedEntityId!==e&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=e)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}const gd=d.vec2();class md{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController;let n,a,l,A=0,h=0,c=0,u=0,p=!1;const f=d.vec3();let g=!0;const m=this._scene.canvas.canvas,_=[];function v(e=!0){m.style.cursor="move",A=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],c=s.pointerCanvasPos[0],u=s.pointerCanvasPos[1],e&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(p=!0,f.set(o.pickResult.worldPos)):p=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!1}),m.addEventListener("mousedown",this._mouseDownHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:_[e.input.KEY_SHIFT]||i.planView?(n=!0,v()):(n=!0,v(!1));break;case 2:a=!0,v();break;case 3:l=!0,i.panRightClick&&v()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(!n&&!a&&!l)return;const o=e.canvas.boundary,c=o[2],u=o[3],g=s.pointerCanvasPos[0],m=s.pointerCanvasPos[1],v=_[e.input.KEY_SHIFT]||i.planView||!i.panRightClick&&a||i.panRightClick&&l,b=document.pointerLockElement?t.movementX:g-A,y=document.pointerLockElement?t.movementY:m-h;if(v){const t=e.camera;if("perspective"===t.projection){const i=Math.abs(p?d.lenVec3(d.subVec3(f,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(t.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*b*i/u,r.panDeltaY+=1.5*y*i/u}else r.panDeltaX+=.5*t.ortho.scale*(b/u),r.panDeltaY+=.5*t.ortho.scale*(y/u)}else!n||a||l||i.planView||(i.firstPerson?(r.rotateDeltaY-=b/c*i.dragRotationRate/2,r.rotateDeltaX+=y/u*(i.dragRotationRate/4)):(r.rotateDeltaY-=b/c*(1.5*i.dragRotationRate),r.rotateDeltaX+=y/u*(1.5*i.dragRotationRate)));A=g,h=m}),m.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{i.active&&i.pointerEnabled&&s.mouseover&&(g=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{if(i.active&&i.pointerEnabled)switch(e.which){case 1:case 2:case 3:n=!1,a=!1,l=!1}}),m.addEventListener("mouseup",this._mouseUpHandler=e=>{if(i.active&&i.pointerEnabled){if(3===e.which){!function(e,t){if(e){let i=e.target,s=0,r=0,o=0,n=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,o+=i.scrollLeft,n+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+o-s,t[1]=e.pageY+n-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,gd);const i=gd[0],s=gd[1];Math.abs(i-c)<3&&Math.abs(s-u)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:gd,event:e},!0)}m.style.removeProperty("cursor")}}),m.addEventListener("mouseenter",this._mouseEnterHandler=()=>{i.active&&i.pointerEnabled});const b=1/60;let y=null;m.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!(i.active&&i.pointerEnabled&&i.zoomOnMouseWheel))return;const t=performance.now()/1e3;var o=null!==y?t-y:0;y=t,o>.05&&(o=.05),o{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover)return;const n=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),a=r._isKeyDownForAction(r.AXIS_VIEW_BACK),l=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),A=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),h=r._isKeyDownForAction(r.AXIS_VIEW_TOP),c=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(n||a||l||A||h||c))return;const u=e.aabb,p=d.getAABB3Diag(u);d.getAABB3Center(u,_d);const f=Math.abs(p/Math.tan(t.cameraFlight.fitFOV*d.DEGTORAD)),g=1.1*p;Bd.orthoScale=g,n?(Bd.eye.set(d.addVec3(_d,d.mulVec3Scalar(o.worldRight,f,vd),xd)),Bd.look.set(_d),Bd.up.set(o.worldUp)):a?(Bd.eye.set(d.addVec3(_d,d.mulVec3Scalar(o.worldForward,f,vd),xd)),Bd.look.set(_d),Bd.up.set(o.worldUp)):l?(Bd.eye.set(d.addVec3(_d,d.mulVec3Scalar(o.worldRight,-f,vd),xd)),Bd.look.set(_d),Bd.up.set(o.worldUp)):A?(Bd.eye.set(d.addVec3(_d,d.mulVec3Scalar(o.worldForward,-f,vd),xd)),Bd.look.set(_d),Bd.up.set(o.worldUp)):h?(Bd.eye.set(d.addVec3(_d,d.mulVec3Scalar(o.worldUp,f,vd),xd)),Bd.look.set(_d),Bd.up.set(d.normalizeVec3(d.mulVec3Scalar(o.worldForward,1,bd),yd))):c&&(Bd.eye.set(d.addVec3(_d,d.mulVec3Scalar(o.worldUp,-f,vd),xd)),Bd.look.set(_d),Bd.up.set(d.normalizeVec3(d.mulVec3Scalar(o.worldForward,-1,bd)))),!i.firstPerson&&i.followPointer&&t.pivotController.setPivotPos(_d),t.cameraFlight.duration>0?t.cameraFlight.flyTo(Bd,(()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(Bd),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class Pd{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;let l=!1,A=!1;const h=this._scene.canvas.canvas,c=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i&&i.entity?i.entity.aabb:e.aabb;if(s){const i=e.camera;d.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})},u=e.tickify(this._canvasMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(l||A)return;if(a.hasSubs("rayMove")){const t=d.vec3(),i=d.vec3();d.canvasPosToWorldRay(e.canvas.canvas,e.camera.viewMatrix,e.camera.projMatrix,e.camera.projection,s.pointerCanvasPos,t,i),a.fire("rayMove",{canvasPos:s.pointerCanvasPos,ray:{origin:t,direction:i,canvasPos:s.pointerCanvasPos}},!0)}const r=a.hasSubs("hover"),n=a.hasSubs("hoverEnter"),h=a.hasSubs("hoverOut"),c=a.hasSubs("hoverOff"),u=a.hasSubs("hoverSurface"),p=a.hasSubs("hoverSnapOrSurface");if(r||n||h||c||u||p)if(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=u,o.scheduleSnapOrPick=p,o.update(),o.pickResult){if(o.pickResult.entity){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),a.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t)}a.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&a.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),a.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)});h.addEventListener("mousemove",u),h.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(l=!0),3===t.which&&(A=!0);if(1===t.which&&i.active&&i.pointerEnabled&&(s.mouseDownClientX=t.clientX,s.mouseDownClientY=t.clientY,s.mouseDownCursorX=s.pointerCanvasPos[0],s.mouseDownCursorY=s.pointerCanvasPos[1],!i.firstPerson&&i.followPointer&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===t.which))){const t=o.pickResult;t&&t.worldPos?(n.setPivotPos(t.worldPos),n.startPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),n.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(l=!1),3===e.which&&(A=!1),n.getPivoting()&&n.endPivot()}),h.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!i.active||!i.pointerEnabled)return;if(!(1===r.which))return;if(n.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const l=a.hasSubs("picked"),A=a.hasSubs("pickedNothing"),h=a.hasSubs("pickedSurface"),u=a.hasSubs("doublePicked"),p=a.hasSubs("doublePickedSurface"),f=a.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||u||p||f))return(l||A||h)&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=h,o.update(),o.pickResult?(a.fire("picked",o.pickResult,!0),o.pickedSurface&&a.fire("pickedSurface",o.pickResult,!0)):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=h,o.update();const e=o.pickResult,r=o.pickedSurface;this._timeout=setTimeout((()=>{e&&e.worldPos?(a.fire("picked",e,!0),r&&(a.fire("pickedSurface",e,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),this._clicks=0}),i.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo||u||p,o.schedulePickSurface=o.schedulePickEntity&&p,o.update(),o.pickResult){if(a.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&a.fire("doublePickedSurface",o.pickResult,!0),i.doublePickFlyTo&&(c(o.pickResult),!i.firstPerson&&i.followPointer)){const e=o.pickResult.entity.aabb,i=d.getAABB3Center(e);t.pivotController.setPivotPos(i),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(a.fire("doublePickedNothing",{canvasPos:s.pointerCanvasPos},!0),i.doublePickFlyTo&&(c(),!i.firstPerson&&i.followPointer)){const i=e.aabb,s=d.getAABB3Center(i);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}this._clicks=0}},!1)}reset(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}class Cd{constructor(e,t,i,s,r){this._scene=e;const o=e.input,n=[],a=e.canvas.canvas;let l=!0;this._onSceneMouseMove=o.on("mousemove",(()=>{l=!0})),this._onSceneKeyDown=o.on("keydown",(t=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover||(n[t]=!0,t===o.KEY_SHIFT&&(a.style.cursor="move")))})),this._onSceneKeyUp=o.on("keyup",(s=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(n[s]=!1,s===o.KEY_SHIFT&&(a.style.cursor=null),t.pivotController.getPivoting()&&t.pivotController.endPivot())})),this._onTick=e.on("tick",(a=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover)return;const A=t.cameraControl,h=a.deltaTime/1e3;if(!i.planView){const e=A._isKeyDownForAction(A.ROTATE_Y_POS,n),s=A._isKeyDownForAction(A.ROTATE_Y_NEG,n),o=A._isKeyDownForAction(A.ROTATE_X_POS,n),a=A._isKeyDownForAction(A.ROTATE_X_NEG,n),l=h*i.keyboardRotationRate;(e||s||o||a)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:s&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:a&&(r.rotateDeltaX-=l),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!n[o.KEY_CTRL]&&!n[o.KEY_ALT]){const e=A._isKeyDownForAction(A.DOLLY_BACKWARDS,n),o=A._isKeyDownForAction(A.DOLLY_FORWARDS,n);if(e||o){const n=h*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=n:e&&(r.dollyDelta+=n),l&&(s.followPointerDirty=!0,l=!1)}}const c=A._isKeyDownForAction(A.PAN_FORWARDS,n),u=A._isKeyDownForAction(A.PAN_BACKWARDS,n),d=A._isKeyDownForAction(A.PAN_LEFT,n),p=A._isKeyDownForAction(A.PAN_RIGHT,n),f=A._isKeyDownForAction(A.PAN_UP,n),g=A._isKeyDownForAction(A.PAN_DOWN,n),m=(n[o.KEY_ALT]?.3:1)*h*i.keyboardPanRate;(c||u||d||p||f||g)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),g?r.panDeltaY+=m:f&&(r.panDeltaY+=-m),p?r.panDeltaX+=-m:d&&(r.panDeltaX+=m),u?r.panDeltaZ+=m:c&&(r.panDeltaZ+=-m))}))}reset(){}destroy(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),this._scene.input.off(this._onSceneKeyUp)}}const Md=d.vec3();class Ed{constructor(e,t,i,s,r){this._scene=e;const o=e.camera,n=t.pickController,a=t.pivotController,l=t.panController;let A=1,h=1,c=null;this._onTick=e.on("tick",(()=>{if(!i.active||!i.pointerEnabled)return;let t="default";if(Math.abs(r.dollyDelta)<.001&&(r.dollyDelta=0),Math.abs(r.rotateDeltaX)<.001&&(r.rotateDeltaX=0),Math.abs(r.rotateDeltaY)<.001&&(r.rotateDeltaY=0),0===r.rotateDeltaX&&0===r.rotateDeltaY||(r.dollyDelta=0),i.followPointer){if(--A<=0&&(A=1,0!==r.dollyDelta)){if(0===r.rotateDeltaY&&0===r.rotateDeltaX&&i.followPointer&&s.followPointerDirty&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),n.pickResult&&n.pickResult.worldPos?c=n.pickResult.worldPos:(h=1,c=null),s.followPointerDirty=!1),c){const t=Math.abs(d.lenVec3(d.subVec3(c,e.camera.eye,Md)));h=t/i.dollyProximityThreshold}h{s.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{s.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{Id(e,o,s.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=e=>{i.active&&i.pointerEnabled&&(Id(e,o,s.pointerCanvasPos),s.mouseover=!0)}),o.addEventListener("mouseup",this._mouseUpHandler=e=>{i.active&&i.pointerEnabled})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}function Id(e,t,i){if(e){const{left:s,top:r}=t.getBoundingClientRect();i[0]=e.clientX-s,i[1]=e.clientY-r}else e=window.event,i[0]=e.x,i[1]=e.y;return i}const Dd=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 Sd{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=d.vec2(),l=d.vec2(),A=d.vec2(),h=d.vec2(),c=[],u=this._scene.canvas.canvas;let p=0,f=!1;this._onTick=e.on("tick",(()=>{f=!1})),u.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!i.active||!i.pointerEnabled)return;t.preventDefault();const r=t.touches,l=t.changedTouches;for(s.touchStartTime=Date.now(),1===r.length&&1===l.length&&(Dd(r[0],a),i.followPointer&&(o.pickCursorPos=a,o.schedulePickSurface=!0,o.update(),i.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(n.setPivotPos(o.pickResult.worldPos),!i.firstPerson&&n.startPivot()&&n.showPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),!i.firstPerson&&n.startPivot()&&n.showPivot()))));c.length{n.getPivoting()&&n.endPivot()}),u.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const n=e.canvas.boundary,a=n[2],u=n[3],g=t.touches;if(t.touches.length===p){if(1===p){Dd(g[0],l),d.subVec2(l,c[0],h);const t=h[0],o=h[1];if(null!==s.longTouchTimeout&&(Math.abs(t)>i.longTapRadius||Math.abs(o)>i.longTapRadius)&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),i.planView){const s=e.camera;if("perspective"===s.projection){const n=Math.abs(e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*n/u*i.touchPanRate,r.panDeltaY+=o*n/u*i.touchPanRate}else r.panDeltaX+=.5*s.ortho.scale*(t/u)*i.touchPanRate,r.panDeltaY+=.5*s.ortho.scale*(o/u)*i.touchPanRate}else r.rotateDeltaY-=t/a*(1*i.dragRotationRate),r.rotateDeltaX+=o/u*(1.5*i.dragRotationRate)}else if(2===p){const t=g[0],n=g[1];Dd(t,l),Dd(n,A);const a=d.geometricMeanVec2(c[0],c[1]),h=d.geometricMeanVec2(l,A),p=d.vec2();d.subVec2(a,h,p);const f=p[0],m=p[1],_=e.camera,v=d.distVec2([t.pageX,t.pageY],[n.pageX,n.pageY]),b=(d.distVec2(c[0],c[1])-v)*i.touchDollyRate;if(r.dollyDelta=b,Math.abs(b)<1)if("perspective"===_.projection){const t=o.pickResult?o.pickResult.worldPos:e.center,s=Math.abs(d.lenVec3(d.subVec3(t,e.camera.eye,[])))*Math.tan(_.perspective.fov/2*Math.PI/180);r.panDeltaX-=f*s/u*i.touchPanRate,r.panDeltaY-=m*s/u*i.touchPanRate}else r.panDeltaX-=.5*_.ortho.scale*(f/u)*i.touchPanRate,r.panDeltaY-=.5*_.ortho.scale*(m/u)*i.touchPanRate;s.pointerCanvasPos=h}for(let e=0;e{let s;i&&i.worldPos&&(s=i.worldPos);const r=i?i.entity.aabb:e.aabb;if(s){const i=e.camera;d.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};u.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!i.active||!i.pointerEnabled)return;null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null);const r=e.touches,o=e.changedTouches;if(a=Date.now(),1===r.length&&1===o.length){h=a,Td(r[0],A);const o=A[0],n=A[1],l=r[0].pageX,c=r[0].pageY;s.longTouchTimeout=setTimeout((()=>{t.cameraControl.fire("rightClick",{pagePos:[Math.round(l),Math.round(c)],canvasPos:[Math.round(o),Math.round(n)],event:e},!0),s.longTouchTimeout=null}),i.longTapTimeout)}else h=-1;for(;l.length{if(!i.active||!i.pointerEnabled)return;const t=Date.now(),r=e.touches,a=e.changedTouches,u=n.hasSubs("pickedSurface");null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),0===r.length&&1===a.length&&h>-1&&t-h<150&&(c>-1&&h-c<325?(Td(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=u,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("doublePicked",o.pickResult),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult),i.doublePickFlyTo&&p(o.pickResult)):(n.fire("doublePickedNothing"),i.doublePickFlyTo&&p()),c=-1):d.distVec2(l[0],A)<4&&(Td(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=u,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("picked",o.pickResult),o.pickedSurface&&n.fire("pickedSurface",o.pickResult)):n.fire("pickedNothing"),c=t),h=-1),l.length=r.length;for(let e=0,t=r.length;e{e.preventDefault()},this._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,zoomOnMouseWheel:!0,snapToVertex:true,snapToEdge:true,snapRadius:30,keyboardEnabledOnlyIfMouseover:!0,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},this._states={pointerCanvasPos:d.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:d.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const i=this.scene;this._controllers={cameraControl:this,pickController:new fd(this,this._configs),pivotController:new pd(i,this._configs),panController:new ad(i),cameraFlight:new Mu(this,{duration:.5})},this._handlers=[new Fd(this.scene,this._controllers,this._configs,this._states,this._updates),new Sd(this.scene,this._controllers,this._configs,this._states,this._updates),new md(this.scene,this._controllers,this._configs,this._states,this._updates),new wd(this.scene,this._controllers,this._configs,this._states,this._updates),new Pd(this.scene,this._controllers,this._configs,this._states,this._updates),new Rd(this.scene,this._controllers,this._configs,this._states,this._updates),new Cd(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new Ed(this.scene,this._controllers,this._configs,this._states,this._updates),this.navMode=t.navMode,t.planView&&(this.planView=t.planView),this.constrainVertical=t.constrainVertical,t.keyboardLayout?this.keyboardLayout=t.keyboardLayout:this.keyMap=t.keyMap,this.doublePickFlyTo=t.doublePickFlyTo,this.panRightClick=t.panRightClick,this.active=t.active,this.followPointer=t.followPointer,this.rotationInertia=t.rotationInertia,this.keyboardPanRate=t.keyboardPanRate,this.touchPanRate=t.touchPanRate,this.keyboardRotationRate=t.keyboardRotationRate,this.dragRotationRate=t.dragRotationRate,this.touchDollyRate=t.touchDollyRate,this.dollyInertia=t.dollyInertia,this.dollyProximityThreshold=t.dollyProximityThreshold,this.dollyMinSpeed=t.dollyMinSpeed,this.panInertia=t.panInertia,this.pointerEnabled=!0,this.keyboardDollyRate=t.keyboardDollyRate,this.mouseWheelDollyRate=t.mouseWheelDollyRate}set keyMap(e){if(e=e||"qwerty",y.isString(e)){const t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=i}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_isKeyDownForAction(e,t){const i=this._keyMap[e];if(!i)return!1;t||(t=this.scene.input.keyDown);for(let e=0,s=i.length;e0&&console.error(`[MetaModel._decompressProperties] Properties not found: ${i}`)}finalize(){if(this.finalized)throw"MetaScene already finalized - can't re-finalize";const e=this.metaScene;for(let t in e.metaObjects){const i=e.metaObjects[t];if(i.children&&(i.children=[]),i.propertySets&&(i.propertySets=[]),i.propertySetIds)for(let t=0,s=i.propertySetIds.length;t0?Vd(t):null,n=i&&i.length>0?Vd(i):null,a=e=>{if(!e)return;var t=!0;(n&&n[e.type]||o&&!o[e.type])&&(t=!1),t&&s.push(e.id);const i=e.children;if(i)for(var r=0,l=i.length;r>t;i.sort(wc);const s=new Int32Array(e.length);for(let t=0,r=i.length;te[t+1]){let i=e[t];e[t]=e[t+1],e[t+1]=i}Pc=new Int32Array(e),t.sort(Cc);const i=new Int32Array(e.length);for(let s=0,r=t.length;st){let i=e;e=t,t=i}function i(i,s){return i!==e?e-i:s!==t?t-s:0}let s=0,r=(o.length>>1)-1;for(;s<=r;){const e=r+s>>1,t=i(o[2*e],o[2*e+1]);if(t>0)s=e+1;else{if(!(t<0))return e;r=e-1}}return-s-1}const a=new Int32Array(o.length/2);a.fill(0);const l=s.length/3;if(l>8*(1<u.maxNumPositions&&(u=c()),u.bucketNumber>8)return[e];let p;-1===A[l]&&(A[l]=u.numPositions++,u.positionsCompressed.push(s[3*l]),u.positionsCompressed.push(s[3*l+1]),u.positionsCompressed.push(s[3*l+2])),-1===A[h]&&(A[h]=u.numPositions++,u.positionsCompressed.push(s[3*h]),u.positionsCompressed.push(s[3*h+1]),u.positionsCompressed.push(s[3*h+2])),-1===A[d]&&(A[d]=u.numPositions++,u.positionsCompressed.push(s[3*d]),u.positionsCompressed.push(s[3*d+1]),u.positionsCompressed.push(s[3*d+2])),u.indices.push(A[l]),u.indices.push(A[h]),u.indices.push(A[d]),(p=n(l,h))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(l,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(h,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]]))}const d=t/8*2,p=t/8,f=2*s.length+(r.length+o.length)*d;let g=0,m=-s.length/3;return h.forEach((e=>{g+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*p,m+=e.positionsCompressed.length/3})),g>f?[e]:(i&&function(e,t){const i={},s={};let r=0;e.forEach((e=>{const t=e.indices,o=e.edgeIndices,n=e.positionsCompressed;for(let e=0,s=t.length;e0){const e=t._meshes;for(let t=0,i=e.length;t0){const e=this._meshes;for(let t=0,i=e.length;t{this._viewMatrixDirty=!0})),this._meshesWithDirtyMatrices=[],this._numMeshesWithDirtyMatrices=0,this._onTick=this.scene.on("tick",(()=>{for(;this._numMeshesWithDirtyMatrices>0;)this._meshesWithDirtyMatrices[--this._numMeshesWithDirtyMatrices]._updateMatrix()})),this._createDefaultTextureSet(),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.backfaces=t.backfaces}_meshMatrixDirty(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}_createDefaultTextureSet(){const e=new ac({id:"defaultColorTexture",texture:new Zr({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new ac({id:"defaultMetalRoughTexture",texture:new Zr({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new ac({id:"defaultNormalsTexture",texture:new Zr({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),s=new ac({id:"defaultEmissiveTexture",texture:new Zr({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new ac({id:"defaultOcclusionTexture",texture:new Zr({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=s,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new nc({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:s,occlusionTexture:r})}get isPerformanceModel(){return!0}get transforms(){return this._transforms}get textures(){return this._textures}get textureSets(){return this._textureSets}get meshes(){return this._meshes}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),d.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||Hc),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),d.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),d.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get matrix(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),d.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),d.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}get rotationMatrixConjugate(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0,this._aabbDirty=!0}_transformDirty(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}_sceneModelDirty(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(let e=0,t=this._entityList.length;e0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,i=this._entityList.length;t0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._entityList.length;t0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._entityList.length;t0}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._entityList.length;t0}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._entityList.length;t0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._entityList.length;t0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,i=new Uint8Array(t.length);for(let e=0,s=t.length;e{l.setImage(A,{minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a}),this.glRedraw()},A.src=e.src;break;default:this._textureTranscoder?y.loadArraybuffer(e.src,(e=>{e.byteLength?this._textureTranscoder.transcode([e],l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'src': file data is zero length")}),(function(e){this.error(`[createTexture] Can't create texture from 'src': ${e}`)})):this.error(`[createTexture] Can't create texture from 'src' - SceneModel needs to be configured with a TextureTranscoder for this file type ('${t}')`)}}else e.buffers&&(this._textureTranscoder?this._textureTranscoder.transcode(e.buffers,l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'buffers' - SceneModel needs to be configured with a TextureTranscoder for this option"));this._textures[t]=new ac({id:t,texture:l})}createTextureSet(e){const t=e.id;if(null==t)return void this.error("[createTextureSet] Config missing: id");if(this._textureSets[t])return void this.error(`[createTextureSet] Texture set already created: ${t}`);let i,s,r,o,n;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(i=this._textures[e.colorTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.colorTextureId} - ensure that you create it first with createTexture()`)}else i=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(s=this._textures[e.metallicRoughnessTextureId],!s)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else s=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(r=this._textures[e.normalsTextureId],!r)return void this.error(`[createTextureSet] Texture not found: ${e.normalsTextureId} - ensure that you create it first with createTexture()`)}else r=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(o=this._textures[e.emissiveTextureId],!o)return void this.error(`[createTextureSet] Texture not found: ${e.emissiveTextureId} - ensure that you create it first with createTexture()`)}else o=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(n=this._textures[e.occlusionTextureId],!n)return void this.error(`[createTextureSet] Texture not found: ${e.occlusionTextureId} - ensure that you create it first with createTexture()`)}else n=this._textures.defaultOcclusionTexture;const a=new nc({id:t,model:this,colorTexture:i,alphaCutoff:e.alphaCutoff,metallicRoughnessTexture:s,normalsTexture:r,emissiveTexture:o,occlusionTexture:n});return this._textureSets[t]=a,a}createTransform(e){if(void 0===e.id||null===e.id)return void this.error("[createTransform] SceneModel.createTransform() config missing: id");if(this._transforms[e.id])return void this.error(`[createTransform] SceneModel already has a transform with this ID: ${e.id}`);let t;if(e.parentTransformId&&(t=this._transforms[e.parentTransformId],!t))return void this.error("[createTransform] SceneModel.createTransform() config missing: id");const i=new Lc({id:e.id,model:this,parent:t,matrix:e.matrix,position:e.position,scale:e.scale,rotation:e.rotation,quaternion:e.quaternion});return this._transforms[i.id]=i,i}createMesh(e){if(void 0===e.id||null===e.id)return this.error("[createMesh] SceneModel.createMesh() config missing: id"),!1;if(this._meshes[e.id])return this.error(`[createMesh] SceneModel already has a mesh with this ID: ${e.id}`),!1;if(!(void 0!==e.geometryId)){if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"!==e.primitive&&"lines"!==e.primitive&&"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)return this.error(`Unsupported value for 'primitive': '${primitive}' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.`),!1;if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),!1;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),!1;if(!(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){const t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return e.indices=this._createDefaultIndices(numIndices),this.error(`Param expected: indices (required for '${e.primitive}' primitive type)`),!1;if((e.matrix||e.position||e.rotation||e.scale)&&(e.positionsCompressed||e.positionsDecodeBoundary))return this.error("Unexpected params: 'matrix', 'rotation', 'scale', 'position' not allowed with 'positionsCompressed'"),!1;const t=!(!this._dtxEnabled||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||e.textureSetId);if(e.origin=e.origin?d.addVec3(this._origin,e.origin,d.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){const t=e.scale||Nc,i=e.position||Qc;e.rotation?(d.eulerToQuaternion(e.rotation,"XYZ",kc),e.meshMatrix=d.composeMat4(i,kc,t,d.mat4())):e.meshMatrix=d.composeMat4(i,e.quaternion||Vc,t,d.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Ln(e.positionsDecodeBoundary,d.mat4())),t){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):jc,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=d.vec3(),i=[];Z(e.positions,i,t)&&(e.positions=i,e.origin=d.addVec3(e.origin,t,t))}if(e.positions){const t=d.collapseAABB3();e.positionsDecodeMatrix=d.mat4(),d.expandAABB3Points3(t,e.positions),e.positionsCompressed=Rn(e.positions,t,e.positionsDecodeMatrix),e.aabb=t}else if(e.positionsCompressed){const t=d.collapseAABB3();d.expandAABB3Points3(t,e.positionsCompressed),Zt.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.buckets){const t=d.collapseAABB3();for(let i=0,s=e.buckets.length;i>24&255,r=i>>16&255,o=i>>8&255,n=255&i;switch(e.pickColor=new Uint8Array([n,o,r,s]),e.solid="solid"===e.primitive,t.origin=d.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),t.numPrimitives=e.numPrimitives,this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}_getNumPrimitives(e){let t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i>>0).toString(16)}_getVBOInstancingLayer(e){const t=this,i=e.origin,s=e.textureSetId||"-",r=e.geometryId,o=`${Math.round(i[0])}.${Math.round(i[1])}.${Math.round(i[2])}.${s}.${r}`;let n=this._vboInstancingLayers[o];if(n)return n;let a=e.textureSet;const l=e.geometry;for(;!n;)switch(l.primitive){case"triangles":case"surface":n=new Na({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":n=new Na({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":n=new wl({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":n=new gA({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[o]=n,this.layerList.push(n),this._layersToFinalize.push(n),n}createEntity(e){if(void 0===e.id?e.id=d.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=d.createUUID()),void 0===e.meshIds)return void this.error("Config missing: meshIds");let t=0;return this._visible&&!1!==e.visible&&(t|=ee),this._pickable&&!1!==e.pickable&&(t|=ie),this._culled&&!1!==e.culled&&(t|=te),this._clippable&&!1!==e.clippable&&(t|=se),this._collidable&&!1!==e.collidable&&(t|=re),this._edges&&!1!==e.edges&&(t|=le),this._xrayed&&!1!==e.xrayed&&(t|=oe),this._highlighted&&!1!==e.highlighted&&(t|=ne),this._selected&&!1!==e.selected&&(t|=ae),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];for(let i=0,s=e.meshIds.length;ie.sortIdt.sortId?1:0));for(let e=0,t=this.layerList.length;e0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}_updateRenderFlagsVisibleLayers(){const e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(let t=0,i=this.layerList.length;t0){const t=`${this.id}-${d.createUUID()}`;this.warn(`Creating dummy SceneModelEntity "${t}" for unused SceneMeshes: [${e.join(",")}]`),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}_getActiveSectionPlanesForLayer(e){const t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,s=i.length,r=e.layerIndex*s;if(s>0)for(let e=0;e0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0){this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions0&&(e.edgesTransparent=!0))}if(this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){const t=this.scene.highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}drawColorOpaque(e,t){const i=this.renderFlags;for(let t=0,s=i.visibleLayers.length;t65536?16:8)}else n=[{positionsCompressed:s,indices:r,edgeIndices:o}];return n}class Wc extends R{constructor(e,t={}){if(super(e,t),this._positions=t.positions||[],t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;ep.has(e.id)||g.has(e.id)||f.has(e.id))).reduce(((e,i)=>{let s,r=function(e){let t="";return t+=Math.round(255*e[0]).toString(16).padStart(2,"0"),t+=Math.round(255*e[1]).toString(16).padStart(2,"0"),t+=Math.round(255*e[2]).toString(16).padStart(2,"0"),t}(i.colorize);i.xrayed?(s=0===t.xrayMaterial.fillAlpha&&0!==t.xrayMaterial.edgeAlpha?.1:t.xrayMaterial.fillAlpha,s=Math.round(255*s).toString(16).padStart(2,"0"),r=s+r):p.has(i.id)&&(s=Math.round(255*i.opacity).toString(16).padStart(2,"0"),r=s+r),e[r]||(e[r]=[]);const o=i.id,n=i.originalSystemId,a={ifc_guid:n,originating_system:this.originatingSystem};return n!==o&&(a.authoring_tool_id=o),e[r].push(a),e}),{}),_=Object.entries(m).map((([e,t])=>({color:e,components:t})));o.components.coloring=_;const v=t.objectIds,b=t.visibleObjects,y=t.visibleObjectIds,x=v.filter((e=>!b[e])),B=t.selectedObjectIds;return e.defaultInvisible||y.length0&&e.clipping_planes.forEach((function(e){let t=$c(e.location,Kc),i=$c(e.direction,Kc);A&&d.negateVec3(i),d.subVec3(t,l),r.yUp&&(t=tu(t),i=tu(i)),new Dr(s,{pos:t,dir:i})})),s.clearLines(),e.lines&&e.lines.length>0){const t=[],i=[];let r=0;e.lines.forEach((e=>{e.start_point&&e.end_point&&(t.push(e.start_point.x),t.push(e.start_point.y),t.push(e.start_point.z),t.push(e.end_point.x),t.push(e.end_point.y),t.push(e.end_point.z),i.push(r++),i.push(r++))})),new Wc(s,{positions:t,indices:i,clippable:!1,collidable:!0})}if(s.clearBitmaps(),e.bitmaps&&e.bitmaps.length>0&&e.bitmaps.forEach((function(e){const t=e.bitmap_type||"jpg",i=e.bitmap_data;let o=$c(e.location,Xc),n=$c(e.normal,Jc),a=$c(e.up,Yc),l=e.height||1;t&&i&&o&&n&&a&&(r.yUp&&(o=tu(o),n=tu(n),a=tu(a)),new bo(s,{src:i,type:t,pos:o,normal:n,up:a,clippable:!1,collidable:!0,height:l}))})),a&&(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=>this._withBCFComponent(t,e,(e=>e.visible=!1))))):(s.setObjectsVisible(s.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!0)))));const r=e.components.visibility.view_setup_hints;r&&(!1===r.spaces_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcSpace"),!1),void 0!==r.spaces_translucent&&s.setObjectsXRayed(i.metaScene.getObjectIDsByType("IfcSpace"),!0),r.space_boundaries_visible,!1===r.openings_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcOpening"),!0),r.space_boundaries_translucent,void 0!==r.openings_translucent&&s.setObjectsXRayed(i.metaScene.getObjectIDsByType("IfcOpening"),!0))}e.components.selection&&(s.setObjectsSelected(s.selectedObjectIds,!1),e.components.selection.forEach((e=>this._withBCFComponent(t,e,(e=>e.selected=!0))))),e.components.translucency&&(s.setObjectsXRayed(s.xrayedObjectIds,!1),e.components.translucency.forEach((e=>this._withBCFComponent(t,e,(e=>e.xrayed=!0))))),e.components.coloring&&e.components.coloring.forEach((e=>{let i=e.color,s=0,r=!1;8===i.length&&(s=parseInt(i.substring(0,2),16)/256,s<=1&&s>=.95&&(s=1),i=i.substring(2),r=!0);const o=[parseInt(i.substring(0,2),16)/256,parseInt(i.substring(2,4),16)/256,parseInt(i.substring(4,6),16)/256];e.components.map((e=>this._withBCFComponent(t,e,(e=>{e.colorize=o,r&&(e.opacity=s)}))))}))}if(e.perspective_camera||e.orthogonal_camera){let a,A,h,c;if(e.perspective_camera?(a=$c(e.perspective_camera.camera_view_point,Kc),A=$c(e.perspective_camera.camera_direction,Kc),h=$c(e.perspective_camera.camera_up_vector,Kc),r.perspective.fov=e.perspective_camera.field_of_view,c="perspective"):(a=$c(e.orthogonal_camera.camera_view_point,Kc),A=$c(e.orthogonal_camera.camera_direction,Kc),h=$c(e.orthogonal_camera.camera_up_vector,Kc),r.ortho.scale=e.orthogonal_camera.view_to_world_scale,c="ortho"),d.subVec3(a,l),r.yUp&&(a=tu(a),A=tu(A),h=tu(h)),o){const e=s.pick({pickSurface:!0,origin:a,direction:A});A=e?e.worldPos:d.addVec3(a,A,Kc)}else A=d.addVec3(a,A,Kc);n?(r.eye=a,r.look=A,r.up=h,r.projection=c):i.cameraFlight.flyTo({eye:a,look:A,up:h,duration:t.duration,projection:c})}}_withBCFComponent(e,t,i){const s=this.viewer,r=s.scene;if(t.authoring_tool_id&&t.originating_system===this.originatingSystem){const o=t.authoring_tool_id,n=r.objects[o];if(n)return void i(n);if(e.updateCompositeObjects){if(s.metaScene.metaObjects[o])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(o),i)}}if(t.ifc_guid){const o=t.ifc_guid,n=r.objects[o];if(n)return void i(n);if(e.updateCompositeObjects){if(s.metaScene.metaObjects[o])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(o),i)}Object.keys(r.models).forEach((t=>{const n=d.globalizeObjectId(t,o),a=r.objects[n];if(a)i(a);else if(e.updateCompositeObjects){s.metaScene.metaObjects[n]&&r.withObjects(s.metaScene.getObjectIDsInSubtree(n),i)}}))}}destroy(){super.destroy()}}function qc(e){return{x:e[0],y:e[1],z:e[2]}}function $c(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function eu(e){return new Float64Array([e[0],-e[2],e[1]])}function tu(e){return new Float64Array([e[0],e[2],-e[1]])}const iu=d.vec3(),su=d.vec3(),ru=(e,t,i,s)=>{var r=e-i,o=t-s;return Math.sqrt(r*r+o*o)};class ou extends R{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var i=this.plugin.viewer.scene;this._originWorld=d.vec3(),this._targetWorld=d.vec3(),this._wp=new Float64Array(24),this._vp=new Float64Array(24),this._pp=new Float64Array(24),this._cp=new Float64Array(8),this._xAxisLabelCulled=!1,this._yAxisLabelCulled=!1,this._zAxisLabelCulled=!1,this._color=t.color||this.plugin.defaultColor;const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))},l=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new me(i,t.origin,this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._targetDot=new me(i,t.target,this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthWire=new ye(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisWire=new ye(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisWire=new ye(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisWire=new ye(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthLabel=new xe(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisLabel=new xe(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisLabel=new xe(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisLabel=new xe(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._measurementOrientation="Horizontal",this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._sectionPlanesDirty=!0,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._useRotationAdjustment=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._xLabelEnabled=!1,this._yLabelEnabled=!1,this._zLabelEnabled=!1,this._lengthLabelEnabled=!1,this._labelsVisible=!1,this._labelsOnWires=!1,this._clickable=!1,this._originDot.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetDot.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=i.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=i.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=i.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.xLabelEnabled=t.xLabelEnabled,this.yLabelEnabled=t.yLabelEnabled,this.zLabelEnabled=t.zLabelEnabled,this.lengthLabelEnabled=t.lengthLabelEnabled,this.labelsVisible=t.labelsVisible,this.labelsOnWires=t.labelsOnWires,this._useRotationAdjustment=t.useRotationAdjustment,this._axesBasis=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}set axesBasis(e){this._axesBasis=e.slice(),this._wpDirty=!0,this._needUpdate(0)}get axesBasis(){return this._axesBasis}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty){const e=d.subVec3(this._targetWorld,this._originWorld,su);this._factors=d.transformVec3(this._axesBasis,e),this._measurementOrientation=function(e,t,i){return Math.abs(t[1]-e[1])>i?"Vertical":"Horizontal"}(this._originWorld,this._targetWorld,0),"Vertical"===this._measurementOrientation&&this._useRotationAdjustment?(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._originWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._originWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1):(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._originWorld[0]+this._axesBasis[0]*this._factors[0],this._wp[5]=this._originWorld[1]+this._axesBasis[4]*this._factors[0],this._wp[6]=this._originWorld[2]+this._axesBasis[8]*this._factors[0],this._wp[7]=1,this._wp[8]=this._originWorld[0]+this._axesBasis[0]*this._factors[0]+this._axesBasis[1]*this._factors[1],this._wp[9]=this._originWorld[1]+this._axesBasis[4]*this._factors[0]+this._axesBasis[5]*this._factors[1],this._wp[10]=this._originWorld[2]+this._axesBasis[8]*this._factors[0]+this._axesBasis[9]*this._factors[1],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1),this._wpDirty=!1,this._vpDirty=!0}if(this._vpDirty&&(d.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._originWorld)||this._isSliced(this._targetWorld))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}const t=this._originDot.viewPos[2],i=this._targetDot.viewPos[2];if(t>-.3||i>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){d.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var s=this._pp,r=this._cp,o=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var n=o.top-t.top,a=o.left-t.left,l=e.canvas.boundary,A=l[2],h=l[3],c=0;const i=this.plugin.viewer.scene.metrics,f=i.scale,g=i.units,m=i.unitsInfo[g].abbrev;for(var u=0,p=s.length;ue.offsetTop+(e.offsetParent&&e.offsetParent!==s.parentNode&&h(e.offsetParent)),c=e=>e.offsetLeft+(e.offsetParent&&e.offsetParent!==s.parentNode&&c(e.offsetParent)),u=d.vec2(),p=e=>{const t=e.snappedCanvasPos||e.canvasPos;r=!0,o.set(e.worldPos),n.set(e.canvasPos),0===this._mouseState?(this._canvasToPagePos?(this._canvasToPagePos(s,t,u),this._markerDiv.style.left=u[0]-5+"px",this._markerDiv.style.top=u[1]-5+"px"):(this._markerDiv.style.left=c(s)+t[0]-5+"px",this._markerDiv.style.top=h(s)+t[1]-5+"px"),this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,this.pointerLens.snapped=!0),this._markerDiv.style.background="greenyellow",this._markerDiv.style.border="2px solid green"):(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red"),A=e.entity):(this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px"),s.style.cursor="pointer",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=this._currentDistanceMeasurementInitState.wireVisible,this._currentDistanceMeasurement.axisVisible=this._currentDistanceMeasurementInitState.axisVisible&&this.distanceMeasurementsPlugin.defaultAxisVisible,this._currentDistanceMeasurement.xAxisVisible=this._currentDistanceMeasurementInitState.xAxisVisible&&this.distanceMeasurementsPlugin.defaultXAxisVisible,this._currentDistanceMeasurement.yAxisVisible=this._currentDistanceMeasurementInitState.yAxisVisible&&this.distanceMeasurementsPlugin.defaultYAxisVisible,this._currentDistanceMeasurement.zAxisVisible=this._currentDistanceMeasurementInitState.zAxisVisible&&this.distanceMeasurementsPlugin.defaultZAxisVisible,this._currentDistanceMeasurement.targetVisible=this._currentDistanceMeasurementInitState.targetVisible,this._currentDistanceMeasurement.target.worldPos=o.slice(),this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px")};this._onHoverSnapOrSurface=i.on("hoverSnapOrSurface",(e=>{this._snapping&&p(e)})),this._onHoverSurface=i.on("hoverSurface",(e=>{this._snapping||p(e)})),s.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(a=e.clientX,l=e.clientY)}),s.addEventListener("mouseup",this._onMouseUp=t=>{1===t.which&&(t.clientX>a+20||t.clientXl+20||t.clientY{this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos),r=!1,this._markerDiv.style.left="-100px",this._markerDiv.style.top="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),s.style.cursor="default"};this._onHoverSnapOrSurfaceOff=i.on("hoverSnapOrSurfaceOff",(e=>{this._snapping&&f(e)})),this._onHoverOff=i.on("hoverOff",(e=>{this._snapping||f(e)})),this._active=!0}deactivate(){if(!this._active)return;this.fire("activated",!1),this.pointerLens&&(this.pointerLens.visible=!1),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onHoverSnapOrSurface),t.off(this._onHoverSurface),t.off(this._onHoverSnapOrSurfaceOff),t.off(this._onHoverOff),this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._mouseState=0)}get currentMeasurement(){return this._currentDistanceMeasurement}destroy(){this.deactivate(),super.destroy()}}class lu extends z{constructor(e,t={}){super("DistanceMeasurements",e),this._pointerLens=t.pointerLens,this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.labelMinAxisLength=t.labelMinAxisLength,this.defaultVisible=!1!==t.defaultVisible,this.defaultOriginVisible=!1!==t.defaultOriginVisible,this.defaultTargetVisible=!1!==t.defaultTargetVisible,this.defaultWireVisible=!1!==t.defaultWireVisible,this.defaultXLabelEnabled=!1!==t.defaultXLabelEnabled,this.defaultYLabelEnabled=!1!==t.defaultYLabelEnabled,this.defaultZLabelEnabled=!1!==t.defaultZLabelEnabled,this.defaultLengthLabelEnabled=!1!==t.defaultLengthLabelEnabled,this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.defaultAxisVisible=!1!==t.defaultAxisVisible,this.defaultXAxisVisible=!1!==t.defaultXAxisVisible,this.defaultYAxisVisible=!1!==t.defaultYAxisVisible,this.defaultZAxisVisible=!1!==t.defaultZAxisVisible,this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.zIndex=t.zIndex||1e4,this.defaultLabelsOnWires=!1!==t.defaultLabelsOnWires,this.useRotationAdjustment=void 0!==t.useRotationAdjustment&&!1!==t.useRotationAdjustment,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,distanceMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get pointerLens(){return this._pointerLens}get control(){return this._defaultControl||(this._defaultControl=new au(this,{})),this._defaultControl}get measurements(){return this._measurements}set labelMinAxisLength(e){e<1&&(this.error("labelMinAxisLength must be >= 1; defaulting to 25"),e=25),this._labelMinAxisLength=e||25}get labelMinAxisLength(){return this._labelMinAxisLength}set useRotationAdjustment(e){e=void 0!==e&&Boolean(e),this._useRotationAdjustment=e}get useRotationAdjustment(){return this._useRotationAdjustment}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,i=e.target,s=new ou(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},target:{entity:i.entity,worldPos:i.worldPos},visible:e.visible,wireVisible:e.wireVisible,axisVisible:!1!==e.axisVisible&&!1!==this.defaultAxisVisible,xAxisVisible:!1!==e.xAxisVisible&&!1!==this.defaultXAxisVisible,yAxisVisible:!1!==e.yAxisVisible&&!1!==this.defaultYAxisVisible,zAxisVisible:!1!==e.zAxisVisible&&!1!==this.defaultZAxisVisible,xLabelEnabled:!1!==e.xLabelEnabled&&!1!==this.defaultXLabelEnabled,yLabelEnabled:!1!==e.yLabelEnabled&&!1!==this.defaultYLabelEnabled,zLabelEnabled:!1!==e.zLabelEnabled&&!1!==this.defaultZLabelEnabled,lengthLabelEnabled:!1!==e.lengthLabelEnabled&&!1!==this.defaultLengthLabelEnabled,labelsVisible:!1!==e.labelsVisible&&!1!==this.defaultLabelsVisible,useRotationAdjustment:this.useRotationAdjustment,originVisible:e.originVisible,targetVisible:e.targetVisible,color:e.color,labelsOnWires:!1!==e.labelsOnWires&&!1!==this.defaultLabelsOnWires,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[s.id]=s,s.clickable=!0,s.on("destroyed",(()=>{delete this._measurements[s.id]})),this.fire("measurementCreated",s),s}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("DistanceMeasurement not found: "+e)}setLabelsShown(e){for(const[t,i]of Object.entries(this.measurements))i.labelShown=e}setAxisVisible(e){for(const[t,i]of Object.entries(this.measurements))i.axisVisible=e;this.defaultAxisVisible=e}getAxisVisible(){return this.defaultAxisVisible}clear(){const e=Object.keys(this._measurements);for(var t=0,i=e.length;t{this.plugin.viewer.cameraControl.active=!1},c=()=>{this.plugin.viewer.cameraControl.active=!0},u=()=>{o&&(clearTimeout(o),o=null),this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),c(),this._touchState=0};i.addEventListener("touchstart",this._onCanvasTouchStart=l=>{const c=l.touches.length;if(1!==c)return void(o&&(clearTimeout(o),o=null));const p=l.touches[0],f=i.getBoundingClientRect(),g=p.clientX-f.left,m=p.clientY-f.top;switch(n.set([g,m]),a.set([g,m]),this._touchState){case 0:if(1!==c&&null!==o)return void u();const i=t.pick({canvasPos:a,snapping:this._snapping,snapToEdge:this._snapping});if(i&&i.snapped)s.set(i.worldPos),this.pointerCircle.start(i.snappedCanvasPos);else{const e=t.pick({canvasPos:a,pickSurface:!0});if(!e||!e.worldPos)return;s.set(e.worldPos),this.pointerCircle.start(e.canvasPos)}o=setTimeout((()=>{1!==c||a[0]>n[0]+r||a[0]n[1]+r||a[1]{if(o=null,1!==c||a[0]>n[0]+r||a[0]n[1]+r||a[1]{this.pointerCircle.stop();const n=r.touches.length;if(1!==n||1!==r.changedTouches.length)return void(o&&(clearTimeout(o),o=null));const l=r.touches[0],h=i.getBoundingClientRect(),c=l.clientX-h.left,u=l.clientY-h.top;if(l.identifier!==A)return;let p,f;switch(a.set([c,u]),this._touchState){case 2:this.pointerLens&&(this.pointerLens.canvasPos=a),p=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),p&&p.snapped?(this.pointerLens&&(this.pointerLens.snappedCanvasPos=p.snappedCanvasPos,this.pointerLens.snapped=!0),s.set(p.worldPos),this._currentDistanceMeasurement?this._currentDistanceMeasurement.origin.worldPos=p.worldPos:(this._currentDistanceMeasurement=e.createMeasurement({id:d.createUUID(),origin:{worldPos:p.worldPos,entity:p.entity},target:{worldPos:p.worldPos,entity:p.entity}}),this._currentDistanceMeasurement.labelsVisible=!1,this._currentDistanceMeasurement.xAxisVisible=!1,this._currentDistanceMeasurement.yAxisVisible=!1,this._currentDistanceMeasurement.zAxisVisible=!1,this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.originVisible=!0,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.clickable=!1),this.distanceMeasurementsPlugin.fire("measurementStart",this._currentDistanceMeasurement)):(f=t.pick({canvasPos:a,pickSurface:!0}),f&&f.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=f.canvasPos,this.pointerLens.snapped=!1),s.set(f.worldPos),this._currentDistanceMeasurement?this._currentDistanceMeasurement.origin.worldPos=f.worldPos:(this._currentDistanceMeasurement=e.createMeasurement({id:d.createUUID(),origin:{worldPos:f.worldPos,entity:f.entity},target:{worldPos:f.worldPos,entity:f.entity}}),this._currentDistanceMeasurement.labelsVisible=!1,this._currentDistanceMeasurement.xAxisVisible=!1,this._currentDistanceMeasurement.yAxisVisible=!1,this._currentDistanceMeasurement.zAxisVisible=!1,this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.originVisible=!0,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.clickable=!1),this.distanceMeasurementsPlugin.fire("measurementStart",this._currentDistanceMeasurement)):this.pointerLens&&(this.pointerLens.cursorPos=null,this.pointerLens.snapped=!1)),this._touchState=2;break;case 5:if(1!==n&&null!==o)return clearTimeout(o),o=null,this.pointerLens&&(this.pointerLens.visible=!1),void(this._touchState=7);this.pointerLens&&(this.pointerLens.canvasPos=a),p=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),p&&p.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=p.snappedCanvasPos,this.pointerLens.snapped=!0),this._currentDistanceMeasurement.target.worldPos=p.worldPos,this._currentDistanceMeasurement.target.entity=p.entity,this._currentDistanceMeasurement.targetVisible=!0,this._currentDistanceMeasurement.wireVisible=!0,this._currentDistanceMeasurement.labelsVisible=!0):(f=t.pick({canvasPos:a,pickSurface:!0}),f&&f.worldPos&&(this.pointerLens&&(this.pointerLens.cursorPos=f.canvasPos,this.pointerLens.snapped=!1),this._currentDistanceMeasurement.target.worldPos=f.worldPos,this._currentDistanceMeasurement.target.entity=f.entity,this._currentDistanceMeasurement.targetVisible=!0,this._currentDistanceMeasurement.wireVisible=!0,this._currentDistanceMeasurement.labelsVisible=!0)),this._touchState=5}}),{passive:!0}),i.addEventListener("touchend",this._onCanvasTouchEnd=s=>{this.pointerCircle.stop();const h=s.changedTouches.length;if(1!==h)return;const u=s.changedTouches[0],p=i.getBoundingClientRect(),f=u.clientX-p.left,g=u.clientY-p.top;if(u.identifier===A)switch(o&&(clearTimeout(o),o=null),l.set([f,g]),this._touchState){case 1:{if(1!==h||f>n[0]+r||fn[1]+r||gn[0]+r||fn[1]+r||g{const o=e=>{const t=r.scene.pick({canvasPos:s,snapToEdge:e,snapToVertex:e,pickSurface:!0});return t&&t.worldPos?t.worldPos:e&&o(!1)};return o(!!t.snapping)},onEnd:(e,t)=>{const i=!d.compareVec3(e,t.worldPos);return i&&this.fire("edited"),i}}),n=e.on("destroyed",o);this._deactivate=function(){e.off("destroyed",n),o()}}deactivate(){this._deactivate(),super.destroy()}}class cu extends hu{constructor(e,t){super(e,t,!0,!1)}}class uu extends hu{constructor(e,t){super(e,t,!1,!0)}}class du extends z{constructor(e,t={}){super("FastNav",e),this._hideColorTexture=!1!==t.hideColorTexture,this._hidePBR=!1!==t.hidePBR,this._hideSAO=!1!==t.hideSAO,this._hideEdges=!1!==t.hideEdges,this._hideTransparentObjects=!!t.hideTransparentObjects,this._scaleCanvasResolution=!!t.scaleCanvasResolution,this._defaultScaleCanvasResolutionFactor=t.defaultScaleCanvasResolutionFactor||1,this._scaleCanvasResolutionFactor=t.scaleCanvasResolutionFactor||.6,this._delayBeforeRestore=!1!==t.delayBeforeRestore,this._delayBeforeRestoreSeconds=t.delayBeforeRestoreSeconds||.5;let i=1e3*this._delayBeforeRestoreSeconds,s=!1;const r=()=>{i=1e3*this._delayBeforeRestoreSeconds,s||(e.scene._renderer.setColorTextureEnabled(!this._hideColorTexture),e.scene._renderer.setPBREnabled(!this._hidePBR),e.scene._renderer.setSAOEnabled(!this._hideSAO),e.scene._renderer.setTransparentEnabled(!this._hideTransparentObjects),e.scene._renderer.setEdgesEnabled(!this._hideEdges),this._scaleCanvasResolution?e.scene.canvas.resolutionScale=this._scaleCanvasResolutionFactor:e.scene.canvas.resolutionScale=this._defaultScaleCanvasResolutionFactor,s=!0)},o=()=>{e.scene.canvas.resolutionScale=this._defaultScaleCanvasResolutionFactor,e.scene._renderer.setEdgesEnabled(!0),e.scene._renderer.setColorTextureEnabled(!0),e.scene._renderer.setPBREnabled(!0),e.scene._renderer.setSAOEnabled(!0),e.scene._renderer.setTransparentEnabled(!0),s=!1};this._onCanvasBoundary=e.scene.canvas.on("boundary",r),this._onCameraMatrix=e.scene.camera.on("matrix",r),this._onSceneTick=e.scene.on("tick",(e=>{s&&(i-=e.deltaTime,(!this._delayBeforeRestore||i<=0)&&o())}));let n=!1;this._onSceneMouseDown=e.scene.input.on("mousedown",(()=>{n=!0})),this._onSceneMouseUp=e.scene.input.on("mouseup",(()=>{n=!1})),this._onSceneMouseMove=e.scene.input.on("mousemove",(()=>{n&&r()}))}get hideColorTexture(){return this._hideColorTexture}set hideColorTexture(e){this._hideColorTexture=e}get hidePBR(){return this._hidePBR}set hidePBR(e){this._hidePBR=e}get hideSAO(){return this._hideSAO}set hideSAO(e){this._hideSAO=e}get hideEdges(){return this._hideEdges}set hideEdges(e){this._hideEdges=e}get hideTransparentObjects(){return this._hideTransparentObjects}set hideTransparentObjects(e){this._hideTransparentObjects=!1!==e}get scaleCanvasResolution(){return this._scaleCanvasResolution}set scaleCanvasResolution(e){this._scaleCanvasResolution=e}get defaultScaleCanvasResolutionFactor(){return this._defaultScaleCanvasResolutionFactor}set defaultScaleCanvasResolutionFactor(e){this._defaultScaleCanvasResolutionFactor=e||1}get scaleCanvasResolutionFactor(){return this._scaleCanvasResolutionFactor}set scaleCanvasResolutionFactor(e){this._scaleCanvasResolutionFactor=e||.6}get delayBeforeRestore(){return this._delayBeforeRestore}set delayBeforeRestore(e){this._delayBeforeRestore=e}get delayBeforeRestoreSeconds(){return this._delayBeforeRestoreSeconds}set delayBeforeRestoreSeconds(e){this._delayBeforeRestoreSeconds=null!=e?e:.5}send(e,t){}destroy(){this.viewer.scene.camera.off(this._onCameraMatrix),this.viewer.scene.canvas.off(this._onCanvasBoundary),this.viewer.scene.input.off(this._onSceneMouseDown),this.viewer.scene.input.off(this._onSceneMouseUp),this.viewer.scene.input.off(this._onSceneMouseMove),this.viewer.scene.off(this._onSceneTick),super.destroy()}}class pu{constructor(e={}){this.cacheBuster=!1!==e.cacheBuster}_cacheBusterURL(e){if(!this.cacheBuster)return e;const t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}getMetaModel(e,t,i){y.loadJSON(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getGLTF(e,t,i){y.loadArraybuffer(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getGLB(e,t,i){y.loadArraybuffer(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getArrayBuffer(e,t,i,s){!function(e,t,i,s){var r=()=>{};i=i||r,s=s||r;const o=/^data:(.*?)(;base64)?,(.*)$/,n=t.match(o);if(n){const e=!!n[2];var a=n[3];a=window.decodeURIComponent(a),e&&(a=window.atob(a));try{const e=new ArrayBuffer(a.length),t=new Uint8Array(e);for(var l=0;l{i(e)}),(function(e){s(e)}))}}class fu{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const i=this._messages[this._locale];if(!i)return null;const s=gu(e,i);return s?t?mu(s,t):s:null}translatePlurals(e,t,i){const s=this._messages[this._locale];if(!s)return null;let r=gu(e,s);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=mu(r,[t]),i&&(r=mu(r,i)),r):null}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];if(s)for(const e in s)if(s.hasOwnProperty(e)){s[e].callback(t)}}on(t,i){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let s=this._eventSubs[t];s||(s={},this._eventSubs[t]=s);const r=this._eventSubIDMap.addItem();s[r]={callback:i},this._eventSubEvents[r]=t;const o=this._events[t];return void 0!==o&&i(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const i=this._eventSubs[t];i&&delete i[e],this._eventSubIDMap.removeItem(e)}}}function gu(e,t){if(t[e])return t[e];const i=e.split(".");let s=t;for(let e=0,t=i.length;s&&e1?1:e}get t(){return this._t}get tangent(){return this.getTangent(this._t)}get length(){var e=this._getLengths();return e[e.length-1]}getTangent(e){var t=1e-4;void 0===e&&(e=this._t);var i=e-t,s=e+t;i<0&&(i=0),s>1&&(s=1);var r=this.getPoint(i),o=this.getPoint(s),n=d.subVec3(o,r,[]);return d.normalizeVec3(n,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,i=[];for(t=0;t<=e;t++)i.push(this.getPoint(t/e));return i}_getLengths(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,i,s=[],r=this.getPoint(0),o=0;for(s.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),o+=d.lenVec3(d.subVec3(t,r,[])),s.push(o),r=t;return this.cacheArcLengths=s,s}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var i,s=this._getLengths(),r=0,o=s.length;i=t||e*s[o-1];for(var n,a=0,l=o-1;a<=l;)if((n=s[r=Math.floor(a+(l-a)/2)]-i)<0)a=r+1;else{if(!(n>0)){l=r;break}l=r-1}if(s[r=l]===i)return r/(o-1);var A=s[r];return(r+(i-A)/(s[r+1]-A))/(o-1)}}class vu extends _u{constructor(e,t={}){super(e,t),this.points=t.points,this.t=t.t}set points(e){this._points=e||[]}get points(){return this._points}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=this.points;if(!(t.length<3)){var i=(t.length-1)*e,s=Math.floor(i),r=i-s,o=t[0===s?s:s-1],n=t[s],a=t[s>t.length-2?t.length-1:s+1],l=t[s>t.length-3?t.length-1:s+2],A=d.vec3();return A[0]=d.catmullRomInterpolate(o[0],n[0],a[0],l[0],r),A[1]=d.catmullRomInterpolate(o[1],n[1],a[1],l[1],r),A[2]=d.catmullRomInterpolate(o[2],n[2],a[2],l[2],r),A}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}getJSON(){return{points:points,t:this._t}}}const bu=d.vec3();class yu extends R{get type(){return"CameraPath"}constructor(e,t={}){super(e,t),this._frames=[],this._eyeCurve=new vu(this),this._lookCurve=new vu(this),this._upCurve=new vu(this),t.frames&&(this.addFrames(t.frames),this.smoothFrameTimes(1))}get frames(){return this._frames}get eyeCurve(){return this._eyeCurve}get lookCurve(){return this._lookCurve}get upCurve(){return this._upCurve}saveFrame(e){const t=this.scene.camera;this.addFrame(e,t.eye,t.look,t.up)}addFrame(e,t,i,s){const r={t:e,eye:t.slice(0),look:i.slice(0),up:s.slice(0)};this._frames.push(r),this._eyeCurve.points.push(r.eye),this._lookCurve.points.push(r.look),this._upCurve.points.push(r.up)}addFrames(e){let t;for(let i=0,s=e.length;i1?1:e,t.eye=this._eyeCurve.getPoint(e,bu),t.look=this._lookCurve.getPoint(e,bu),t.up=this._upCurve.getPoint(e,bu)}sampleFrame(e,t,i,s){e=e<0?0:e>1?1:e,this._eyeCurve.getPoint(e,t),this._lookCurve.getPoint(e,i),this._upCurve.getPoint(e,s)}smoothFrameTimes(e){if(0===this._frames.length)return;const t=d.vec3();var i=0;this._frames[0].t=0;const s=[];for(let e=1,o=this._frames.length;e=1;e>1&&(e=1);const i=this.easing?Mu._ease(e,0,1,1):e,s=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(d.subVec3(s.eye,s.look,Cu),s.eye=d.lerpVec3(i,0,1,this._eye1,this._eye2,wu),s.look=d.subVec3(wu,Cu,Bu)):this._flyingLook&&(s.look=d.lerpVec3(i,0,1,this._look1,this._look2,Bu),s.up=d.lerpVec3(i,0,1,this._up1,this._up2,Pu)):this._flyingEyeLookUp&&(s.eye=d.lerpVec3(i,0,1,this._eye1,this._eye2,wu),s.look=d.lerpVec3(i,0,1,this._look1,this._look2,Bu),s.up=d.lerpVec3(i,0,1,this._up1,this._up2,Pu)),this._projection2){const t="ortho"===this._projection2?Mu._easeOutExpo(e,0,1,1):Mu._easeInCubic(e,0,1,1);s.customProjection.matrix=d.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else s.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return s.ortho.scale=this._orthoScale2,void this.stop();I.scheduleTask(this._update,this)}static _ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}static _easeInCubic(e,t,i,s){return i*(e/=s)*e*e+t}static _easeOutExpo(e,t,i,s){return i*(1-Math.pow(2,-10*e/s))+t}stop(){if(!this._flying)return;this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);const e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}cancel(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}set duration(e){this._duration=e?1e3*e:500,this.stop()}get duration(){return this._duration/1e3}set fit(e){this._fit=!1!==e}get fit(){return this._fit}set fitFOV(e){this._fitFOV=e||45}get fitFOV(){return this._fitFOV}set trail(e){this._trail=!!e}get trail(){return this._trail}destroy(){this.stop(),super.destroy()}}class Eu extends R{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new Mu(this),this._t=0,this.state=Eu.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,i;const s=performance.now(),r=this._lastTime?.001*(s-this._lastTime):0;if(this._lastTime=s,0!==r)switch(this.state){case Eu.SCRUBBING:return;case Eu.PLAYING:if(this._t+=this._playingRate*r,t=this._cameraPath.frames.length,0===t||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=Eu.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case Eu.PLAYING_TO:i=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&i<=this._playingToT||this._playingDir>0&&i>=this._playingToT)&&(i=this._playingToT,this.state=Eu.SCRUBBING,this.fire("stopped")),this._t=i,e.loadFrame(this._t)}}_ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}set cameraPath(e){this._cameraPath=e}get cameraPath(){return this._cameraPath}set rate(e){this._playingRate=e}get rate(){return this._playingRate}play(){this._cameraPath&&(this._lastTime=null,this.state=Eu.PLAYING)}playToT(e){this._cameraPath&&(this._playingFromT=this._t,this._playingToT=e,this._playingDir=this._playingToT-this._playingFromT<0?-1:1,this._lastTime=null,this.state=Eu.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const i=t.frames[e];i?this.playToT(i.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const i=this._cameraPath;if(!i)return;const s=i.frames[e];s?(this.state=Eu.SCRUBBING,this._cameraFlightAnimation.flyTo(s,t)):this.error("flyToFrame - frame index out of range: "+e)}scrubToT(e){const t=this._cameraPath;if(!t)return;this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=Eu.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=Eu.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=Eu.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}Eu.STOPPED=0,Eu.SCRUBBING=1,Eu.PLAYING=2,Eu.PLAYING_TO=3;const Fu=d.vec3(),Iu=d.vec3();d.vec3();const Du=d.vec3([0,-1,0]),Su=d.vec4([0,0,0,1]);class Tu extends R{constructor(e,t={}){super(e,t),this._src=null,this._image=null,this._pos=d.vec3(),this._origin=d.vec3(),this._rtcPos=d.vec3(),this._dir=d.vec3(),this._size=1,this._imageSize=d.vec2(),this._texture=new so(this),this._plane=new wr(this,{geometry:new ei(this,fo({center:[0,0,0],xSize:1,zSize:1,xSegments:10,zSegments:10})),material:new oi(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0}),clippable:t.clippable}),this._grid=new wr(this,{geometry:new ei(this,po({size:1,divisions:10})),material:new oi(this,{diffuse:[0,0,0],ambient:[0,0,0],emissive:[.2,.8,.2]}),position:[0,.001,0],clippable:t.clippable}),this._node=new Vr(this,{rotation:[0,0,0],position:[0,0,0],scale:[1,1,1],clippable:!1,children:[this._plane,this._grid]}),this._gridVisible=!1,this.visible=!0,this.gridVisible=t.gridVisible,this.position=t.position,this.rotation=t.rotation,this.dir=t.dir,this.size=t.size,this.collidable=t.collidable,this.clippable=t.clippable,this.pickable=t.pickable,this.opacity=t.opacity,t.image?this.image=t.image:this.src=t.src}set visible(e){this._plane.visible=e,this._grid.visible=this._gridVisible&&e}get visible(){return this._plane.visible}set gridVisible(e){e=!1!==e,this._gridVisible=e,this._grid.visible=this._gridVisible&&this.visible}get gridVisible(){return this._gridVisible}set image(e){this._image=e,this._image&&(this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}get image(){return this._image}set src(e){if(this._src=e,this._src){this._image=null;const e=new Image;e.onload=()=>{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set position(e){this._pos.set(e||[0,0,0]),Y(this._pos,this._origin,this._rtcPos),this._node.origin=this._origin,this._node.position=this._rtcPos}get position(){return this._pos}set rotation(e){this._node.rotation=e}get rotation(){return this._node.rotation}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set dir(e){if(this._dir.set(e||[0,0,-1]),e){const t=this.scene.center,i=[-this._dir[0],-this._dir[1],-this._dir[2]];d.subVec3(t,this.position,Fu);const s=-d.dotVec3(i,Fu);d.normalizeVec3(i),d.mulVec3Scalar(i,s,Iu),d.vec3PairToQuaternion(Du,e,Su),this._node.quaternion=Su}}get dir(){return this._dir}set collidable(e){this._node.collidable=!1!==e}get collidable(){return this._node.collidable}set clippable(e){this._node.clippable=!1!==e}get clippable(){return this._node.clippable}set pickable(e){this._node.pickable=!1!==e}get pickable(){return this._node.pickable}set opacity(e){this._node.opacity=e}get opacity(){return this._node.opacity}destroy(){super.destroy()}_updatePlaneSizeFromImage(){const e=this._size,t=this._imageSize[0],i=this._imageSize[1];if(t>i){const s=i/t;this._node.scale=[e,1,e*s]}else{const s=t/i;this._node.scale=[e*s,1,e]}}}class Ru extends Qt{get type(){return"PointLight"}constructor(e,t={}){super(e,t);const i=this;this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const s=this.scene.camera,r=this.scene.canvas;this._onCameraViewMatrix=s.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=s.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=r.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new _t({type:"point",pos:d.vec3([1,1,1]),color:d.vec3([.7,.7,.8]),intensity:1,attenuation:[0,0,0],space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(i._shadowViewMatrixDirty){i._shadowViewMatrix||(i._shadowViewMatrix=d.identityMat4());const e=i._state.pos,t=s.look,r=s.up;d.lookAtMat4v(e,t,r,i._shadowViewMatrix),i._shadowViewMatrixDirty=!1}return i._shadowViewMatrix},getShadowProjMatrix:()=>{if(i._shadowProjMatrixDirty){i._shadowProjMatrix||(i._shadowProjMatrix=d.identityMat4());const e=i.scene.canvas.canvas;d.perspectiveMat4(Math.PI/180*70,e.clientWidth/e.clientHeight,.1,500,i._shadowProjMatrix),i._shadowProjMatrixDirty=!1}return i._shadowProjMatrix},getShadowRenderBuf:()=>(i._shadowRenderBuf||(i._shadowRenderBuf=new ut(i.scene.canvas.canvas,i.scene.canvas.gl,{size:[1024,1024]})),i._shadowRenderBuf)}),this.pos=t.pos,this.color=t.color,this.intensity=t.intensity,this.constantAttenuation=t.constantAttenuation,this.linearAttenuation=t.linearAttenuation,this.quadraticAttenuation=t.quadraticAttenuation,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set pos(e){this._state.pos.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get pos(){return this._state.pos}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set constantAttenuation(e){this._state.attenuation[0]=e||0,this.glRedraw()}get constantAttenuation(){return this._state.attenuation[0]}set linearAttenuation(e){this._state.attenuation[1]=e||0,this.glRedraw()}get linearAttenuation(){return this._state.attenuation[1]}set quadraticAttenuation(e){this._state.attenuation[2]=e||0,this.glRedraw()}get quadraticAttenuation(){return this._state.attenuation[2]}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}function Lu(e){if(!Uu(e.width)||!Uu(e.height)){const t=document.createElement("canvas");t.width=Ou(e.width),t.height=Ou(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function Uu(e){return 0==(e&e-1)}function Ou(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class ku extends R{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const i=this.scene.canvas.gl;this._state=new _t({texture:new Zr({gl:i,target:i.TEXTURE_CUBE_MAP}),flipY:this._checkFlipY(t.minFilter),encoding:this._checkEncoding(t.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),this._src=t.src,this._images=[],this._loadSrc(t.src),m.memory.textures++}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}_loadSrc(e){const t=this,i=this.scene.canvas.gl;this._images=[];let s=!1,r=0;for(let o=0;o{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set collidable(e){this._mesh.collidable=!1!==e}get collidable(){return this._mesh.collidable}set clippable(e){this._mesh.clippable=!1!==e}get clippable(){return this._mesh.clippable}set pickable(e){this._mesh.pickable=!1!==e}get pickable(){return this._mesh.pickable}set opacity(e){this._mesh.opacity=e}get opacity(){return this._mesh.opacity}_updatePlaneSizeFromImage(){const e=.5*this._size,t=this._imageSize[0],i=this._imageSize[1],s=i/t;this._geometry.positions=t>i?[e,e*s,0,-e,e*s,0,-e,-e*s,0,e,-e*s,0]:[e/s,e,0,-e/s,e,0,-e/s,-e,0,e/s,-e,0]}}class Hu{constructor(e){this._eye=d.vec3(),this._look=d.vec3(),this._up=d.vec3(),this._projection={},e&&this.saveCamera(e)}saveCamera(e){const t=e.camera,i=t.project;switch(this._eye.set(t.eye),this._look.set(t.look),this._up.set(t.up),t.projection){case"perspective":this._projection={projection:"perspective",fov:i.fov,fovAxis:i.fovAxis,near:i.near,far:i.far};break;case"ortho":this._projection={projection:"ortho",scale:i.scale,near:i.near,far:i.far};break;case"frustum":this._projection={projection:"frustum",left:i.left,right:i.right,top:i.top,bottom:i.bottom,near:i.near,far:i.far};break;case"custom":this._projection={projection:"custom",matrix:i.matrix.slice()}}}restoreCamera(e,t){const i=e.camera,s=this._projection;function r(){switch(s.type){case"perspective":i.perspective.fov=s.fov,i.perspective.fovAxis=s.fovAxis,i.perspective.near=s.near,i.perspective.far=s.far;break;case"ortho":i.ortho.scale=s.scale,i.ortho.near=s.near,i.ortho.far=s.far;break;case"frustum":i.frustum.left=s.left,i.frustum.right=s.right,i.frustum.top=s.top,i.frustum.bottom=s.bottom,i.frustum.near=s.near,i.frustum.far=s.far;break;case"custom":i.customProjection.matrix=s.matrix}}t?e.viewer.cameraFlight.flyTo({eye:this._eye,look:this._look,up:this._up,orthoScale:s.scale,projection:s.projection},(()=>{r(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,r(),i.projection=s.projection)}}const ju=d.vec3();class Gu{constructor(e){if(this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsOpacity=[],this.numObjects=0,e){const t=e.metaScene.scene;this.saveObjects(t,e)}}saveObjects(e,t,i){this.numObjects=0,this._mask=i?y.apply(i,{}):null;const s=!i||i.visible,r=!i||i.edges,o=!i||i.xrayed,n=!i||i.highlighted,a=!i||i.selected,l=!i||i.clippable,A=!i||i.pickable,h=!i||i.colorize,c=!i||i.opacity,u=t.metaObjects,d=e.objects;for(let e=0,t=u.length;e1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=d.vec3();return t[0]=d.b3(e,this._v0[0],this._v1[0],this._v2[0],this._v3[0]),t[1]=d.b3(e,this._v0[1],this._v1[1],this._v2[1],this._v3[1]),t[2]=d.b3(e,this._v0[2],this._v1[2],this._v2[2],this._v3[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,v3:this._v3,t:this._t}}}class Xu extends _u{constructor(e,t={}){super(e,t),this._cachedLengths=[],this._dirty=!0,this._curves=[],this._t=0,this._dirtySubs=[],this._destroyedSubs=[],this.curves=t.curves||[],this.t=t.t}addCurve(e){this._curves.push(e),this._dirty=!0}set curves(e){var t,i,s;for(e=e||[],i=0,s=this._curves.length;i1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}get length(){var e=this._getCurveLengths();return e[e.length-1]}getPoint(e){for(var t,i=e*this.length,s=this._getCurveLengths(),r=0;r=i){var o=1-(s[r]-i)/(t=this._curves[r]).length;return t.getPointAt(o)}r++}return null}_getCurveLengths(){if(!this._dirty)return this._cachedLengths;var e,t=[],i=0,s=this._curves.length;for(e=0;e1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=d.vec3();return t[0]=d.b2(e,this._v0[0],this._v1[0],this._v2[0]),t[1]=d.b2(e,this._v0[1],this._v1[1],this._v2[1]),t[2]=d.b2(e,this._v0[2],this._v1[2],this._v2[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,t:this._t}}}class Yu extends Gc{constructor(e,t={}){super(e,t)}}class Zu extends R{constructor(e,t={}){super(e,t),this._skyboxMesh=new wr(this,{geometry:new ei(this,{primitive:"triangles",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]}),background:!0,scale:[2e3,2e3,2e3],rotation:[0,-90,0],material:new oi(this,{ambient:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],emissive:[1,1,1],emissiveMap:new so(this,{src:t.src,flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge",encoding:t.encoding||"sRGB"}),backfaces:!0}),visible:!1,pickable:!1,clippable:!1,collidable:!1}),this.size=t.size,this.active=t.active}set size(e){this._size=e||1e3,this._skyboxMesh.scale=[this._size,this._size,this._size]}get size(){return this._size}set active(e){this._skyboxMesh.visible=e}get active(){return this._skyboxMesh.visible}}class qu{transcode(e,t,i={}){}destroy(){}}const $u=d.vec4(),ed=d.vec4(),td=d.vec3(),id=d.vec3(),sd=d.vec3(),rd=d.vec4(),od=d.vec4(),nd=d.vec4();class ad{constructor(e){this._scene=e}dollyToCanvasPos(e,t,i){let s=!1;const r=this._scene.camera;if(e){const t=d.subVec3(e,r.eye,td);s=d.lenVec3(t){this._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(()=>{this._cameraDirty=!0})),this._onTick=this._scene.on("tick",(()=>{this.updatePivotElement(),this.updatePivotSphere()}))}createPivotSphere(){const e=this.getPivotPos(),t=d.vec3();d.decomposeMat4(d.inverseMat4(this._scene.viewer.camera.viewMatrix,d.mat4()),t,d.vec4(),d.vec3());const i=d.distVec3(t,e);let s=Math.tan(Math.PI/500)*i*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(s/=this._scene.camera.ortho.scale/2),Y(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new ao(this._scene,Mr({radius:s})),this._pivotSphere=new wr(this._scene,{geometry:this._pivotSphereGeometry,material:this._pivotSphereMaterial,pickable:!1,position:this._rtcPos,rtcCenter:this._rtcCenter})}destroyPivotSphere(){this._pivotSphere&&(this._pivotSphere.destroy(),this._pivotSphere=null),this._pivotSphereGeometry&&(this._pivotSphereGeometry.destroy(),this._pivotSphereGeometry=null)}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){d.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,d.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const i=t.boundary,s=i[2],r=i[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*s/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*r/2);let o=t._lastBoundingClientRect;if(!o||t._canvasSizeChanged){const e=t.canvas;o=t._lastBoundingClientRect=e.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(o.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(o.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}updatePivotSphere(){this._pivoting&&this._pivotSphere&&(Y(this.getPivotPos(),this._rtcCenter,this._rtcPos),d.compareVec3(this._rtcPos,this._pivotSphere.position)||(this.destroyPivotSphere(),this.createPivotSphere()))}setPivotElement(e){this._pivotElement=e}enablePivotSphere(e={}){this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);const t=e.color||[1,0,0];this._pivotSphereMaterial=new oi(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}disablePivotSphere(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}startPivot(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;const e=this._scene.camera;let t=d.lookAtMat4v(e.eye,e.look,e.worldUp);d.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const i=this.getPivotPos();this._cameraOffset[2]+=d.distVec3(e.eye,i),t=d.inverseMat4(t);const s=d.transformVec3(t,this._cameraOffset),r=d.vec3();if(d.subVec3(e.eye,i,r),d.addVec3(r,s),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=d.lenVec3(r),this._polar=Math.acos(r[1]/this._radius),this._azimuth=Math.atan2(r[0],r[2]),this._pivoting=!0}_cameraLookingDownwards(){const e=this._scene.camera,t=d.normalizeVec3(d.subVec3(e.look,e.eye,ld)),i=d.cross3Vec3(t,e.worldUp,Ad);return d.sqLenVec3(i)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}setCanvasPivotPos(e){const t=this._scene.camera,i=Math.abs(d.distVec3(this._scene.center,t.eye)),s=t.project.transposedMatrix,r=s.subarray(8,12),o=s.subarray(12),n=[0,0,-1,1],a=d.dotVec4(n,r)/d.dotVec4(n,o),l=cd;t.project.unproject(e,a,ud,dd,l);const A=d.normalizeVec3(d.subVec3(l,t.eye,ld)),h=d.addVec3(t.eye,d.mulVec3Scalar(A,i,Ad),hd);this.setPivotPos(h)}getPivotPos(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const i=this._scene.camera;var s=-e;const r=-t;1===i.worldUp[2]&&(s=-s),this._azimuth+=.01*-s,this._polar+=.01*r,this._polar=d.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 n=d.lenVec3(d.subVec3(i.look,i.eye,d.vec3())),a=this.getPivotPos();d.addVec3(o,a);let l=d.lookAtMat4v(o,a,i.worldUp);l=d.inverseMat4(l);const A=d.transformVec3(l,this._cameraOffset);l[12]-=A[0],l[13]-=A[1],l[14]-=A[2];const h=[l[8],l[9],l[10]];i.eye=[l[12],l[13],l[14]],d.subVec3(i.eye,d.mulVec3Scalar(h,n),i.look),i.up=[l[4],l[5],l[6]],this.showPivot()}showPivot(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}hidePivot(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}endPivot(){this._pivoting=!1}destroy(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}class fd{constructor(e,t){this._scene=e.scene,this._cameraControl=e,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=t,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=d.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;const e=`${~~this.pickCursorPos[0]}-${~~this.pickCursorPos[1]}-${this.scheduleSnapOrPick}-${this.schedulePickSurface}-${this.schedulePickEntity}`;if(this._lastHash===e)return;this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;const t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){const e=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});e&&(e.snappedToEdge||e.snappedToVertex)?(this.snapPickResult=e,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const e=this.pickResult.canvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){const e=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){const e=new Ge;e.entity=this.snapPickResult.entity,e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){const e=this.pickResult.entity.id;this._lastPickedEntityId!==e&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=e)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}const gd=d.vec2();class md{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController;let n,a,l,A=0,h=0,c=0,u=0,p=!1;const f=d.vec3();let g=!0;const m=this._scene.canvas.canvas,_=[];function v(e=!0){m.style.cursor="move",A=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],c=s.pointerCanvasPos[0],u=s.pointerCanvasPos[1],e&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(p=!0,f.set(o.pickResult.worldPos)):p=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!1}),m.addEventListener("mousedown",this._mouseDownHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:_[e.input.KEY_SHIFT]||i.planView?(n=!0,v()):(n=!0,v(!1));break;case 2:a=!0,v();break;case 3:l=!0,i.panRightClick&&v()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(!n&&!a&&!l)return;const o=e.canvas.boundary,c=o[2],u=o[3],g=s.pointerCanvasPos[0],m=s.pointerCanvasPos[1],v=_[e.input.KEY_SHIFT]||i.planView||!i.panRightClick&&a||i.panRightClick&&l,b=document.pointerLockElement?t.movementX:g-A,y=document.pointerLockElement?t.movementY:m-h;if(v){const t=e.camera;if("perspective"===t.projection){const i=Math.abs(p?d.lenVec3(d.subVec3(f,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(t.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*b*i/u,r.panDeltaY+=1.5*y*i/u}else r.panDeltaX+=.5*t.ortho.scale*(b/u),r.panDeltaY+=.5*t.ortho.scale*(y/u)}else!n||a||l||i.planView||(i.firstPerson?(r.rotateDeltaY-=b/c*i.dragRotationRate/2,r.rotateDeltaX+=y/u*(i.dragRotationRate/4)):(r.rotateDeltaY-=b/c*(1.5*i.dragRotationRate),r.rotateDeltaX+=y/u*(1.5*i.dragRotationRate)));A=g,h=m}),m.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{i.active&&i.pointerEnabled&&s.mouseover&&(g=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{if(i.active&&i.pointerEnabled)switch(e.which){case 1:case 2:case 3:n=!1,a=!1,l=!1}}),m.addEventListener("mouseup",this._mouseUpHandler=e=>{if(i.active&&i.pointerEnabled){if(3===e.which){!function(e,t){if(e){let i=e.target,s=0,r=0,o=0,n=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,o+=i.scrollLeft,n+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+o-s,t[1]=e.pageY+n-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,gd);const i=gd[0],s=gd[1];Math.abs(i-c)<3&&Math.abs(s-u)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:gd,event:e},!0)}m.style.removeProperty("cursor")}}),m.addEventListener("mouseenter",this._mouseEnterHandler=()=>{i.active&&i.pointerEnabled});const b=1/60;let y=null;m.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!(i.active&&i.pointerEnabled&&i.zoomOnMouseWheel))return;const t=performance.now()/1e3;var o=null!==y?t-y:0;y=t,o>.05&&(o=.05),o{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover)return;const n=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),a=r._isKeyDownForAction(r.AXIS_VIEW_BACK),l=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),A=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),h=r._isKeyDownForAction(r.AXIS_VIEW_TOP),c=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(n||a||l||A||h||c))return;const u=e.aabb,p=d.getAABB3Diag(u);d.getAABB3Center(u,_d);const f=Math.abs(p/Math.tan(t.cameraFlight.fitFOV*d.DEGTORAD)),g=1.1*p;Bd.orthoScale=g,n?(Bd.eye.set(d.addVec3(_d,d.mulVec3Scalar(o.worldRight,f,vd),xd)),Bd.look.set(_d),Bd.up.set(o.worldUp)):a?(Bd.eye.set(d.addVec3(_d,d.mulVec3Scalar(o.worldForward,f,vd),xd)),Bd.look.set(_d),Bd.up.set(o.worldUp)):l?(Bd.eye.set(d.addVec3(_d,d.mulVec3Scalar(o.worldRight,-f,vd),xd)),Bd.look.set(_d),Bd.up.set(o.worldUp)):A?(Bd.eye.set(d.addVec3(_d,d.mulVec3Scalar(o.worldForward,-f,vd),xd)),Bd.look.set(_d),Bd.up.set(o.worldUp)):h?(Bd.eye.set(d.addVec3(_d,d.mulVec3Scalar(o.worldUp,f,vd),xd)),Bd.look.set(_d),Bd.up.set(d.normalizeVec3(d.mulVec3Scalar(o.worldForward,1,bd),yd))):c&&(Bd.eye.set(d.addVec3(_d,d.mulVec3Scalar(o.worldUp,-f,vd),xd)),Bd.look.set(_d),Bd.up.set(d.normalizeVec3(d.mulVec3Scalar(o.worldForward,-1,bd)))),!i.firstPerson&&i.followPointer&&t.pivotController.setPivotPos(_d),t.cameraFlight.duration>0?t.cameraFlight.flyTo(Bd,(()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(Bd),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class Pd{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;let l=!1,A=!1;const h=this._scene.canvas.canvas,c=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i&&i.entity?i.entity.aabb:e.aabb;if(s){const i=e.camera;d.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})},u=e.tickify(this._canvasMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(l||A)return;if(a.hasSubs("rayMove")){const t=d.vec3(),i=d.vec3();d.canvasPosToWorldRay(e.canvas.canvas,e.camera.viewMatrix,e.camera.projMatrix,e.camera.projection,s.pointerCanvasPos,t,i),a.fire("rayMove",{canvasPos:s.pointerCanvasPos,ray:{origin:t,direction:i,canvasPos:s.pointerCanvasPos}},!0)}const r=a.hasSubs("hover"),n=a.hasSubs("hoverEnter"),h=a.hasSubs("hoverOut"),c=a.hasSubs("hoverOff"),u=a.hasSubs("hoverSurface"),p=a.hasSubs("hoverSnapOrSurface");if(r||n||h||c||u||p)if(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=u,o.scheduleSnapOrPick=p,o.update(),o.pickResult){if(o.pickResult.entity){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),a.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t)}a.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&a.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),a.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)});h.addEventListener("mousemove",u),h.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(l=!0),3===t.which&&(A=!0);if(1===t.which&&i.active&&i.pointerEnabled&&(s.mouseDownClientX=t.clientX,s.mouseDownClientY=t.clientY,s.mouseDownCursorX=s.pointerCanvasPos[0],s.mouseDownCursorY=s.pointerCanvasPos[1],!i.firstPerson&&i.followPointer&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===t.which))){const t=o.pickResult;t&&t.worldPos?(n.setPivotPos(t.worldPos),n.startPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),n.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(l=!1),3===e.which&&(A=!1),n.getPivoting()&&n.endPivot()}),h.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!i.active||!i.pointerEnabled)return;if(!(1===r.which))return;if(n.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const l=a.hasSubs("picked"),A=a.hasSubs("pickedNothing"),h=a.hasSubs("pickedSurface"),u=a.hasSubs("doublePicked"),p=a.hasSubs("doublePickedSurface"),f=a.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||u||p||f))return(l||A||h)&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=h,o.update(),o.pickResult?(a.fire("picked",o.pickResult,!0),o.pickedSurface&&a.fire("pickedSurface",o.pickResult,!0)):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=h,o.update();const e=o.pickResult,r=o.pickedSurface;this._timeout=setTimeout((()=>{e&&e.worldPos?(a.fire("picked",e,!0),r&&(a.fire("pickedSurface",e,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),this._clicks=0}),i.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo||u||p,o.schedulePickSurface=o.schedulePickEntity&&p,o.update(),o.pickResult){if(a.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&a.fire("doublePickedSurface",o.pickResult,!0),i.doublePickFlyTo&&(c(o.pickResult),!i.firstPerson&&i.followPointer)){const e=o.pickResult.entity.aabb,i=d.getAABB3Center(e);t.pivotController.setPivotPos(i),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(a.fire("doublePickedNothing",{canvasPos:s.pointerCanvasPos},!0),i.doublePickFlyTo&&(c(),!i.firstPerson&&i.followPointer)){const i=e.aabb,s=d.getAABB3Center(i);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}this._clicks=0}},!1)}reset(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}class Cd{constructor(e,t,i,s,r){this._scene=e;const o=e.input,n=[],a=e.canvas.canvas;let l=!0;this._onSceneMouseMove=o.on("mousemove",(()=>{l=!0})),this._onSceneKeyDown=o.on("keydown",(t=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover||(n[t]=!0,t===o.KEY_SHIFT&&(a.style.cursor="move")))})),this._onSceneKeyUp=o.on("keyup",(s=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(n[s]=!1,s===o.KEY_SHIFT&&(a.style.cursor=null),t.pivotController.getPivoting()&&t.pivotController.endPivot())})),this._onTick=e.on("tick",(a=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover)return;const A=t.cameraControl,h=a.deltaTime/1e3;if(!i.planView){const e=A._isKeyDownForAction(A.ROTATE_Y_POS,n),s=A._isKeyDownForAction(A.ROTATE_Y_NEG,n),o=A._isKeyDownForAction(A.ROTATE_X_POS,n),a=A._isKeyDownForAction(A.ROTATE_X_NEG,n),l=h*i.keyboardRotationRate;(e||s||o||a)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:s&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:a&&(r.rotateDeltaX-=l),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!n[o.KEY_CTRL]&&!n[o.KEY_ALT]){const e=A._isKeyDownForAction(A.DOLLY_BACKWARDS,n),o=A._isKeyDownForAction(A.DOLLY_FORWARDS,n);if(e||o){const n=h*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=n:e&&(r.dollyDelta+=n),l&&(s.followPointerDirty=!0,l=!1)}}const c=A._isKeyDownForAction(A.PAN_FORWARDS,n),u=A._isKeyDownForAction(A.PAN_BACKWARDS,n),d=A._isKeyDownForAction(A.PAN_LEFT,n),p=A._isKeyDownForAction(A.PAN_RIGHT,n),f=A._isKeyDownForAction(A.PAN_UP,n),g=A._isKeyDownForAction(A.PAN_DOWN,n),m=(n[o.KEY_ALT]?.3:1)*h*i.keyboardPanRate;(c||u||d||p||f||g)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),g?r.panDeltaY+=m:f&&(r.panDeltaY+=-m),p?r.panDeltaX+=-m:d&&(r.panDeltaX+=m),u?r.panDeltaZ+=m:c&&(r.panDeltaZ+=-m))}))}reset(){}destroy(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),this._scene.input.off(this._onSceneKeyUp)}}const Md=d.vec3();class Ed{constructor(e,t,i,s,r){this._scene=e;const o=e.camera,n=t.pickController,a=t.pivotController,l=t.panController;let A=1,h=1,c=null;this._onTick=e.on("tick",(()=>{if(!i.active||!i.pointerEnabled)return;let t="default";if(Math.abs(r.dollyDelta)<.001&&(r.dollyDelta=0),Math.abs(r.rotateDeltaX)<.001&&(r.rotateDeltaX=0),Math.abs(r.rotateDeltaY)<.001&&(r.rotateDeltaY=0),0===r.rotateDeltaX&&0===r.rotateDeltaY||(r.dollyDelta=0),i.followPointer){if(--A<=0&&(A=1,0!==r.dollyDelta)){if(0===r.rotateDeltaY&&0===r.rotateDeltaX&&i.followPointer&&s.followPointerDirty&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),n.pickResult&&n.pickResult.worldPos?c=n.pickResult.worldPos:(h=1,c=null),s.followPointerDirty=!1),c){const t=Math.abs(d.lenVec3(d.subVec3(c,e.camera.eye,Md)));h=t/i.dollyProximityThreshold}h{s.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{s.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{Id(e,o,s.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=e=>{i.active&&i.pointerEnabled&&(Id(e,o,s.pointerCanvasPos),s.mouseover=!0)}),o.addEventListener("mouseup",this._mouseUpHandler=e=>{i.active&&i.pointerEnabled})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}function Id(e,t,i){if(e){const{left:s,top:r}=t.getBoundingClientRect();i[0]=e.clientX-s,i[1]=e.clientY-r}else e=window.event,i[0]=e.x,i[1]=e.y;return i}const Dd=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 Sd{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=d.vec2(),l=d.vec2(),A=d.vec2(),h=d.vec2(),c=[],u=this._scene.canvas.canvas;let p=0,f=!1;this._onTick=e.on("tick",(()=>{f=!1})),u.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!i.active||!i.pointerEnabled)return;t.preventDefault();const r=t.touches,l=t.changedTouches;for(s.touchStartTime=Date.now(),1===r.length&&1===l.length&&(Dd(r[0],a),i.followPointer&&(o.pickCursorPos=a,o.schedulePickSurface=!0,o.update(),i.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(n.setPivotPos(o.pickResult.worldPos),!i.firstPerson&&n.startPivot()&&n.showPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),!i.firstPerson&&n.startPivot()&&n.showPivot()))));c.length{n.getPivoting()&&n.endPivot()}),u.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const n=e.canvas.boundary,a=n[2],u=n[3],g=t.touches;if(t.touches.length===p){if(1===p){Dd(g[0],l),d.subVec2(l,c[0],h);const t=h[0],o=h[1];if(null!==s.longTouchTimeout&&(Math.abs(t)>i.longTapRadius||Math.abs(o)>i.longTapRadius)&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),i.planView){const s=e.camera;if("perspective"===s.projection){const n=Math.abs(e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*n/u*i.touchPanRate,r.panDeltaY+=o*n/u*i.touchPanRate}else r.panDeltaX+=.5*s.ortho.scale*(t/u)*i.touchPanRate,r.panDeltaY+=.5*s.ortho.scale*(o/u)*i.touchPanRate}else r.rotateDeltaY-=t/a*(1*i.dragRotationRate),r.rotateDeltaX+=o/u*(1.5*i.dragRotationRate)}else if(2===p){const t=g[0],n=g[1];Dd(t,l),Dd(n,A);const a=d.geometricMeanVec2(c[0],c[1]),h=d.geometricMeanVec2(l,A),p=d.vec2();d.subVec2(a,h,p);const f=p[0],m=p[1],_=e.camera,v=d.distVec2([t.pageX,t.pageY],[n.pageX,n.pageY]),b=(d.distVec2(c[0],c[1])-v)*i.touchDollyRate;if(r.dollyDelta=b,Math.abs(b)<1)if("perspective"===_.projection){const t=o.pickResult?o.pickResult.worldPos:e.center,s=Math.abs(d.lenVec3(d.subVec3(t,e.camera.eye,[])))*Math.tan(_.perspective.fov/2*Math.PI/180);r.panDeltaX-=f*s/u*i.touchPanRate,r.panDeltaY-=m*s/u*i.touchPanRate}else r.panDeltaX-=.5*_.ortho.scale*(f/u)*i.touchPanRate,r.panDeltaY-=.5*_.ortho.scale*(m/u)*i.touchPanRate;s.pointerCanvasPos=h}for(let e=0;e{let s;i&&i.worldPos&&(s=i.worldPos);const r=i?i.entity.aabb:e.aabb;if(s){const i=e.camera;d.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};u.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!i.active||!i.pointerEnabled)return;null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null);const r=e.touches,o=e.changedTouches;if(a=Date.now(),1===r.length&&1===o.length){h=a,Td(r[0],A);const o=A[0],n=A[1],l=r[0].pageX,c=r[0].pageY;s.longTouchTimeout=setTimeout((()=>{t.cameraControl.fire("rightClick",{pagePos:[Math.round(l),Math.round(c)],canvasPos:[Math.round(o),Math.round(n)],event:e},!0),s.longTouchTimeout=null}),i.longTapTimeout)}else h=-1;for(;l.length{if(!i.active||!i.pointerEnabled)return;const t=Date.now(),r=e.touches,a=e.changedTouches,u=n.hasSubs("pickedSurface");null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),0===r.length&&1===a.length&&h>-1&&t-h<150&&(c>-1&&h-c<325?(Td(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=u,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("doublePicked",o.pickResult),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult),i.doublePickFlyTo&&p(o.pickResult)):(n.fire("doublePickedNothing"),i.doublePickFlyTo&&p()),c=-1):d.distVec2(l[0],A)<4&&(Td(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=u,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("picked",o.pickResult),o.pickedSurface&&n.fire("pickedSurface",o.pickResult)):n.fire("pickedNothing"),c=t),h=-1),l.length=r.length;for(let e=0,t=r.length;e{e.preventDefault()},this._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,zoomOnMouseWheel:!0,snapToVertex:true,snapToEdge:true,snapRadius:30,keyboardEnabledOnlyIfMouseover:!0,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},this._states={pointerCanvasPos:d.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:d.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const i=this.scene;this._controllers={cameraControl:this,pickController:new fd(this,this._configs),pivotController:new pd(i,this._configs),panController:new ad(i),cameraFlight:new Mu(this,{duration:.5})},this._handlers=[new Fd(this.scene,this._controllers,this._configs,this._states,this._updates),new Sd(this.scene,this._controllers,this._configs,this._states,this._updates),new md(this.scene,this._controllers,this._configs,this._states,this._updates),new wd(this.scene,this._controllers,this._configs,this._states,this._updates),new Pd(this.scene,this._controllers,this._configs,this._states,this._updates),new Rd(this.scene,this._controllers,this._configs,this._states,this._updates),new Cd(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new Ed(this.scene,this._controllers,this._configs,this._states,this._updates),this.navMode=t.navMode,t.planView&&(this.planView=t.planView),this.constrainVertical=t.constrainVertical,t.keyboardLayout?this.keyboardLayout=t.keyboardLayout:this.keyMap=t.keyMap,this.doublePickFlyTo=t.doublePickFlyTo,this.panRightClick=t.panRightClick,this.active=t.active,this.followPointer=t.followPointer,this.rotationInertia=t.rotationInertia,this.keyboardPanRate=t.keyboardPanRate,this.touchPanRate=t.touchPanRate,this.keyboardRotationRate=t.keyboardRotationRate,this.dragRotationRate=t.dragRotationRate,this.touchDollyRate=t.touchDollyRate,this.dollyInertia=t.dollyInertia,this.dollyProximityThreshold=t.dollyProximityThreshold,this.dollyMinSpeed=t.dollyMinSpeed,this.panInertia=t.panInertia,this.pointerEnabled=!0,this.keyboardDollyRate=t.keyboardDollyRate,this.mouseWheelDollyRate=t.mouseWheelDollyRate}set keyMap(e){if(e=e||"qwerty",y.isString(e)){const t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=i}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_isKeyDownForAction(e,t){const i=this._keyMap[e];if(!i)return!1;t||(t=this.scene.input.keyDown);for(let e=0,s=i.length;e0&&console.error(`[MetaModel._decompressProperties] Properties not found: ${i}`)}finalize(){if(this.finalized)throw"MetaScene already finalized - can't re-finalize";const e=this.metaScene;for(let t in e.metaObjects){const i=e.metaObjects[t];if(i.children&&(i.children=[]),i.propertySets&&(i.propertySets=[]),i.propertySetIds)for(let t=0,s=i.propertySetIds.length;t0?Vd(t):null,n=i&&i.length>0?Vd(i):null,a=e=>{if(!e)return;var t=!0;(n&&n[e.type]||o&&!o[e.type])&&(t=!1),t&&s.push(e.id);const i=e.children;if(i)for(var r=0,l=i.length;r * Copyright (c) 2022 Niklas von Hertzen @@ -33,5 +33,5 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */var Hd=function(e,t){return Hd=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},Hd(e,t)};function jd(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}Hd(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}var Gd=function(){return Gd=Object.assign||function(e){for(var t,i=1,s=arguments.length;i0&&r[r.length-1])||6!==o[0]&&2!==o[0])){n=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]=55296&&r<=56319&&i>10),n%1024+56320)),(r+1===i||s.length>16384)&&(o+=String.fromCharCode.apply(String,s),s.length=0)}return o},qd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",$d="undefined"==typeof Uint8Array?[]:new Uint8Array(256),ep=0;ep=0){if(e<55296||e>56319&&e<=65535)return t=((t=this.index[e>>5])<<2)+(31&e),this.data[t];if(e<=65535)return t=((t=this.index[2048+(e-55296>>5)])<<2)+(31&e),this.data[t];if(e>11),t=this.index[t],t+=e>>5&63,t=((t=this.index[t])<<2)+(31&e),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},e}(),np="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ap="undefined"==typeof Uint8Array?[]:new Uint8Array(256),lp=0;lp>4,h[l++]=(15&s)<<4|r>>2,h[l++]=(3&r)<<6|63&o;return A}(e),n=Array.isArray(o)?function(e){for(var t=e.length,i=[],s=0;s0;){var n=s[--o];if(Array.isArray(e)?-1!==e.indexOf(n):e===n)for(var a=i;a<=s.length;){var l;if((l=s[++a])===t)return!0;if(l!==Ap)break}if(n!==Ap)break}return!1},jp=function(e,t){for(var i=e;i>=0;){var s=t[i];if(s!==Ap)return s;i--}return 0},Gp=function(e,t,i,s,r){if(0===i[s])return"×";var o=s-1;if(Array.isArray(r)&&!0===r[o])return"×";var n=o-1,a=o+1,l=t[o],A=n>=0?t[n]:0,h=t[a];if(2===l&&3===h)return"×";if(-1!==Up.indexOf(l))return"!";if(-1!==Up.indexOf(h))return"×";if(-1!==kp.indexOf(h))return"×";if(8===jp(o,t))return"÷";if(11===Rp.get(e[o]))return"×";if((l===wp||l===Pp)&&11===Rp.get(e[a]))return"×";if(7===l||7===h)return"×";if(9===l)return"×";if(-1===[Ap,hp,cp].indexOf(l)&&9===h)return"×";if(-1!==[up,dp,pp,_p,xp].indexOf(h))return"×";if(jp(o,t)===mp)return"×";if(Hp(23,mp,o,t))return"×";if(Hp([up,dp],gp,o,t))return"×";if(Hp(12,12,o,t))return"×";if(l===Ap)return"÷";if(23===l||23===h)return"×";if(16===h||16===l)return"÷";if(-1!==[hp,cp,gp].indexOf(h)||14===l)return"×";if(36===A&&-1!==Vp.indexOf(l))return"×";if(l===xp&&36===h)return"×";if(h===fp)return"×";if(-1!==Lp.indexOf(h)&&l===vp||-1!==Lp.indexOf(l)&&h===vp)return"×";if(l===yp&&-1!==[Ep,wp,Pp].indexOf(h)||-1!==[Ep,wp,Pp].indexOf(l)&&h===bp)return"×";if(-1!==Lp.indexOf(l)&&-1!==Op.indexOf(h)||-1!==Op.indexOf(l)&&-1!==Lp.indexOf(h))return"×";if(-1!==[yp,bp].indexOf(l)&&(h===vp||-1!==[mp,cp].indexOf(h)&&t[a+1]===vp)||-1!==[mp,cp].indexOf(l)&&h===vp||l===vp&&-1!==[vp,xp,_p].indexOf(h))return"×";if(-1!==[vp,xp,_p,up,dp].indexOf(h))for(var c=o;c>=0;){if((u=t[c])===vp)return"×";if(-1===[xp,_p].indexOf(u))break;c--}if(-1!==[yp,bp].indexOf(h))for(c=-1!==[up,dp].indexOf(l)?n:o;c>=0;){var u;if((u=t[c])===vp)return"×";if(-1===[xp,_p].indexOf(u))break;c--}if(Fp===l&&-1!==[Fp,Ip,Cp,Mp].indexOf(h)||-1!==[Ip,Cp].indexOf(l)&&-1!==[Ip,Dp].indexOf(h)||-1!==[Dp,Mp].indexOf(l)&&h===Dp)return"×";if(-1!==Qp.indexOf(l)&&-1!==[fp,bp].indexOf(h)||-1!==Qp.indexOf(h)&&l===yp)return"×";if(-1!==Lp.indexOf(l)&&-1!==Lp.indexOf(h))return"×";if(l===_p&&-1!==Lp.indexOf(h))return"×";if(-1!==Lp.concat(vp).indexOf(l)&&h===mp&&-1===Tp.indexOf(e[a])||-1!==Lp.concat(vp).indexOf(h)&&l===dp)return"×";if(41===l&&41===h){for(var d=i[o],p=1;d>0&&41===t[--d];)p++;if(p%2!=0)return"×"}return l===wp&&h===Pp?"×":"÷"},zp=function(e,t){t||(t={lineBreak:"normal",wordBreak:"normal"});var i=function(e,t){void 0===t&&(t="strict");var i=[],s=[],r=[];return e.forEach((function(e,o){var n=Rp.get(e);if(n>50?(r.push(!0),n-=50):r.push(!1),-1!==["normal","auto","loose"].indexOf(t)&&-1!==[8208,8211,12316,12448].indexOf(e))return s.push(o),i.push(16);if(4===n||11===n){if(0===o)return s.push(o),i.push(Bp);var a=i[o-1];return-1===Np.indexOf(a)?(s.push(s[o-1]),i.push(a)):(s.push(o),i.push(Bp))}return s.push(o),31===n?i.push("strict"===t?gp:Ep):n===Sp||29===n?i.push(Bp):43===n?e>=131072&&e<=196605||e>=196608&&e<=262141?i.push(Ep):i.push(Bp):void i.push(n)})),[s,i,r]}(e,t.lineBreak),s=i[0],r=i[1],o=i[2];"break-all"!==t.wordBreak&&"break-word"!==t.wordBreak||(r=r.map((function(e){return-1!==[vp,Bp,Sp].indexOf(e)?Ep:e})));var n="keep-all"===t.wordBreak?o.map((function(t,i){return t&&e[i]>=19968&&e[i]<=40959})):void 0;return[s,r,n]},Wp=function(){function e(e,t,i,s){this.codePoints=e,this.required="!"===t,this.start=i,this.end=s}return e.prototype.slice=function(){return Zd.apply(void 0,this.codePoints.slice(this.start,this.end))},e}(),Kp=function(e){return e>=48&&e<=57},Xp=function(e){return Kp(e)||e>=65&&e<=70||e>=97&&e<=102},Jp=function(e){return 10===e||9===e||32===e},Yp=function(e){return function(e){return function(e){return e>=97&&e<=122}(e)||function(e){return e>=65&&e<=90}(e)}(e)||function(e){return e>=128}(e)||95===e},Zp=function(e){return Yp(e)||Kp(e)||45===e},qp=function(e){return e>=0&&e<=8||11===e||e>=14&&e<=31||127===e},$p=function(e,t){return 92===e&&10!==t},ef=function(e,t,i){return 45===e?Yp(t)||$p(t,i):!!Yp(e)||!(92!==e||!$p(e,t))},tf=function(e,t,i){return 43===e||45===e?!!Kp(t)||46===t&&Kp(i):Kp(46===e?t:e)},sf=function(e){var t=0,i=1;43!==e[t]&&45!==e[t]||(45===e[t]&&(i=-1),t++);for(var s=[];Kp(e[t]);)s.push(e[t++]);var r=s.length?parseInt(Zd.apply(void 0,s),10):0;46===e[t]&&t++;for(var o=[];Kp(e[t]);)o.push(e[t++]);var n=o.length,a=n?parseInt(Zd.apply(void 0,o),10):0;69!==e[t]&&101!==e[t]||t++;var l=1;43!==e[t]&&45!==e[t]||(45===e[t]&&(l=-1),t++);for(var A=[];Kp(e[t]);)A.push(e[t++]);var h=A.length?parseInt(Zd.apply(void 0,A),10):0;return i*(r+a*Math.pow(10,-n))*Math.pow(10,l*h)},rf={type:2},of={type:3},nf={type:4},af={type:13},lf={type:8},Af={type:21},hf={type:9},cf={type:10},uf={type:11},df={type:12},pf={type:14},ff={type:23},gf={type:1},mf={type:25},_f={type:24},vf={type:26},bf={type:27},yf={type:28},xf={type:29},Bf={type:31},wf={type:32},Pf=function(){function e(){this._value=[]}return e.prototype.write=function(e){this._value=this._value.concat(Yd(e))},e.prototype.read=function(){for(var e=[],t=this.consumeToken();t!==wf;)e.push(t),t=this.consumeToken();return e},e.prototype.consumeToken=function(){var e=this.consumeCodePoint();switch(e){case 34:return this.consumeStringToken(34);case 35:var t=this.peekCodePoint(0),i=this.peekCodePoint(1),s=this.peekCodePoint(2);if(Zp(t)||$p(i,s)){var r=ef(t,i,s)?2:1;return{type:5,value:this.consumeName(),flags:r}}break;case 36:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),af;break;case 39:return this.consumeStringToken(39);case 40:return rf;case 41:return of;case 42:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),pf;break;case 43:if(tf(e,this.peekCodePoint(0),this.peekCodePoint(1)))return this.reconsumeCodePoint(e),this.consumeNumericToken();break;case 44:return nf;case 45:var o=e,n=this.peekCodePoint(0),a=this.peekCodePoint(1);if(tf(o,n,a))return this.reconsumeCodePoint(e),this.consumeNumericToken();if(ef(o,n,a))return this.reconsumeCodePoint(e),this.consumeIdentLikeToken();if(45===n&&62===a)return this.consumeCodePoint(),this.consumeCodePoint(),_f;break;case 46:if(tf(e,this.peekCodePoint(0),this.peekCodePoint(1)))return this.reconsumeCodePoint(e),this.consumeNumericToken();break;case 47:if(42===this.peekCodePoint(0))for(this.consumeCodePoint();;){var l=this.consumeCodePoint();if(42===l&&47===(l=this.consumeCodePoint()))return this.consumeToken();if(-1===l)return this.consumeToken()}break;case 58:return vf;case 59:return bf;case 60:if(33===this.peekCodePoint(0)&&45===this.peekCodePoint(1)&&45===this.peekCodePoint(2))return this.consumeCodePoint(),this.consumeCodePoint(),mf;break;case 64:var A=this.peekCodePoint(0),h=this.peekCodePoint(1),c=this.peekCodePoint(2);if(ef(A,h,c))return{type:7,value:this.consumeName()};break;case 91:return yf;case 92:if($p(e,this.peekCodePoint(0)))return this.reconsumeCodePoint(e),this.consumeIdentLikeToken();break;case 93:return xf;case 61:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),lf;break;case 123:return uf;case 125:return df;case 117:case 85:var u=this.peekCodePoint(0),d=this.peekCodePoint(1);return 43!==u||!Xp(d)&&63!==d||(this.consumeCodePoint(),this.consumeUnicodeRangeToken()),this.reconsumeCodePoint(e),this.consumeIdentLikeToken();case 124:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),hf;if(124===this.peekCodePoint(0))return this.consumeCodePoint(),Af;break;case 126:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),cf;break;case-1:return wf}return Jp(e)?(this.consumeWhiteSpace(),Bf):Kp(e)?(this.reconsumeCodePoint(e),this.consumeNumericToken()):Yp(e)?(this.reconsumeCodePoint(e),this.consumeIdentLikeToken()):{type:6,value:Zd(e)}},e.prototype.consumeCodePoint=function(){var e=this._value.shift();return void 0===e?-1:e},e.prototype.reconsumeCodePoint=function(e){this._value.unshift(e)},e.prototype.peekCodePoint=function(e){return e>=this._value.length?-1:this._value[e]},e.prototype.consumeUnicodeRangeToken=function(){for(var e=[],t=this.consumeCodePoint();Xp(t)&&e.length<6;)e.push(t),t=this.consumeCodePoint();for(var i=!1;63===t&&e.length<6;)e.push(t),t=this.consumeCodePoint(),i=!0;if(i)return{type:30,start:parseInt(Zd.apply(void 0,e.map((function(e){return 63===e?48:e}))),16),end:parseInt(Zd.apply(void 0,e.map((function(e){return 63===e?70:e}))),16)};var s=parseInt(Zd.apply(void 0,e),16);if(45===this.peekCodePoint(0)&&Xp(this.peekCodePoint(1))){this.consumeCodePoint(),t=this.consumeCodePoint();for(var r=[];Xp(t)&&r.length<6;)r.push(t),t=this.consumeCodePoint();return{type:30,start:s,end:parseInt(Zd.apply(void 0,r),16)}}return{type:30,start:s,end:s}},e.prototype.consumeIdentLikeToken=function(){var e=this.consumeName();return"url"===e.toLowerCase()&&40===this.peekCodePoint(0)?(this.consumeCodePoint(),this.consumeUrlToken()):40===this.peekCodePoint(0)?(this.consumeCodePoint(),{type:19,value:e}):{type:20,value:e}},e.prototype.consumeUrlToken=function(){var e=[];if(this.consumeWhiteSpace(),-1===this.peekCodePoint(0))return{type:22,value:""};var t=this.peekCodePoint(0);if(39===t||34===t){var i=this.consumeStringToken(this.consumeCodePoint());return 0===i.type&&(this.consumeWhiteSpace(),-1===this.peekCodePoint(0)||41===this.peekCodePoint(0))?(this.consumeCodePoint(),{type:22,value:i.value}):(this.consumeBadUrlRemnants(),ff)}for(;;){var s=this.consumeCodePoint();if(-1===s||41===s)return{type:22,value:Zd.apply(void 0,e)};if(Jp(s))return this.consumeWhiteSpace(),-1===this.peekCodePoint(0)||41===this.peekCodePoint(0)?(this.consumeCodePoint(),{type:22,value:Zd.apply(void 0,e)}):(this.consumeBadUrlRemnants(),ff);if(34===s||39===s||40===s||qp(s))return this.consumeBadUrlRemnants(),ff;if(92===s){if(!$p(s,this.peekCodePoint(0)))return this.consumeBadUrlRemnants(),ff;e.push(this.consumeEscapedCodePoint())}else e.push(s)}},e.prototype.consumeWhiteSpace=function(){for(;Jp(this.peekCodePoint(0));)this.consumeCodePoint()},e.prototype.consumeBadUrlRemnants=function(){for(;;){var e=this.consumeCodePoint();if(41===e||-1===e)return;$p(e,this.peekCodePoint(0))&&this.consumeEscapedCodePoint()}},e.prototype.consumeStringSlice=function(e){for(var t="";e>0;){var i=Math.min(5e4,e);t+=Zd.apply(void 0,this._value.splice(0,i)),e-=i}return this._value.shift(),t},e.prototype.consumeStringToken=function(e){for(var t="",i=0;;){var s=this._value[i];if(-1===s||void 0===s||s===e)return{type:0,value:t+=this.consumeStringSlice(i)};if(10===s)return this._value.splice(0,i),gf;if(92===s){var r=this._value[i+1];-1!==r&&void 0!==r&&(10===r?(t+=this.consumeStringSlice(i),i=-1,this._value.shift()):$p(s,r)&&(t+=this.consumeStringSlice(i),t+=Zd(this.consumeEscapedCodePoint()),i=-1))}i++}},e.prototype.consumeNumber=function(){var e=[],t=4,i=this.peekCodePoint(0);for(43!==i&&45!==i||e.push(this.consumeCodePoint());Kp(this.peekCodePoint(0));)e.push(this.consumeCodePoint());i=this.peekCodePoint(0);var s=this.peekCodePoint(1);if(46===i&&Kp(s))for(e.push(this.consumeCodePoint(),this.consumeCodePoint()),t=8;Kp(this.peekCodePoint(0));)e.push(this.consumeCodePoint());i=this.peekCodePoint(0),s=this.peekCodePoint(1);var r=this.peekCodePoint(2);if((69===i||101===i)&&((43===s||45===s)&&Kp(r)||Kp(s)))for(e.push(this.consumeCodePoint(),this.consumeCodePoint()),t=8;Kp(this.peekCodePoint(0));)e.push(this.consumeCodePoint());return[sf(e),t]},e.prototype.consumeNumericToken=function(){var e=this.consumeNumber(),t=e[0],i=e[1],s=this.peekCodePoint(0),r=this.peekCodePoint(1),o=this.peekCodePoint(2);return ef(s,r,o)?{type:15,number:t,flags:i,unit:this.consumeName()}:37===s?(this.consumeCodePoint(),{type:16,number:t,flags:i}):{type:17,number:t,flags:i}},e.prototype.consumeEscapedCodePoint=function(){var e=this.consumeCodePoint();if(Xp(e)){for(var t=Zd(e);Xp(this.peekCodePoint(0))&&t.length<6;)t+=Zd(this.consumeCodePoint());Jp(this.peekCodePoint(0))&&this.consumeCodePoint();var i=parseInt(t,16);return 0===i||function(e){return e>=55296&&e<=57343}(i)||i>1114111?65533:i}return-1===e?65533:e},e.prototype.consumeName=function(){for(var e="";;){var t=this.consumeCodePoint();if(Zp(t))e+=Zd(t);else{if(!$p(t,this.peekCodePoint(0)))return this.reconsumeCodePoint(t),e;e+=Zd(this.consumeEscapedCodePoint())}}},e}(),Cf=function(){function e(e){this._tokens=e}return e.create=function(t){var i=new Pf;return i.write(t),new e(i.read())},e.parseValue=function(t){return e.create(t).parseComponentValue()},e.parseValues=function(t){return e.create(t).parseComponentValues()},e.prototype.parseComponentValue=function(){for(var e=this.consumeToken();31===e.type;)e=this.consumeToken();if(32===e.type)throw new SyntaxError("Error parsing CSS component value, unexpected EOF");this.reconsumeToken(e);var t=this.consumeComponentValue();do{e=this.consumeToken()}while(31===e.type);if(32===e.type)return t;throw new SyntaxError("Error parsing CSS component value, multiple values found when expecting only one")},e.prototype.parseComponentValues=function(){for(var e=[];;){var t=this.consumeComponentValue();if(32===t.type)return e;e.push(t),e.push()}},e.prototype.consumeComponentValue=function(){var e=this.consumeToken();switch(e.type){case 11:case 28:case 2:return this.consumeSimpleBlock(e.type);case 19:return this.consumeFunction(e)}return e},e.prototype.consumeSimpleBlock=function(e){for(var t={type:e,values:[]},i=this.consumeToken();;){if(32===i.type||Lf(i,e))return t;this.reconsumeToken(i),t.values.push(this.consumeComponentValue()),i=this.consumeToken()}},e.prototype.consumeFunction=function(e){for(var t={name:e.value,values:[],type:18};;){var i=this.consumeToken();if(32===i.type||3===i.type)return t;this.reconsumeToken(i),t.values.push(this.consumeComponentValue())}},e.prototype.consumeToken=function(){var e=this._tokens.shift();return void 0===e?wf:e},e.prototype.reconsumeToken=function(e){this._tokens.unshift(e)},e}(),Mf=function(e){return 15===e.type},Ef=function(e){return 17===e.type},Ff=function(e){return 20===e.type},If=function(e){return 0===e.type},Df=function(e,t){return Ff(e)&&e.value===t},Sf=function(e){return 31!==e.type},Tf=function(e){return 31!==e.type&&4!==e.type},Rf=function(e){var t=[],i=[];return e.forEach((function(e){if(4===e.type){if(0===i.length)throw new Error("Error parsing function args, zero tokens for arg");return t.push(i),void(i=[])}31!==e.type&&i.push(e)})),i.length&&t.push(i),t},Lf=function(e,t){return 11===t&&12===e.type||(28===t&&29===e.type||2===t&&3===e.type)},Uf=function(e){return 17===e.type||15===e.type},kf=function(e){return 16===e.type||Uf(e)},Of=function(e){return e.length>1?[e[0],e[1]]:[e[0]]},Nf={type:17,number:0,flags:4},Qf={type:16,number:50,flags:4},Vf={type:16,number:100,flags:4},Hf=function(e,t,i){var s=e[0],r=e[1];return[jf(s,t),jf(void 0!==r?r:s,i)]},jf=function(e,t){if(16===e.type)return e.number/100*t;if(Mf(e))switch(e.unit){case"rem":case"em":return 16*e.number;default:return e.number}return e.number},Gf=function(e,t){if(15===t.type)switch(t.unit){case"deg":return Math.PI*t.number/180;case"grad":return Math.PI/200*t.number;case"rad":return t.number;case"turn":return 2*Math.PI*t.number}throw new Error("Unsupported angle type")},zf=function(e){return 15===e.type&&("deg"===e.unit||"grad"===e.unit||"rad"===e.unit||"turn"===e.unit)},Wf=function(e){switch(e.filter(Ff).map((function(e){return e.value})).join(" ")){case"to bottom right":case"to right bottom":case"left top":case"top left":return[Nf,Nf];case"to top":case"bottom":return Kf(0);case"to bottom left":case"to left bottom":case"right top":case"top right":return[Nf,Vf];case"to right":case"left":return Kf(90);case"to top left":case"to left top":case"right bottom":case"bottom right":return[Vf,Vf];case"to bottom":case"top":return Kf(180);case"to top right":case"to right top":case"left bottom":case"bottom left":return[Vf,Nf];case"to left":case"right":return Kf(270)}return 0},Kf=function(e){return Math.PI*e/180},Xf=function(e,t){if(18===t.type){var i=ig[t.name];if(void 0===i)throw new Error('Attempting to parse an unsupported color function "'+t.name+'"');return i(e,t.values)}if(5===t.type){if(3===t.value.length){var s=t.value.substring(0,1),r=t.value.substring(1,2),o=t.value.substring(2,3);return Zf(parseInt(s+s,16),parseInt(r+r,16),parseInt(o+o,16),1)}if(4===t.value.length){s=t.value.substring(0,1),r=t.value.substring(1,2),o=t.value.substring(2,3);var n=t.value.substring(3,4);return Zf(parseInt(s+s,16),parseInt(r+r,16),parseInt(o+o,16),parseInt(n+n,16)/255)}if(6===t.value.length){s=t.value.substring(0,2),r=t.value.substring(2,4),o=t.value.substring(4,6);return Zf(parseInt(s,16),parseInt(r,16),parseInt(o,16),1)}if(8===t.value.length){s=t.value.substring(0,2),r=t.value.substring(2,4),o=t.value.substring(4,6),n=t.value.substring(6,8);return Zf(parseInt(s,16),parseInt(r,16),parseInt(o,16),parseInt(n,16)/255)}}if(20===t.type){var a=rg[t.value.toUpperCase()];if(void 0!==a)return a}return rg.TRANSPARENT},Jf=function(e){return 0==(255&e)},Yf=function(e){var t=255&e,i=255&e>>8,s=255&e>>16,r=255&e>>24;return t<255?"rgba("+r+","+s+","+i+","+t/255+")":"rgb("+r+","+s+","+i+")"},Zf=function(e,t,i,s){return(e<<24|t<<16|i<<8|Math.round(255*s)<<0)>>>0},qf=function(e,t){if(17===e.type)return e.number;if(16===e.type){var i=3===t?1:255;return 3===t?e.number/100*i:Math.round(e.number/100*i)}return 0},$f=function(e,t){var i=t.filter(Tf);if(3===i.length){var s=i.map(qf),r=s[0],o=s[1],n=s[2];return Zf(r,o,n,1)}if(4===i.length){var a=i.map(qf),l=(r=a[0],o=a[1],n=a[2],a[3]);return Zf(r,o,n,l)}return 0};function eg(e,t,i){return i<0&&(i+=1),i>=1&&(i-=1),i<1/6?(t-e)*i*6+e:i<.5?t:i<2/3?6*(t-e)*(2/3-i)+e:e}var tg=function(e,t){var i=t.filter(Tf),s=i[0],r=i[1],o=i[2],n=i[3],a=(17===s.type?Kf(s.number):Gf(e,s))/(2*Math.PI),l=kf(r)?r.number/100:0,A=kf(o)?o.number/100:0,h=void 0!==n&&kf(n)?jf(n,1):1;if(0===l)return Zf(255*A,255*A,255*A,1);var c=A<=.5?A*(l+1):A+l-A*l,u=2*A-c,d=eg(u,c,a+1/3),p=eg(u,c,a),f=eg(u,c,a-1/3);return Zf(255*d,255*p,255*f,h)},ig={hsl:tg,hsla:tg,rgb:$f,rgba:$f},sg=function(e,t){return Xf(e,Cf.create(t).parseComponentValue())},rg={ALICEBLUE:4042850303,ANTIQUEWHITE:4209760255,AQUA:16777215,AQUAMARINE:2147472639,AZURE:4043309055,BEIGE:4126530815,BISQUE:4293182719,BLACK:255,BLANCHEDALMOND:4293643775,BLUE:65535,BLUEVIOLET:2318131967,BROWN:2771004159,BURLYWOOD:3736635391,CADETBLUE:1604231423,CHARTREUSE:2147418367,CHOCOLATE:3530104575,CORAL:4286533887,CORNFLOWERBLUE:1687547391,CORNSILK:4294499583,CRIMSON:3692313855,CYAN:16777215,DARKBLUE:35839,DARKCYAN:9145343,DARKGOLDENROD:3095837695,DARKGRAY:2846468607,DARKGREEN:6553855,DARKGREY:2846468607,DARKKHAKI:3182914559,DARKMAGENTA:2332068863,DARKOLIVEGREEN:1433087999,DARKORANGE:4287365375,DARKORCHID:2570243327,DARKRED:2332033279,DARKSALMON:3918953215,DARKSEAGREEN:2411499519,DARKSLATEBLUE:1211993087,DARKSLATEGRAY:793726975,DARKSLATEGREY:793726975,DARKTURQUOISE:13554175,DARKVIOLET:2483082239,DEEPPINK:4279538687,DEEPSKYBLUE:12582911,DIMGRAY:1768516095,DIMGREY:1768516095,DODGERBLUE:512819199,FIREBRICK:2988581631,FLORALWHITE:4294635775,FORESTGREEN:579543807,FUCHSIA:4278255615,GAINSBORO:3705462015,GHOSTWHITE:4177068031,GOLD:4292280575,GOLDENROD:3668254975,GRAY:2155905279,GREEN:8388863,GREENYELLOW:2919182335,GREY:2155905279,HONEYDEW:4043305215,HOTPINK:4285117695,INDIANRED:3445382399,INDIGO:1258324735,IVORY:4294963455,KHAKI:4041641215,LAVENDER:3873897215,LAVENDERBLUSH:4293981695,LAWNGREEN:2096890111,LEMONCHIFFON:4294626815,LIGHTBLUE:2916673279,LIGHTCORAL:4034953471,LIGHTCYAN:3774873599,LIGHTGOLDENRODYELLOW:4210742015,LIGHTGRAY:3553874943,LIGHTGREEN:2431553791,LIGHTGREY:3553874943,LIGHTPINK:4290167295,LIGHTSALMON:4288707327,LIGHTSEAGREEN:548580095,LIGHTSKYBLUE:2278488831,LIGHTSLATEGRAY:2005441023,LIGHTSLATEGREY:2005441023,LIGHTSTEELBLUE:2965692159,LIGHTYELLOW:4294959359,LIME:16711935,LIMEGREEN:852308735,LINEN:4210091775,MAGENTA:4278255615,MAROON:2147483903,MEDIUMAQUAMARINE:1724754687,MEDIUMBLUE:52735,MEDIUMORCHID:3126187007,MEDIUMPURPLE:2473647103,MEDIUMSEAGREEN:1018393087,MEDIUMSLATEBLUE:2070474495,MEDIUMSPRINGGREEN:16423679,MEDIUMTURQUOISE:1221709055,MEDIUMVIOLETRED:3340076543,MIDNIGHTBLUE:421097727,MINTCREAM:4127193855,MISTYROSE:4293190143,MOCCASIN:4293178879,NAVAJOWHITE:4292783615,NAVY:33023,OLDLACE:4260751103,OLIVE:2155872511,OLIVEDRAB:1804477439,ORANGE:4289003775,ORANGERED:4282712319,ORCHID:3664828159,PALEGOLDENROD:4008225535,PALEGREEN:2566625535,PALETURQUOISE:2951671551,PALEVIOLETRED:3681588223,PAPAYAWHIP:4293907967,PEACHPUFF:4292524543,PERU:3448061951,PINK:4290825215,PLUM:3718307327,POWDERBLUE:2967529215,PURPLE:2147516671,REBECCAPURPLE:1714657791,RED:4278190335,ROSYBROWN:3163525119,ROYALBLUE:1097458175,SADDLEBROWN:2336560127,SALMON:4202722047,SANDYBROWN:4104413439,SEAGREEN:780883967,SEASHELL:4294307583,SIENNA:2689740287,SILVER:3233857791,SKYBLUE:2278484991,SLATEBLUE:1784335871,SLATEGRAY:1887473919,SLATEGREY:1887473919,SNOW:4294638335,SPRINGGREEN:16744447,STEELBLUE:1182971135,TAN:3535047935,TEAL:8421631,THISTLE:3636451583,TOMATO:4284696575,TRANSPARENT:0,TURQUOISE:1088475391,VIOLET:4001558271,WHEAT:4125012991,WHITE:4294967295,WHITESMOKE:4126537215,YELLOW:4294902015,YELLOWGREEN:2597139199},og={name:"background-clip",initialValue:"border-box",prefix:!1,type:1,parse:function(e,t){return t.map((function(e){if(Ff(e))switch(e.value){case"padding-box":return 1;case"content-box":return 2}return 0}))}},ng={name:"background-color",initialValue:"transparent",prefix:!1,type:3,format:"color"},ag=function(e,t){var i=Xf(e,t[0]),s=t[1];return s&&kf(s)?{color:i,stop:s}:{color:i,stop:null}},lg=function(e,t){var i=e[0],s=e[e.length-1];null===i.stop&&(i.stop=Nf),null===s.stop&&(s.stop=Vf);for(var r=[],o=0,n=0;no?r.push(l):r.push(o),o=l}else r.push(null)}var A=null;for(n=0;ne.optimumDistance)?{optimumCorner:t,optimumDistance:a}:e}),{optimumDistance:r?1/0:-1/0,optimumCorner:null}).optimumCorner},ug=function(e,t){var i=Kf(180),s=[];return Rf(t).forEach((function(t,r){if(0===r){var o=t[0];if(20===o.type&&-1!==["top","left","right","bottom"].indexOf(o.value))return void(i=Wf(t));if(zf(o))return void(i=(Gf(e,o)+Kf(270))%Kf(360))}var n=ag(e,t);s.push(n)})),{angle:i,stops:s,type:1}},dg=function(e,t){var i=0,s=3,r=[],o=[];return Rf(t).forEach((function(t,n){var a=!0;if(0===n?a=t.reduce((function(e,t){if(Ff(t))switch(t.value){case"center":return o.push(Qf),!1;case"top":case"left":return o.push(Nf),!1;case"right":case"bottom":return o.push(Vf),!1}else if(kf(t)||Uf(t))return o.push(t),!1;return e}),a):1===n&&(a=t.reduce((function(e,t){if(Ff(t))switch(t.value){case"circle":return i=0,!1;case"ellipse":return i=1,!1;case"contain":case"closest-side":return s=0,!1;case"farthest-side":return s=1,!1;case"closest-corner":return s=2,!1;case"cover":case"farthest-corner":return s=3,!1}else if(Uf(t)||kf(t))return Array.isArray(s)||(s=[]),s.push(t),!1;return e}),a)),a){var l=ag(e,t);r.push(l)}})),{size:s,shape:i,stops:r,position:o,type:2}},pg=function(e,t){if(22===t.type){var i={url:t.value,type:0};return e.cache.addImage(t.value),i}if(18===t.type){var s=gg[t.name];if(void 0===s)throw new Error('Attempting to parse an unsupported image function "'+t.name+'"');return s(e,t.values)}throw new Error("Unsupported image type "+t.type)};var fg,gg={"linear-gradient":function(e,t){var i=Kf(180),s=[];return Rf(t).forEach((function(t,r){if(0===r){var o=t[0];if(20===o.type&&"to"===o.value)return void(i=Wf(t));if(zf(o))return void(i=Gf(e,o))}var n=ag(e,t);s.push(n)})),{angle:i,stops:s,type:1}},"-moz-linear-gradient":ug,"-ms-linear-gradient":ug,"-o-linear-gradient":ug,"-webkit-linear-gradient":ug,"radial-gradient":function(e,t){var i=0,s=3,r=[],o=[];return Rf(t).forEach((function(t,n){var a=!0;if(0===n){var l=!1;a=t.reduce((function(e,t){if(l)if(Ff(t))switch(t.value){case"center":return o.push(Qf),e;case"top":case"left":return o.push(Nf),e;case"right":case"bottom":return o.push(Vf),e}else(kf(t)||Uf(t))&&o.push(t);else if(Ff(t))switch(t.value){case"circle":return i=0,!1;case"ellipse":return i=1,!1;case"at":return l=!0,!1;case"closest-side":return s=0,!1;case"cover":case"farthest-side":return s=1,!1;case"contain":case"closest-corner":return s=2,!1;case"farthest-corner":return s=3,!1}else if(Uf(t)||kf(t))return Array.isArray(s)||(s=[]),s.push(t),!1;return e}),a)}if(a){var A=ag(e,t);r.push(A)}})),{size:s,shape:i,stops:r,position:o,type:2}},"-moz-radial-gradient":dg,"-ms-radial-gradient":dg,"-o-radial-gradient":dg,"-webkit-radial-gradient":dg,"-webkit-gradient":function(e,t){var i=Kf(180),s=[],r=1;return Rf(t).forEach((function(t,i){var o=t[0];if(0===i){if(Ff(o)&&"linear"===o.value)return void(r=1);if(Ff(o)&&"radial"===o.value)return void(r=2)}if(18===o.type)if("from"===o.name){var n=Xf(e,o.values[0]);s.push({stop:Nf,color:n})}else if("to"===o.name){n=Xf(e,o.values[0]);s.push({stop:Vf,color:n})}else if("color-stop"===o.name){var a=o.values.filter(Tf);if(2===a.length){n=Xf(e,a[1]);var l=a[0];Ef(l)&&s.push({stop:{type:16,number:100*l.number,flags:l.flags},color:n})}}})),1===r?{angle:(i+Kf(180))%Kf(360),stops:s,type:r}:{size:3,shape:0,stops:s,position:[],type:r}}},mg={name:"background-image",initialValue:"none",type:1,prefix:!1,parse:function(e,t){if(0===t.length)return[];var i=t[0];return 20===i.type&&"none"===i.value?[]:t.filter((function(e){return Tf(e)&&function(e){return!(20===e.type&&"none"===e.value||18===e.type&&!gg[e.name])}(e)})).map((function(t){return pg(e,t)}))}},_g={name:"background-origin",initialValue:"border-box",prefix:!1,type:1,parse:function(e,t){return t.map((function(e){if(Ff(e))switch(e.value){case"padding-box":return 1;case"content-box":return 2}return 0}))}},vg={name:"background-position",initialValue:"0% 0%",type:1,prefix:!1,parse:function(e,t){return Rf(t).map((function(e){return e.filter(kf)})).map(Of)}},bg={name:"background-repeat",initialValue:"repeat",prefix:!1,type:1,parse:function(e,t){return Rf(t).map((function(e){return e.filter(Ff).map((function(e){return e.value})).join(" ")})).map(yg)}},yg=function(e){switch(e){case"no-repeat":return 1;case"repeat-x":case"repeat no-repeat":return 2;case"repeat-y":case"no-repeat repeat":return 3;default:return 0}};!function(e){e.AUTO="auto",e.CONTAIN="contain",e.COVER="cover"}(fg||(fg={}));var xg,Bg={name:"background-size",initialValue:"0",prefix:!1,type:1,parse:function(e,t){return Rf(t).map((function(e){return e.filter(wg)}))}},wg=function(e){return Ff(e)||kf(e)},Pg=function(e){return{name:"border-"+e+"-color",initialValue:"transparent",prefix:!1,type:3,format:"color"}},Cg=Pg("top"),Mg=Pg("right"),Eg=Pg("bottom"),Fg=Pg("left"),Ig=function(e){return{name:"border-radius-"+e,initialValue:"0 0",prefix:!1,type:1,parse:function(e,t){return Of(t.filter(kf))}}},Dg=Ig("top-left"),Sg=Ig("top-right"),Tg=Ig("bottom-right"),Rg=Ig("bottom-left"),Lg=function(e){return{name:"border-"+e+"-style",initialValue:"solid",prefix:!1,type:2,parse:function(e,t){switch(t){case"none":return 0;case"dashed":return 2;case"dotted":return 3;case"double":return 4}return 1}}},Ug=Lg("top"),kg=Lg("right"),Og=Lg("bottom"),Ng=Lg("left"),Qg=function(e){return{name:"border-"+e+"-width",initialValue:"0",type:0,prefix:!1,parse:function(e,t){return Mf(t)?t.number:0}}},Vg=Qg("top"),Hg=Qg("right"),jg=Qg("bottom"),Gg=Qg("left"),zg={name:"color",initialValue:"transparent",prefix:!1,type:3,format:"color"},Wg={name:"direction",initialValue:"ltr",prefix:!1,type:2,parse:function(e,t){return"rtl"===t?1:0}},Kg={name:"display",initialValue:"inline-block",prefix:!1,type:1,parse:function(e,t){return t.filter(Ff).reduce((function(e,t){return e|Xg(t.value)}),0)}},Xg=function(e){switch(e){case"block":case"-webkit-box":return 2;case"inline":return 4;case"run-in":return 8;case"flow":return 16;case"flow-root":return 32;case"table":return 64;case"flex":case"-webkit-flex":return 128;case"grid":case"-ms-grid":return 256;case"ruby":return 512;case"subgrid":return 1024;case"list-item":return 2048;case"table-row-group":return 4096;case"table-header-group":return 8192;case"table-footer-group":return 16384;case"table-row":return 32768;case"table-cell":return 65536;case"table-column-group":return 131072;case"table-column":return 262144;case"table-caption":return 524288;case"ruby-base":return 1048576;case"ruby-text":return 2097152;case"ruby-base-container":return 4194304;case"ruby-text-container":return 8388608;case"contents":return 16777216;case"inline-block":return 33554432;case"inline-list-item":return 67108864;case"inline-table":return 134217728;case"inline-flex":return 268435456;case"inline-grid":return 536870912}return 0},Jg={name:"float",initialValue:"none",prefix:!1,type:2,parse:function(e,t){switch(t){case"left":return 1;case"right":return 2;case"inline-start":return 3;case"inline-end":return 4}return 0}},Yg={name:"letter-spacing",initialValue:"0",prefix:!1,type:0,parse:function(e,t){return 20===t.type&&"normal"===t.value?0:17===t.type||15===t.type?t.number:0}};!function(e){e.NORMAL="normal",e.STRICT="strict"}(xg||(xg={}));var Zg,qg={name:"line-break",initialValue:"normal",prefix:!1,type:2,parse:function(e,t){return"strict"===t?xg.STRICT:xg.NORMAL}},$g={name:"line-height",initialValue:"normal",prefix:!1,type:4},em=function(e,t){return Ff(e)&&"normal"===e.value?1.2*t:17===e.type?t*e.number:kf(e)?jf(e,t):t},tm={name:"list-style-image",initialValue:"none",type:0,prefix:!1,parse:function(e,t){return 20===t.type&&"none"===t.value?null:pg(e,t)}},im={name:"list-style-position",initialValue:"outside",prefix:!1,type:2,parse:function(e,t){return"inside"===t?0:1}},sm={name:"list-style-type",initialValue:"none",prefix:!1,type:2,parse:function(e,t){switch(t){case"disc":return 0;case"circle":return 1;case"square":return 2;case"decimal":return 3;case"cjk-decimal":return 4;case"decimal-leading-zero":return 5;case"lower-roman":return 6;case"upper-roman":return 7;case"lower-greek":return 8;case"lower-alpha":return 9;case"upper-alpha":return 10;case"arabic-indic":return 11;case"armenian":return 12;case"bengali":return 13;case"cambodian":return 14;case"cjk-earthly-branch":return 15;case"cjk-heavenly-stem":return 16;case"cjk-ideographic":return 17;case"devanagari":return 18;case"ethiopic-numeric":return 19;case"georgian":return 20;case"gujarati":return 21;case"gurmukhi":case"hebrew":return 22;case"hiragana":return 23;case"hiragana-iroha":return 24;case"japanese-formal":return 25;case"japanese-informal":return 26;case"kannada":return 27;case"katakana":return 28;case"katakana-iroha":return 29;case"khmer":return 30;case"korean-hangul-formal":return 31;case"korean-hanja-formal":return 32;case"korean-hanja-informal":return 33;case"lao":return 34;case"lower-armenian":return 35;case"malayalam":return 36;case"mongolian":return 37;case"myanmar":return 38;case"oriya":return 39;case"persian":return 40;case"simp-chinese-formal":return 41;case"simp-chinese-informal":return 42;case"tamil":return 43;case"telugu":return 44;case"thai":return 45;case"tibetan":return 46;case"trad-chinese-formal":return 47;case"trad-chinese-informal":return 48;case"upper-armenian":return 49;case"disclosure-open":return 50;case"disclosure-closed":return 51;default:return-1}}},rm=function(e){return{name:"margin-"+e,initialValue:"0",prefix:!1,type:4}},om=rm("top"),nm=rm("right"),am=rm("bottom"),lm=rm("left"),Am={name:"overflow",initialValue:"visible",prefix:!1,type:1,parse:function(e,t){return t.filter(Ff).map((function(e){switch(e.value){case"hidden":return 1;case"scroll":return 2;case"clip":return 3;case"auto":return 4;default:return 0}}))}},hm={name:"overflow-wrap",initialValue:"normal",prefix:!1,type:2,parse:function(e,t){return"break-word"===t?"break-word":"normal"}},cm=function(e){return{name:"padding-"+e,initialValue:"0",prefix:!1,type:3,format:"length-percentage"}},um=cm("top"),dm=cm("right"),pm=cm("bottom"),fm=cm("left"),gm={name:"text-align",initialValue:"left",prefix:!1,type:2,parse:function(e,t){switch(t){case"right":return 2;case"center":case"justify":return 1;default:return 0}}},mm={name:"position",initialValue:"static",prefix:!1,type:2,parse:function(e,t){switch(t){case"relative":return 1;case"absolute":return 2;case"fixed":return 3;case"sticky":return 4}return 0}},_m={name:"text-shadow",initialValue:"none",type:1,prefix:!1,parse:function(e,t){return 1===t.length&&Df(t[0],"none")?[]:Rf(t).map((function(t){for(var i={color:rg.TRANSPARENT,offsetX:Nf,offsetY:Nf,blur:Nf},s=0,r=0;r1?1:0],this.overflowWrap=Zm(e,hm,t.overflowWrap),this.paddingTop=Zm(e,um,t.paddingTop),this.paddingRight=Zm(e,dm,t.paddingRight),this.paddingBottom=Zm(e,pm,t.paddingBottom),this.paddingLeft=Zm(e,fm,t.paddingLeft),this.paintOrder=Zm(e,zm,t.paintOrder),this.position=Zm(e,mm,t.position),this.textAlign=Zm(e,gm,t.textAlign),this.textDecorationColor=Zm(e,Im,null!==(i=t.textDecorationColor)&&void 0!==i?i:t.color),this.textDecorationLine=Zm(e,Dm,null!==(s=t.textDecorationLine)&&void 0!==s?s:t.textDecoration),this.textShadow=Zm(e,_m,t.textShadow),this.textTransform=Zm(e,vm,t.textTransform),this.transform=Zm(e,bm,t.transform),this.transformOrigin=Zm(e,wm,t.transformOrigin),this.visibility=Zm(e,Pm,t.visibility),this.webkitTextStrokeColor=Zm(e,Wm,t.webkitTextStrokeColor),this.webkitTextStrokeWidth=Zm(e,Km,t.webkitTextStrokeWidth),this.wordBreak=Zm(e,Cm,t.wordBreak),this.zIndex=Zm(e,Mm,t.zIndex)}return e.prototype.isVisible=function(){return this.display>0&&this.opacity>0&&0===this.visibility},e.prototype.isTransparent=function(){return Jf(this.backgroundColor)},e.prototype.isTransformed=function(){return null!==this.transform},e.prototype.isPositioned=function(){return 0!==this.position},e.prototype.isPositionedWithZIndex=function(){return this.isPositioned()&&!this.zIndex.auto},e.prototype.isFloating=function(){return 0!==this.float},e.prototype.isInlineLevel=function(){return km(this.display,4)||km(this.display,33554432)||km(this.display,268435456)||km(this.display,536870912)||km(this.display,67108864)||km(this.display,134217728)},e}(),Jm=function(e,t){this.content=Zm(e,Om,t.content),this.quotes=Zm(e,Hm,t.quotes)},Ym=function(e,t){this.counterIncrement=Zm(e,Nm,t.counterIncrement),this.counterReset=Zm(e,Qm,t.counterReset)},Zm=function(e,t,i){var s=new Pf,r=null!=i?i.toString():t.initialValue;s.write(r);var o=new Cf(s.read());switch(t.type){case 2:var n=o.parseComponentValue();return t.parse(e,Ff(n)?n.value:t.initialValue);case 0:return t.parse(e,o.parseComponentValue());case 1:return t.parse(e,o.parseComponentValues());case 4:return o.parseComponentValue();case 3:switch(t.format){case"angle":return Gf(e,o.parseComponentValue());case"color":return Xf(e,o.parseComponentValue());case"image":return pg(e,o.parseComponentValue());case"length":var a=o.parseComponentValue();return Uf(a)?a:Nf;case"length-percentage":var l=o.parseComponentValue();return kf(l)?l:Nf;case"time":return Em(e,o.parseComponentValue())}}},qm=function(e,t){var i=function(e){switch(e.getAttribute("data-html2canvas-debug")){case"all":return 1;case"clone":return 2;case"parse":return 3;case"render":return 4;default:return 0}}(e);return 1===i||t===i},$m=function(e,t){this.context=e,this.textNodes=[],this.elements=[],this.flags=0,qm(t,3),this.styles=new Xm(e,window.getComputedStyle(t,null)),$_(t)&&(this.styles.animationDuration.some((function(e){return e>0}))&&(t.style.animationDuration="0s"),null!==this.styles.transform&&(t.style.transform="none")),this.bounds=Jd(this.context,t),qm(t,4)&&(this.flags|=16)},e_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t_="undefined"==typeof Uint8Array?[]:new Uint8Array(256),i_=0;i_=0){if(e<55296||e>56319&&e<=65535)return t=((t=this.index[e>>5])<<2)+(31&e),this.data[t];if(e<=65535)return t=((t=this.index[2048+(e-55296>>5)])<<2)+(31&e),this.data[t];if(e>11),t=this.index[t],t+=e>>5&63,t=((t=this.index[t])<<2)+(31&e),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},e}(),o_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n_="undefined"==typeof Uint8Array?[]:new Uint8Array(256),a_=0;a_>10),n%1024+56320)),(r+1===i||s.length>16384)&&(o+=String.fromCharCode.apply(String,s),s.length=0)}return o},p_=function(e,t){var i,s,r,o=function(e){var t,i,s,r,o,n=.75*e.length,a=e.length,l=0;"="===e[e.length-1]&&(n--,"="===e[e.length-2]&&n--);var A="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&void 0!==Uint8Array.prototype.slice?new ArrayBuffer(n):new Array(n),h=Array.isArray(A)?A:new Uint8Array(A);for(t=0;t>4,h[l++]=(15&s)<<4|r>>2,h[l++]=(3&r)<<6|63&o;return A}(e),n=Array.isArray(o)?function(e){for(var t=e.length,i=[],s=0;s=55296&&r<=56319&&i=i)return{done:!0,value:null};for(var e="×";sn.x||r.y>n.y;return n=r,0===t||a}));return e.body.removeChild(t),a}(document);return Object.defineProperty(y_,"SUPPORT_WORD_BREAKING",{value:e}),e},get SUPPORT_SVG_DRAWING(){var e=function(e){var t=new Image,i=e.createElement("canvas"),s=i.getContext("2d");if(!s)return!1;t.src="data:image/svg+xml,";try{s.drawImage(t,0,0),i.toDataURL()}catch(e){return!1}return!0}(document);return Object.defineProperty(y_,"SUPPORT_SVG_DRAWING",{value:e}),e},get SUPPORT_FOREIGNOBJECT_DRAWING(){var e="function"==typeof Array.from&&"function"==typeof window.fetch?function(e){var t=e.createElement("canvas"),i=100;t.width=i,t.height=i;var s=t.getContext("2d");if(!s)return Promise.reject(!1);s.fillStyle="rgb(0, 255, 0)",s.fillRect(0,0,i,i);var r=new Image,o=t.toDataURL();r.src=o;var n=v_(i,i,0,0,r);return s.fillStyle="red",s.fillRect(0,0,i,i),b_(n).then((function(t){s.drawImage(t,0,0);var r=s.getImageData(0,0,i,i).data;s.fillStyle="red",s.fillRect(0,0,i,i);var n=e.createElement("div");return n.style.backgroundImage="url("+o+")",n.style.height="100px",__(r)?b_(v_(i,i,0,0,n)):Promise.reject(!1)})).then((function(e){return s.drawImage(e,0,0),__(s.getImageData(0,0,i,i).data)})).catch((function(){return!1}))}(document):Promise.resolve(!1);return Object.defineProperty(y_,"SUPPORT_FOREIGNOBJECT_DRAWING",{value:e}),e},get SUPPORT_CORS_IMAGES(){var e=void 0!==(new Image).crossOrigin;return Object.defineProperty(y_,"SUPPORT_CORS_IMAGES",{value:e}),e},get SUPPORT_RESPONSE_TYPE(){var e="string"==typeof(new XMLHttpRequest).responseType;return Object.defineProperty(y_,"SUPPORT_RESPONSE_TYPE",{value:e}),e},get SUPPORT_CORS_XHR(){var e="withCredentials"in new XMLHttpRequest;return Object.defineProperty(y_,"SUPPORT_CORS_XHR",{value:e}),e},get SUPPORT_NATIVE_TEXT_SEGMENTATION(){var e=!("undefined"==typeof Intl||!Intl.Segmenter);return Object.defineProperty(y_,"SUPPORT_NATIVE_TEXT_SEGMENTATION",{value:e}),e}},x_=function(e,t){this.text=e,this.bounds=t},B_=function(e,t){var i=t.ownerDocument;if(i){var s=i.createElement("html2canvaswrapper");s.appendChild(t.cloneNode(!0));var r=t.parentNode;if(r){r.replaceChild(s,t);var o=Jd(e,s);return s.firstChild&&r.replaceChild(s.firstChild,s),o}}return Xd.EMPTY},w_=function(e,t,i){var s=e.ownerDocument;if(!s)throw new Error("Node has no owner document");var r=s.createRange();return r.setStart(e,t),r.setEnd(e,t+i),r},P_=function(e){if(y_.SUPPORT_NATIVE_TEXT_SEGMENTATION){var t=new Intl.Segmenter(void 0,{granularity:"grapheme"});return Array.from(t.segment(e)).map((function(e){return e.segment}))}return function(e){for(var t,i=m_(e),s=[];!(t=i.next()).done;)t.value&&s.push(t.value.slice());return s}(e)},C_=function(e,t){return 0!==t.letterSpacing?P_(e):function(e,t){if(y_.SUPPORT_NATIVE_TEXT_SEGMENTATION){var i=new Intl.Segmenter(void 0,{granularity:"word"});return Array.from(i.segment(e)).map((function(e){return e.segment}))}return E_(e,t)}(e,t)},M_=[32,160,4961,65792,65793,4153,4241],E_=function(e,t){for(var i,s=function(e,t){var i=Yd(e),s=zp(i,t),r=s[0],o=s[1],n=s[2],a=i.length,l=0,A=0;return{next:function(){if(A>=a)return{done:!0,value:null};for(var e="×";A0)if(y_.SUPPORT_RANGE_BOUNDS){var r=w_(s,n,t.length).getClientRects();if(r.length>1){var a=P_(t),l=0;a.forEach((function(t){o.push(new x_(t,Xd.fromDOMRectList(e,w_(s,l+n,t.length).getClientRects()))),l+=t.length}))}else o.push(new x_(t,Xd.fromDOMRectList(e,r)))}else{var A=s.splitText(t.length);o.push(new x_(t,B_(e,s))),s=A}else y_.SUPPORT_RANGE_BOUNDS||(s=s.splitText(t.length));n+=t.length})),o}(e,this.text,i,t)},I_=function(e,t){switch(t){case 1:return e.toLowerCase();case 3:return e.replace(D_,S_);case 2:return e.toUpperCase();default:return e}},D_=/(^|\s|:|-|\(|\))([a-z])/g,S_=function(e,t,i){return e.length>0?t+i.toUpperCase():e},T_=function(e){function t(t,i){var s=e.call(this,t,i)||this;return s.src=i.currentSrc||i.src,s.intrinsicWidth=i.naturalWidth,s.intrinsicHeight=i.naturalHeight,s.context.cache.addImage(s.src),s}return jd(t,e),t}($m),R_=function(e){function t(t,i){var s=e.call(this,t,i)||this;return s.canvas=i,s.intrinsicWidth=i.width,s.intrinsicHeight=i.height,s}return jd(t,e),t}($m),L_=function(e){function t(t,i){var s=e.call(this,t,i)||this,r=new XMLSerializer,o=Jd(t,i);return i.setAttribute("width",o.width+"px"),i.setAttribute("height",o.height+"px"),s.svg="data:image/svg+xml,"+encodeURIComponent(r.serializeToString(i)),s.intrinsicWidth=i.width.baseVal.value,s.intrinsicHeight=i.height.baseVal.value,s.context.cache.addImage(s.svg),s}return jd(t,e),t}($m),U_=function(e){function t(t,i){var s=e.call(this,t,i)||this;return s.value=i.value,s}return jd(t,e),t}($m),k_=function(e){function t(t,i){var s=e.call(this,t,i)||this;return s.start=i.start,s.reversed="boolean"==typeof i.reversed&&!0===i.reversed,s}return jd(t,e),t}($m),O_=[{type:15,flags:0,unit:"px",number:3}],N_=[{type:16,flags:0,number:50}],Q_="password",V_=function(e){function t(t,i){var s,r=e.call(this,t,i)||this;switch(r.type=i.type.toLowerCase(),r.checked=i.checked,r.value=function(e){var t=e.type===Q_?new Array(e.value.length+1).join("•"):e.value;return 0===t.length?e.placeholder||"":t}(i),"checkbox"!==r.type&&"radio"!==r.type||(r.styles.backgroundColor=3739148031,r.styles.borderTopColor=r.styles.borderRightColor=r.styles.borderBottomColor=r.styles.borderLeftColor=2779096575,r.styles.borderTopWidth=r.styles.borderRightWidth=r.styles.borderBottomWidth=r.styles.borderLeftWidth=1,r.styles.borderTopStyle=r.styles.borderRightStyle=r.styles.borderBottomStyle=r.styles.borderLeftStyle=1,r.styles.backgroundClip=[0],r.styles.backgroundOrigin=[0],r.bounds=(s=r.bounds).width>s.height?new Xd(s.left+(s.width-s.height)/2,s.top,s.height,s.height):s.width0)i.textNodes.push(new F_(e,r,i.styles));else if(q_(r))if(dv(r)&&r.assignedNodes)r.assignedNodes().forEach((function(t){return W_(e,t,i,s)}));else{var n=K_(e,r);n.styles.isVisible()&&(J_(r,n,s)?n.flags|=4:Y_(n.styles)&&(n.flags|=2),-1!==z_.indexOf(r.tagName)&&(n.flags|=8),i.elements.push(n),r.slot,r.shadowRoot?W_(e,r.shadowRoot,n,s):cv(r)||rv(r)||uv(r)||W_(e,r,n,s))}},K_=function(e,t){return lv(t)?new T_(e,t):nv(t)?new R_(e,t):rv(t)?new L_(e,t):tv(t)?new U_(e,t):iv(t)?new k_(e,t):sv(t)?new V_(e,t):uv(t)?new H_(e,t):cv(t)?new j_(e,t):Av(t)?new G_(e,t):new $m(e,t)},X_=function(e,t){var i=K_(e,t);return i.flags|=4,W_(e,t,i,i),i},J_=function(e,t,i){return t.styles.isPositionedWithZIndex()||t.styles.opacity<1||t.styles.isTransformed()||ov(e)&&i.styles.isTransparent()},Y_=function(e){return e.isPositioned()||e.isFloating()},Z_=function(e){return e.nodeType===Node.TEXT_NODE},q_=function(e){return e.nodeType===Node.ELEMENT_NODE},$_=function(e){return q_(e)&&void 0!==e.style&&!ev(e)},ev=function(e){return"object"==typeof e.className},tv=function(e){return"LI"===e.tagName},iv=function(e){return"OL"===e.tagName},sv=function(e){return"INPUT"===e.tagName},rv=function(e){return"svg"===e.tagName},ov=function(e){return"BODY"===e.tagName},nv=function(e){return"CANVAS"===e.tagName},av=function(e){return"VIDEO"===e.tagName},lv=function(e){return"IMG"===e.tagName},Av=function(e){return"IFRAME"===e.tagName},hv=function(e){return"STYLE"===e.tagName},cv=function(e){return"TEXTAREA"===e.tagName},uv=function(e){return"SELECT"===e.tagName},dv=function(e){return"SLOT"===e.tagName},pv=function(e){return e.tagName.indexOf("-")>0},fv=function(){function e(){this.counters={}}return e.prototype.getCounterValue=function(e){var t=this.counters[e];return t&&t.length?t[t.length-1]:1},e.prototype.getCounterValues=function(e){var t=this.counters[e];return t||[]},e.prototype.pop=function(e){var t=this;e.forEach((function(e){return t.counters[e].pop()}))},e.prototype.parse=function(e){var t=this,i=e.counterIncrement,s=e.counterReset,r=!0;null!==i&&i.forEach((function(e){var i=t.counters[e.counter];i&&0!==e.increment&&(r=!1,i.length||i.push(1),i[Math.max(0,i.length-1)]+=e.increment)}));var o=[];return r&&s.forEach((function(e){var i=t.counters[e.counter];o.push(e.counter),i||(i=t.counters[e.counter]=[]),i.push(e.reset)})),o},e}(),gv={integers:[1e3,900,500,400,100,90,50,40,10,9,5,4,1],values:["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]},mv={integers:[9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],values:["Ք","Փ","Ւ","Ց","Ր","Տ","Վ","Ս","Ռ","Ջ","Պ","Չ","Ո","Շ","Ն","Յ","Մ","Ճ","Ղ","Ձ","Հ","Կ","Ծ","Խ","Լ","Ի","Ժ","Թ","Ը","Է","Զ","Ե","Դ","Գ","Բ","Ա"]},_v={integers:[1e4,9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,400,300,200,100,90,80,70,60,50,40,30,20,19,18,17,16,15,10,9,8,7,6,5,4,3,2,1],values:["י׳","ט׳","ח׳","ז׳","ו׳","ה׳","ד׳","ג׳","ב׳","א׳","ת","ש","ר","ק","צ","פ","ע","ס","נ","מ","ל","כ","יט","יח","יז","טז","טו","י","ט","ח","ז","ו","ה","ד","ג","ב","א"]},vv={integers:[1e4,9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],values:["ჵ","ჰ","ჯ","ჴ","ხ","ჭ","წ","ძ","ც","ჩ","შ","ყ","ღ","ქ","ფ","ჳ","ტ","ს","რ","ჟ","პ","ო","ჲ","ნ","მ","ლ","კ","ი","თ","ჱ","ზ","ვ","ე","დ","გ","ბ","ა"]},bv=function(e,t,i,s,r,o){return ei?Pv(e,r,o.length>0):s.integers.reduce((function(t,i,r){for(;e>=i;)e-=i,t+=s.values[r];return t}),"")+o},yv=function(e,t,i,s){var r="";do{i||e--,r=s(e)+r,e/=t}while(e*t>=t);return r},xv=function(e,t,i,s,r){var o=i-t+1;return(e<0?"-":"")+(yv(Math.abs(e),o,s,(function(e){return Zd(Math.floor(e%o)+t)}))+r)},Bv=function(e,t,i){void 0===i&&(i=". ");var s=t.length;return yv(Math.abs(e),s,!1,(function(e){return t[Math.floor(e%s)]}))+i},wv=function(e,t,i,s,r,o){if(e<-9999||e>9999)return Pv(e,4,r.length>0);var n=Math.abs(e),a=r;if(0===n)return t[0]+a;for(var l=0;n>0&&l<=4;l++){var A=n%10;0===A&&km(o,1)&&""!==a?a=t[A]+a:A>1||1===A&&0===l||1===A&&1===l&&km(o,2)||1===A&&1===l&&km(o,4)&&e>100||1===A&&l>1&&km(o,8)?a=t[A]+(l>0?i[l-1]:"")+a:1===A&&l>0&&(a=i[l-1]+a),n=Math.floor(n/10)}return(e<0?s:"")+a},Pv=function(e,t,i){var s=i?". ":"",r=i?"、":"",o=i?", ":"",n=i?" ":"";switch(t){case 0:return"•"+n;case 1:return"◦"+n;case 2:return"◾"+n;case 5:var a=xv(e,48,57,!0,s);return a.length<4?"0"+a:a;case 4:return Bv(e,"〇一二三四五六七八九",r);case 6:return bv(e,1,3999,gv,3,s).toLowerCase();case 7:return bv(e,1,3999,gv,3,s);case 8:return xv(e,945,969,!1,s);case 9:return xv(e,97,122,!1,s);case 10:return xv(e,65,90,!1,s);case 11:return xv(e,1632,1641,!0,s);case 12:case 49:return bv(e,1,9999,mv,3,s);case 35:return bv(e,1,9999,mv,3,s).toLowerCase();case 13:return xv(e,2534,2543,!0,s);case 14:case 30:return xv(e,6112,6121,!0,s);case 15:return Bv(e,"子丑寅卯辰巳午未申酉戌亥",r);case 16:return Bv(e,"甲乙丙丁戊己庚辛壬癸",r);case 17:case 48:return wv(e,"零一二三四五六七八九","十百千萬","負",r,14);case 47:return wv(e,"零壹貳參肆伍陸柒捌玖","拾佰仟萬","負",r,15);case 42:return wv(e,"零一二三四五六七八九","十百千萬","负",r,14);case 41:return wv(e,"零壹贰叁肆伍陆柒捌玖","拾佰仟萬","负",r,15);case 26:return wv(e,"〇一二三四五六七八九","十百千万","マイナス",r,0);case 25:return wv(e,"零壱弐参四伍六七八九","拾百千万","マイナス",r,7);case 31:return wv(e,"영일이삼사오육칠팔구","십백천만","마이너스",o,7);case 33:return wv(e,"零一二三四五六七八九","十百千萬","마이너스",o,0);case 32:return wv(e,"零壹貳參四五六七八九","拾百千","마이너스",o,7);case 18:return xv(e,2406,2415,!0,s);case 20:return bv(e,1,19999,vv,3,s);case 21:return xv(e,2790,2799,!0,s);case 22:return xv(e,2662,2671,!0,s);case 22:return bv(e,1,10999,_v,3,s);case 23:return Bv(e,"あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわゐゑをん");case 24:return Bv(e,"いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす");case 27:return xv(e,3302,3311,!0,s);case 28:return Bv(e,"アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヰヱヲン",r);case 29:return Bv(e,"イロハニホヘトチリヌルヲワカヨタレソツネナラムウヰノオクヤマケフコエテアサキユメミシヱヒモセス",r);case 34:return xv(e,3792,3801,!0,s);case 37:return xv(e,6160,6169,!0,s);case 38:return xv(e,4160,4169,!0,s);case 39:return xv(e,2918,2927,!0,s);case 40:return xv(e,1776,1785,!0,s);case 43:return xv(e,3046,3055,!0,s);case 44:return xv(e,3174,3183,!0,s);case 45:return xv(e,3664,3673,!0,s);case 46:return xv(e,3872,3881,!0,s);default:return xv(e,48,57,!0,s)}},Cv=function(){function e(e,t,i){if(this.context=e,this.options=i,this.scrolledElements=[],this.referenceElement=t,this.counters=new fv,this.quoteDepth=0,!t.ownerDocument)throw new Error("Cloned element does not have an owner document");this.documentElement=this.cloneNode(t.ownerDocument.documentElement,!1)}return e.prototype.toIFrame=function(e,t){var i=this,s=Ev(e,t);if(!s.contentWindow)return Promise.reject("Unable to find iframe window");var r=e.defaultView.pageXOffset,o=e.defaultView.pageYOffset,n=s.contentWindow,a=n.document,l=Dv(s).then((function(){return zd(i,void 0,void 0,(function(){var e,i;return Wd(this,(function(r){switch(r.label){case 0:return this.scrolledElements.forEach(Uv),n&&(n.scrollTo(t.left,t.top),!/(iPad|iPhone|iPod)/g.test(navigator.userAgent)||n.scrollY===t.top&&n.scrollX===t.left||(this.context.logger.warn("Unable to restore scroll position for cloned document"),this.context.windowBounds=this.context.windowBounds.add(n.scrollX-t.left,n.scrollY-t.top,0,0))),e=this.options.onclone,void 0===(i=this.clonedReferenceElement)?[2,Promise.reject("Error finding the "+this.referenceElement.nodeName+" in the cloned document")]:a.fonts&&a.fonts.ready?[4,a.fonts.ready]:[3,2];case 1:r.sent(),r.label=2;case 2:return/(AppleWebKit)/g.test(navigator.userAgent)?[4,Iv(a)]:[3,4];case 3:r.sent(),r.label=4;case 4:return"function"==typeof e?[2,Promise.resolve().then((function(){return e(a,i)})).then((function(){return s}))]:[2,s]}}))}))}));return a.open(),a.write(Rv(document.doctype)+""),Lv(this.referenceElement.ownerDocument,r,o),a.replaceChild(a.adoptNode(this.documentElement),a.documentElement),a.close(),l},e.prototype.createElementClone=function(e){if(qm(e,2),nv(e))return this.createCanvasClone(e);if(av(e))return this.createVideoClone(e);if(hv(e))return this.createStyleClone(e);var t=e.cloneNode(!1);return lv(t)&&(lv(e)&&e.currentSrc&&e.currentSrc!==e.src&&(t.src=e.currentSrc,t.srcset=""),"lazy"===t.loading&&(t.loading="eager")),pv(t)?this.createCustomElementClone(t):t},e.prototype.createCustomElementClone=function(e){var t=document.createElement("html2canvascustomelement");return Tv(e.style,t),t},e.prototype.createStyleClone=function(e){try{var t=e.sheet;if(t&&t.cssRules){var i=[].slice.call(t.cssRules,0).reduce((function(e,t){return t&&"string"==typeof t.cssText?e+t.cssText:e}),""),s=e.cloneNode(!1);return s.textContent=i,s}}catch(e){if(this.context.logger.error("Unable to access cssRules property",e),"SecurityError"!==e.name)throw e}return e.cloneNode(!1)},e.prototype.createCanvasClone=function(e){var t;if(this.options.inlineImages&&e.ownerDocument){var i=e.ownerDocument.createElement("img");try{return i.src=e.toDataURL(),i}catch(t){this.context.logger.info("Unable to inline canvas contents, canvas is tainted",e)}}var s=e.cloneNode(!1);try{s.width=e.width,s.height=e.height;var r=e.getContext("2d"),o=s.getContext("2d");if(o)if(!this.options.allowTaint&&r)o.putImageData(r.getImageData(0,0,e.width,e.height),0,0);else{var n=null!==(t=e.getContext("webgl2"))&&void 0!==t?t:e.getContext("webgl");if(n){var a=n.getContextAttributes();!1===(null==a?void 0:a.preserveDrawingBuffer)&&this.context.logger.warn("Unable to clone WebGL context as it has preserveDrawingBuffer=false",e)}o.drawImage(e,0,0)}return s}catch(t){this.context.logger.info("Unable to clone canvas as it is tainted",e)}return s},e.prototype.createVideoClone=function(e){var t=e.ownerDocument.createElement("canvas");t.width=e.offsetWidth,t.height=e.offsetHeight;var i=t.getContext("2d");try{return i&&(i.drawImage(e,0,0,t.width,t.height),this.options.allowTaint||i.getImageData(0,0,t.width,t.height)),t}catch(t){this.context.logger.info("Unable to clone video as it is tainted",e)}var s=e.ownerDocument.createElement("canvas");return s.width=e.offsetWidth,s.height=e.offsetHeight,s},e.prototype.appendChildNode=function(e,t,i){q_(t)&&(function(e){return"SCRIPT"===e.tagName}(t)||t.hasAttribute("data-html2canvas-ignore")||"function"==typeof this.options.ignoreElements&&this.options.ignoreElements(t))||this.options.copyStyles&&q_(t)&&hv(t)||e.appendChild(this.cloneNode(t,i))},e.prototype.cloneChildNodes=function(e,t,i){for(var s=this,r=e.shadowRoot?e.shadowRoot.firstChild:e.firstChild;r;r=r.nextSibling)if(q_(r)&&dv(r)&&"function"==typeof r.assignedNodes){var o=r.assignedNodes();o.length&&o.forEach((function(e){return s.appendChildNode(t,e,i)}))}else this.appendChildNode(t,r,i)},e.prototype.cloneNode=function(e,t){if(Z_(e))return document.createTextNode(e.data);if(!e.ownerDocument)return e.cloneNode(!1);var i=e.ownerDocument.defaultView;if(i&&q_(e)&&($_(e)||ev(e))){var s=this.createElementClone(e);s.style.transitionProperty="none";var r=i.getComputedStyle(e),o=i.getComputedStyle(e,":before"),n=i.getComputedStyle(e,":after");this.referenceElement===e&&$_(s)&&(this.clonedReferenceElement=s),ov(s)&&Nv(s);var a=this.counters.parse(new Ym(this.context,r)),l=this.resolvePseudoContent(e,s,o,l_.BEFORE);pv(e)&&(t=!0),av(e)||this.cloneChildNodes(e,s,t),l&&s.insertBefore(l,s.firstChild);var A=this.resolvePseudoContent(e,s,n,l_.AFTER);return A&&s.appendChild(A),this.counters.pop(a),(r&&(this.options.copyStyles||ev(e))&&!Av(e)||t)&&Tv(r,s),0===e.scrollTop&&0===e.scrollLeft||this.scrolledElements.push([s,e.scrollLeft,e.scrollTop]),(cv(e)||uv(e))&&(cv(s)||uv(s))&&(s.value=e.value),s}return e.cloneNode(!1)},e.prototype.resolvePseudoContent=function(e,t,i,s){var r=this;if(i){var o=i.content,n=t.ownerDocument;if(n&&o&&"none"!==o&&"-moz-alt-content"!==o&&"none"!==i.display){this.counters.parse(new Ym(this.context,i));var a=new Jm(this.context,i),l=n.createElement("html2canvaspseudoelement");Tv(i,l),a.content.forEach((function(t){if(0===t.type)l.appendChild(n.createTextNode(t.value));else if(22===t.type){var i=n.createElement("img");i.src=t.value,i.style.opacity="1",l.appendChild(i)}else if(18===t.type){if("attr"===t.name){var s=t.values.filter(Ff);s.length&&l.appendChild(n.createTextNode(e.getAttribute(s[0].value)||""))}else if("counter"===t.name){var o=t.values.filter(Tf),A=o[0],h=o[1];if(A&&Ff(A)){var c=r.counters.getCounterValue(A.value),u=h&&Ff(h)?sm.parse(r.context,h.value):3;l.appendChild(n.createTextNode(Pv(c,u,!1)))}}else if("counters"===t.name){var d=t.values.filter(Tf),p=(A=d[0],d[1]);h=d[2];if(A&&Ff(A)){var f=r.counters.getCounterValues(A.value),g=h&&Ff(h)?sm.parse(r.context,h.value):3,m=p&&0===p.type?p.value:"",_=f.map((function(e){return Pv(e,g,!1)})).join(m);l.appendChild(n.createTextNode(_))}}}else if(20===t.type)switch(t.value){case"open-quote":l.appendChild(n.createTextNode(jm(a.quotes,r.quoteDepth++,!0)));break;case"close-quote":l.appendChild(n.createTextNode(jm(a.quotes,--r.quoteDepth,!1)));break;default:l.appendChild(n.createTextNode(t.value))}})),l.className=kv+" "+Ov;var A=s===l_.BEFORE?" "+kv:" "+Ov;return ev(t)?t.className.baseValue+=A:t.className+=A,l}}},e.destroy=function(e){return!!e.parentNode&&(e.parentNode.removeChild(e),!0)},e}();!function(e){e[e.BEFORE=0]="BEFORE",e[e.AFTER=1]="AFTER"}(l_||(l_={}));var Mv,Ev=function(e,t){var i=e.createElement("iframe");return i.className="html2canvas-container",i.style.visibility="hidden",i.style.position="fixed",i.style.left="-10000px",i.style.top="0px",i.style.border="0",i.width=t.width.toString(),i.height=t.height.toString(),i.scrolling="no",i.setAttribute("data-html2canvas-ignore","true"),e.body.appendChild(i),i},Fv=function(e){return new Promise((function(t){e.complete?t():e.src?(e.onload=t,e.onerror=t):t()}))},Iv=function(e){return Promise.all([].slice.call(e.images,0).map(Fv))},Dv=function(e){return new Promise((function(t,i){var s=e.contentWindow;if(!s)return i("No window assigned for iframe");var r=s.document;s.onload=e.onload=function(){s.onload=e.onload=null;var i=setInterval((function(){r.body.childNodes.length>0&&"complete"===r.readyState&&(clearInterval(i),t(e))}),50)}}))},Sv=["all","d","content"],Tv=function(e,t){for(var i=e.length-1;i>=0;i--){var s=e.item(i);-1===Sv.indexOf(s)&&t.style.setProperty(s,e.getPropertyValue(s))}return t},Rv=function(e){var t="";return e&&(t+=""),t},Lv=function(e,t,i){e&&e.defaultView&&(t!==e.defaultView.pageXOffset||i!==e.defaultView.pageYOffset)&&e.defaultView.scrollTo(t,i)},Uv=function(e){var t=e[0],i=e[1],s=e[2];t.scrollLeft=i,t.scrollTop=s},kv="___html2canvas___pseudoelement_before",Ov="___html2canvas___pseudoelement_after",Nv=function(e){Qv(e,"."+kv+':before{\n content: "" !important;\n display: none !important;\n}\n .'+Ov+':after{\n content: "" !important;\n display: none !important;\n}')},Qv=function(e,t){var i=e.ownerDocument;if(i){var s=i.createElement("style");s.textContent=t,e.appendChild(s)}},Vv=function(){function e(){}return e.getOrigin=function(t){var i=e._link;return i?(i.href=t,i.href=i.href,i.protocol+i.hostname+i.port):"about:blank"},e.isSameOrigin=function(t){return e.getOrigin(t)===e._origin},e.setContext=function(t){e._link=t.document.createElement("a"),e._origin=e.getOrigin(t.location.href)},e._origin="about:blank",e}(),Hv=function(){function e(e,t){this.context=e,this._options=t,this._cache={}}return e.prototype.addImage=function(e){var t=Promise.resolve();return this.has(e)?t:Jv(e)||Wv(e)?((this._cache[e]=this.loadImage(e)).catch((function(){})),t):t},e.prototype.match=function(e){return this._cache[e]},e.prototype.loadImage=function(e){return zd(this,void 0,void 0,(function(){var t,i,s,r,o=this;return Wd(this,(function(n){switch(n.label){case 0:return t=Vv.isSameOrigin(e),i=!Kv(e)&&!0===this._options.useCORS&&y_.SUPPORT_CORS_IMAGES&&!t,s=!Kv(e)&&!t&&!Jv(e)&&"string"==typeof this._options.proxy&&y_.SUPPORT_CORS_XHR&&!i,t||!1!==this._options.allowTaint||Kv(e)||Jv(e)||s||i?(r=e,s?[4,this.proxy(r)]:[3,2]):[2];case 1:r=n.sent(),n.label=2;case 2:return this.context.logger.debug("Added image "+e.substring(0,256)),[4,new Promise((function(e,t){var s=new Image;s.onload=function(){return e(s)},s.onerror=t,(Xv(r)||i)&&(s.crossOrigin="anonymous"),s.src=r,!0===s.complete&&setTimeout((function(){return e(s)}),500),o._options.imageTimeout>0&&setTimeout((function(){return t("Timed out ("+o._options.imageTimeout+"ms) loading image")}),o._options.imageTimeout)}))];case 3:return[2,n.sent()]}}))}))},e.prototype.has=function(e){return void 0!==this._cache[e]},e.prototype.keys=function(){return Promise.resolve(Object.keys(this._cache))},e.prototype.proxy=function(e){var t=this,i=this._options.proxy;if(!i)throw new Error("No proxy defined");var s=e.substring(0,256);return new Promise((function(r,o){var n=y_.SUPPORT_RESPONSE_TYPE?"blob":"text",a=new XMLHttpRequest;a.onload=function(){if(200===a.status)if("text"===n)r(a.response);else{var e=new FileReader;e.addEventListener("load",(function(){return r(e.result)}),!1),e.addEventListener("error",(function(e){return o(e)}),!1),e.readAsDataURL(a.response)}else o("Failed to proxy resource "+s+" with status code "+a.status)},a.onerror=o;var l=i.indexOf("?")>-1?"&":"?";if(a.open("GET",""+i+l+"url="+encodeURIComponent(e)+"&responseType="+n),"text"!==n&&a instanceof XMLHttpRequest&&(a.responseType=n),t._options.imageTimeout){var A=t._options.imageTimeout;a.timeout=A,a.ontimeout=function(){return o("Timed out ("+A+"ms) proxying "+s)}}a.send()}))},e}(),jv=/^data:image\/svg\+xml/i,Gv=/^data:image\/.*;base64,/i,zv=/^data:image\/.*/i,Wv=function(e){return y_.SUPPORT_SVG_DRAWING||!Yv(e)},Kv=function(e){return zv.test(e)},Xv=function(e){return Gv.test(e)},Jv=function(e){return"blob"===e.substr(0,4)},Yv=function(e){return"svg"===e.substr(-3).toLowerCase()||jv.test(e)},Zv=function(){function e(e,t){this.type=0,this.x=e,this.y=t}return e.prototype.add=function(t,i){return new e(this.x+t,this.y+i)},e}(),qv=function(e,t,i){return new Zv(e.x+(t.x-e.x)*i,e.y+(t.y-e.y)*i)},$v=function(){function e(e,t,i,s){this.type=1,this.start=e,this.startControl=t,this.endControl=i,this.end=s}return e.prototype.subdivide=function(t,i){var s=qv(this.start,this.startControl,t),r=qv(this.startControl,this.endControl,t),o=qv(this.endControl,this.end,t),n=qv(s,r,t),a=qv(r,o,t),l=qv(n,a,t);return i?new e(this.start,s,n,l):new e(l,a,o,this.end)},e.prototype.add=function(t,i){return new e(this.start.add(t,i),this.startControl.add(t,i),this.endControl.add(t,i),this.end.add(t,i))},e.prototype.reverse=function(){return new e(this.end,this.endControl,this.startControl,this.start)},e}(),eb=function(e){return 1===e.type},tb=function(e){var t=e.styles,i=e.bounds,s=Hf(t.borderTopLeftRadius,i.width,i.height),r=s[0],o=s[1],n=Hf(t.borderTopRightRadius,i.width,i.height),a=n[0],l=n[1],A=Hf(t.borderBottomRightRadius,i.width,i.height),h=A[0],c=A[1],u=Hf(t.borderBottomLeftRadius,i.width,i.height),d=u[0],p=u[1],f=[];f.push((r+a)/i.width),f.push((d+h)/i.width),f.push((o+p)/i.height),f.push((l+c)/i.height);var g=Math.max.apply(Math,f);g>1&&(r/=g,o/=g,a/=g,l/=g,h/=g,c/=g,d/=g,p/=g);var m=i.width-a,_=i.height-c,v=i.width-h,b=i.height-p,y=t.borderTopWidth,x=t.borderRightWidth,B=t.borderBottomWidth,w=t.borderLeftWidth,P=jf(t.paddingTop,e.bounds.width),C=jf(t.paddingRight,e.bounds.width),M=jf(t.paddingBottom,e.bounds.width),E=jf(t.paddingLeft,e.bounds.width);this.topLeftBorderDoubleOuterBox=r>0||o>0?ib(i.left+w/3,i.top+y/3,r-w/3,o-y/3,Mv.TOP_LEFT):new Zv(i.left+w/3,i.top+y/3),this.topRightBorderDoubleOuterBox=r>0||o>0?ib(i.left+m,i.top+y/3,a-x/3,l-y/3,Mv.TOP_RIGHT):new Zv(i.left+i.width-x/3,i.top+y/3),this.bottomRightBorderDoubleOuterBox=h>0||c>0?ib(i.left+v,i.top+_,h-x/3,c-B/3,Mv.BOTTOM_RIGHT):new Zv(i.left+i.width-x/3,i.top+i.height-B/3),this.bottomLeftBorderDoubleOuterBox=d>0||p>0?ib(i.left+w/3,i.top+b,d-w/3,p-B/3,Mv.BOTTOM_LEFT):new Zv(i.left+w/3,i.top+i.height-B/3),this.topLeftBorderDoubleInnerBox=r>0||o>0?ib(i.left+2*w/3,i.top+2*y/3,r-2*w/3,o-2*y/3,Mv.TOP_LEFT):new Zv(i.left+2*w/3,i.top+2*y/3),this.topRightBorderDoubleInnerBox=r>0||o>0?ib(i.left+m,i.top+2*y/3,a-2*x/3,l-2*y/3,Mv.TOP_RIGHT):new Zv(i.left+i.width-2*x/3,i.top+2*y/3),this.bottomRightBorderDoubleInnerBox=h>0||c>0?ib(i.left+v,i.top+_,h-2*x/3,c-2*B/3,Mv.BOTTOM_RIGHT):new Zv(i.left+i.width-2*x/3,i.top+i.height-2*B/3),this.bottomLeftBorderDoubleInnerBox=d>0||p>0?ib(i.left+2*w/3,i.top+b,d-2*w/3,p-2*B/3,Mv.BOTTOM_LEFT):new Zv(i.left+2*w/3,i.top+i.height-2*B/3),this.topLeftBorderStroke=r>0||o>0?ib(i.left+w/2,i.top+y/2,r-w/2,o-y/2,Mv.TOP_LEFT):new Zv(i.left+w/2,i.top+y/2),this.topRightBorderStroke=r>0||o>0?ib(i.left+m,i.top+y/2,a-x/2,l-y/2,Mv.TOP_RIGHT):new Zv(i.left+i.width-x/2,i.top+y/2),this.bottomRightBorderStroke=h>0||c>0?ib(i.left+v,i.top+_,h-x/2,c-B/2,Mv.BOTTOM_RIGHT):new Zv(i.left+i.width-x/2,i.top+i.height-B/2),this.bottomLeftBorderStroke=d>0||p>0?ib(i.left+w/2,i.top+b,d-w/2,p-B/2,Mv.BOTTOM_LEFT):new Zv(i.left+w/2,i.top+i.height-B/2),this.topLeftBorderBox=r>0||o>0?ib(i.left,i.top,r,o,Mv.TOP_LEFT):new Zv(i.left,i.top),this.topRightBorderBox=a>0||l>0?ib(i.left+m,i.top,a,l,Mv.TOP_RIGHT):new Zv(i.left+i.width,i.top),this.bottomRightBorderBox=h>0||c>0?ib(i.left+v,i.top+_,h,c,Mv.BOTTOM_RIGHT):new Zv(i.left+i.width,i.top+i.height),this.bottomLeftBorderBox=d>0||p>0?ib(i.left,i.top+b,d,p,Mv.BOTTOM_LEFT):new Zv(i.left,i.top+i.height),this.topLeftPaddingBox=r>0||o>0?ib(i.left+w,i.top+y,Math.max(0,r-w),Math.max(0,o-y),Mv.TOP_LEFT):new Zv(i.left+w,i.top+y),this.topRightPaddingBox=a>0||l>0?ib(i.left+Math.min(m,i.width-x),i.top+y,m>i.width+x?0:Math.max(0,a-x),Math.max(0,l-y),Mv.TOP_RIGHT):new Zv(i.left+i.width-x,i.top+y),this.bottomRightPaddingBox=h>0||c>0?ib(i.left+Math.min(v,i.width-w),i.top+Math.min(_,i.height-B),Math.max(0,h-x),Math.max(0,c-B),Mv.BOTTOM_RIGHT):new Zv(i.left+i.width-x,i.top+i.height-B),this.bottomLeftPaddingBox=d>0||p>0?ib(i.left+w,i.top+Math.min(b,i.height-B),Math.max(0,d-w),Math.max(0,p-B),Mv.BOTTOM_LEFT):new Zv(i.left+w,i.top+i.height-B),this.topLeftContentBox=r>0||o>0?ib(i.left+w+E,i.top+y+P,Math.max(0,r-(w+E)),Math.max(0,o-(y+P)),Mv.TOP_LEFT):new Zv(i.left+w+E,i.top+y+P),this.topRightContentBox=a>0||l>0?ib(i.left+Math.min(m,i.width+w+E),i.top+y+P,m>i.width+w+E?0:a-w+E,l-(y+P),Mv.TOP_RIGHT):new Zv(i.left+i.width-(x+C),i.top+y+P),this.bottomRightContentBox=h>0||c>0?ib(i.left+Math.min(v,i.width-(w+E)),i.top+Math.min(_,i.height+y+P),Math.max(0,h-(x+C)),c-(B+M),Mv.BOTTOM_RIGHT):new Zv(i.left+i.width-(x+C),i.top+i.height-(B+M)),this.bottomLeftContentBox=d>0||p>0?ib(i.left+w+E,i.top+b,Math.max(0,d-(w+E)),p-(B+M),Mv.BOTTOM_LEFT):new Zv(i.left+w+E,i.top+i.height-(B+M))};!function(e){e[e.TOP_LEFT=0]="TOP_LEFT",e[e.TOP_RIGHT=1]="TOP_RIGHT",e[e.BOTTOM_RIGHT=2]="BOTTOM_RIGHT",e[e.BOTTOM_LEFT=3]="BOTTOM_LEFT"}(Mv||(Mv={}));var ib=function(e,t,i,s,r){var o=(Math.sqrt(2)-1)/3*4,n=i*o,a=s*o,l=e+i,A=t+s;switch(r){case Mv.TOP_LEFT:return new $v(new Zv(e,A),new Zv(e,A-a),new Zv(l-n,t),new Zv(l,t));case Mv.TOP_RIGHT:return new $v(new Zv(e,t),new Zv(e+n,t),new Zv(l,A-a),new Zv(l,A));case Mv.BOTTOM_RIGHT:return new $v(new Zv(l,t),new Zv(l,t+a),new Zv(e+n,A),new Zv(e,A));case Mv.BOTTOM_LEFT:default:return new $v(new Zv(l,A),new Zv(l-n,A),new Zv(e,t+a),new Zv(e,t))}},sb=function(e){return[e.topLeftBorderBox,e.topRightBorderBox,e.bottomRightBorderBox,e.bottomLeftBorderBox]},rb=function(e){return[e.topLeftPaddingBox,e.topRightPaddingBox,e.bottomRightPaddingBox,e.bottomLeftPaddingBox]},ob=function(e,t,i){this.offsetX=e,this.offsetY=t,this.matrix=i,this.type=0,this.target=6},nb=function(e,t){this.path=e,this.target=t,this.type=1},ab=function(e){this.opacity=e,this.type=2,this.target=6},lb=function(e){return 1===e.type},Ab=function(e,t){return e.length===t.length&&e.some((function(e,i){return e===t[i]}))},hb=function(e){this.element=e,this.inlineLevel=[],this.nonInlineLevel=[],this.negativeZIndex=[],this.zeroOrAutoZIndexOrTransformedOrOpacity=[],this.positiveZIndex=[],this.nonPositionedFloats=[],this.nonPositionedInlineLevel=[]},cb=function(){function e(e,t){if(this.container=e,this.parent=t,this.effects=[],this.curves=new tb(this.container),this.container.styles.opacity<1&&this.effects.push(new ab(this.container.styles.opacity)),null!==this.container.styles.transform){var i=this.container.bounds.left+this.container.styles.transformOrigin[0].number,s=this.container.bounds.top+this.container.styles.transformOrigin[1].number,r=this.container.styles.transform;this.effects.push(new ob(i,s,r))}if(0!==this.container.styles.overflowX){var o=sb(this.curves),n=rb(this.curves);Ab(o,n)?this.effects.push(new nb(o,6)):(this.effects.push(new nb(o,2)),this.effects.push(new nb(n,4)))}}return e.prototype.getEffects=function(e){for(var t=-1===[2,3].indexOf(this.container.styles.position),i=this.parent,s=this.effects.slice(0);i;){var r=i.effects.filter((function(e){return!lb(e)}));if(t||0!==i.container.styles.position||!i.parent){if(s.unshift.apply(s,r),t=-1===[2,3].indexOf(i.container.styles.position),0!==i.container.styles.overflowX){var o=sb(i.curves),n=rb(i.curves);Ab(o,n)||s.unshift(new nb(n,6))}}else s.unshift.apply(s,r);i=i.parent}return s.filter((function(t){return km(t.target,e)}))},e}(),ub=function(e,t,i,s){e.container.elements.forEach((function(r){var o=km(r.flags,4),n=km(r.flags,2),a=new cb(r,e);km(r.styles.display,2048)&&s.push(a);var l=km(r.flags,8)?[]:s;if(o||n){var A=o||r.styles.isPositioned()?i:t,h=new hb(a);if(r.styles.isPositioned()||r.styles.opacity<1||r.styles.isTransformed()){var c=r.styles.zIndex.order;if(c<0){var u=0;A.negativeZIndex.some((function(e,t){return c>e.element.container.styles.zIndex.order?(u=t,!1):u>0})),A.negativeZIndex.splice(u,0,h)}else if(c>0){var d=0;A.positiveZIndex.some((function(e,t){return c>=e.element.container.styles.zIndex.order?(d=t+1,!1):d>0})),A.positiveZIndex.splice(d,0,h)}else A.zeroOrAutoZIndexOrTransformedOrOpacity.push(h)}else r.styles.isFloating()?A.nonPositionedFloats.push(h):A.nonPositionedInlineLevel.push(h);ub(a,h,o?h:i,l)}else r.styles.isInlineLevel()?t.inlineLevel.push(a):t.nonInlineLevel.push(a),ub(a,t,i,l);km(r.flags,8)&&db(r,l)}))},db=function(e,t){for(var i=e instanceof k_?e.start:1,s=e instanceof k_&&e.reversed,r=0;r0&&e.intrinsicHeight>0){var s=_b(e),r=rb(t);this.path(r),this.ctx.save(),this.ctx.clip(),this.ctx.drawImage(i,0,0,e.intrinsicWidth,e.intrinsicHeight,s.left,s.top,s.width,s.height),this.ctx.restore()}},t.prototype.renderNodeContent=function(e){return zd(this,void 0,void 0,(function(){var i,s,r,o,n,a,l,A,h,c,u,d,p,f,g,m,_,v;return Wd(this,(function(b){switch(b.label){case 0:this.applyEffects(e.getEffects(4)),i=e.container,s=e.curves,r=i.styles,o=0,n=i.textNodes,b.label=1;case 1:return o0&&B>0&&(m=s.ctx.createPattern(p,"repeat"),s.renderRepeat(v,m,P,C))):function(e){return 2===e.type}(i)&&(_=vb(e,t,[null,null,null]),v=_[0],b=_[1],y=_[2],x=_[3],B=_[4],w=0===i.position.length?[Qf]:i.position,P=jf(w[0],x),C=jf(w[w.length-1],B),M=function(e,t,i,s,r){var o=0,n=0;switch(e.size){case 0:0===e.shape?o=n=Math.min(Math.abs(t),Math.abs(t-s),Math.abs(i),Math.abs(i-r)):1===e.shape&&(o=Math.min(Math.abs(t),Math.abs(t-s)),n=Math.min(Math.abs(i),Math.abs(i-r)));break;case 2:if(0===e.shape)o=n=Math.min(hg(t,i),hg(t,i-r),hg(t-s,i),hg(t-s,i-r));else if(1===e.shape){var a=Math.min(Math.abs(i),Math.abs(i-r))/Math.min(Math.abs(t),Math.abs(t-s)),l=cg(s,r,t,i,!0),A=l[0],h=l[1];n=a*(o=hg(A-t,(h-i)/a))}break;case 1:0===e.shape?o=n=Math.max(Math.abs(t),Math.abs(t-s),Math.abs(i),Math.abs(i-r)):1===e.shape&&(o=Math.max(Math.abs(t),Math.abs(t-s)),n=Math.max(Math.abs(i),Math.abs(i-r)));break;case 3:if(0===e.shape)o=n=Math.max(hg(t,i),hg(t,i-r),hg(t-s,i),hg(t-s,i-r));else if(1===e.shape){a=Math.max(Math.abs(i),Math.abs(i-r))/Math.max(Math.abs(t),Math.abs(t-s));var c=cg(s,r,t,i,!1);A=c[0],h=c[1],n=a*(o=hg(A-t,(h-i)/a))}}return Array.isArray(e.size)&&(o=jf(e.size[0],s),n=2===e.size.length?jf(e.size[1],r):o),[o,n]}(i,P,C,x,B),E=M[0],F=M[1],E>0&&F>0&&(I=s.ctx.createRadialGradient(b+P,y+C,0,b+P,y+C,E),lg(i.stops,2*E).forEach((function(e){return I.addColorStop(e.stop,Yf(e.color))})),s.path(v),s.ctx.fillStyle=I,E!==F?(D=e.bounds.left+.5*e.bounds.width,S=e.bounds.top+.5*e.bounds.height,R=1/(T=F/E),s.ctx.save(),s.ctx.translate(D,S),s.ctx.transform(1,0,0,T,0,0),s.ctx.translate(-D,-S),s.ctx.fillRect(b,R*(y-S)+S,x,B*R),s.ctx.restore()):s.ctx.fill())),L.label=6;case 6:return t--,[2]}}))},s=this,r=0,o=e.styles.backgroundImage.slice(0).reverse(),a.label=1;case 1:return r0?2!==l.style?[3,5]:[4,this.renderDashedDottedBorder(l.color,l.width,o,e.curves,2)]:[3,11]:[3,13];case 4:return h.sent(),[3,11];case 5:return 3!==l.style?[3,7]:[4,this.renderDashedDottedBorder(l.color,l.width,o,e.curves,3)];case 6:return h.sent(),[3,11];case 7:return 4!==l.style?[3,9]:[4,this.renderDoubleBorder(l.color,l.width,o,e.curves)];case 8:return h.sent(),[3,11];case 9:return[4,this.renderSolidBorder(l.color,o,e.curves)];case 10:h.sent(),h.label=11;case 11:o++,h.label=12;case 12:return n++,[3,3];case 13:return[2]}}))}))},t.prototype.renderDashedDottedBorder=function(e,t,i,s,r){return zd(this,void 0,void 0,(function(){var o,n,a,l,A,h,c,u,d,p,f,g,m,_,v,b;return Wd(this,(function(y){return this.ctx.save(),o=function(e,t){switch(t){case 0:return fb(e.topLeftBorderStroke,e.topRightBorderStroke);case 1:return fb(e.topRightBorderStroke,e.bottomRightBorderStroke);case 2:return fb(e.bottomRightBorderStroke,e.bottomLeftBorderStroke);default:return fb(e.bottomLeftBorderStroke,e.topLeftBorderStroke)}}(s,i),n=pb(s,i),2===r&&(this.path(n),this.ctx.clip()),eb(n[0])?(a=n[0].start.x,l=n[0].start.y):(a=n[0].x,l=n[0].y),eb(n[1])?(A=n[1].end.x,h=n[1].end.y):(A=n[1].x,h=n[1].y),c=0===i||2===i?Math.abs(a-A):Math.abs(l-h),this.ctx.beginPath(),3===r?this.formatPath(o):this.formatPath(n.slice(0,2)),u=t<3?3*t:2*t,d=t<3?2*t:t,3===r&&(u=t,d=t),p=!0,c<=2*u?p=!1:c<=2*u+d?(u*=f=c/(2*u+d),d*=f):(g=Math.floor((c+d)/(u+d)),m=(c-g*u)/(g-1),d=(_=(c-(g+1)*u)/g)<=0||Math.abs(d-m){})),Zb(this,"_reject",(()=>{})),this.name=e,this.workerThread=t,this.result=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}postMessage(e,t){this.workerThread.postMessage({source:"loaders.gl",type:e,payload:t})}done(e){Gb(this.isRunning),this.isRunning=!1,this._resolve(e)}error(e){Gb(this.isRunning),this.isRunning=!1,this._reject(e)}}class $b{}const ey=new Map;function ty(e){Gb(e.source&&!e.url||!e.source&&e.url);let t=ey.get(e.source||e.url);return t||(e.url&&(t=function(e){if(!e.startsWith("http"))return e;return iy((t=e,"try {\n importScripts('".concat(t,"');\n} catch (error) {\n console.error(error);\n throw error;\n}")));var t}(e.url),ey.set(e.url,t)),e.source&&(t=iy(e.source),ey.set(e.source,t))),Gb(t),t}function iy(e){const t=new Blob([e],{type:"application/javascript"});return URL.createObjectURL(t)}function sy(e,t=!0,i){const s=i||new Set;if(e){if(ry(e))s.add(e);else if(ry(e.buffer))s.add(e.buffer);else if(ArrayBuffer.isView(e));else if(t&&"object"==typeof e)for(const i in e)sy(e[i],t,s)}else;return void 0===i?Array.from(s):[]}function ry(e){return!!e&&(e instanceof ArrayBuffer||("undefined"!=typeof MessagePort&&e instanceof MessagePort||("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)))}const oy=()=>{};class ny{static isSupported(){return"undefined"!=typeof Worker&&Kb||void 0!==typeof $b}constructor(e){Zb(this,"name",void 0),Zb(this,"source",void 0),Zb(this,"url",void 0),Zb(this,"terminated",!1),Zb(this,"worker",void 0),Zb(this,"onMessage",void 0),Zb(this,"onError",void 0),Zb(this,"_loadableURL","");const{name:t,source:i,url:s}=e;Gb(i||s),this.name=t,this.source=i,this.url=s,this.onMessage=oy,this.onError=e=>console.log(e),this.worker=Kb?this._createBrowserWorker():this._createNodeWorker()}destroy(){this.onMessage=oy,this.onError=oy,this.worker.terminate(),this.terminated=!0}get isRunning(){return Boolean(this.onMessage)}postMessage(e,t){t=t||sy(e),this.worker.postMessage(e,t)}_getErrorFromErrorEvent(e){let t="Failed to load ";return t+="worker ".concat(this.name," from ").concat(this.url,". "),e.message&&(t+="".concat(e.message," in ")),e.lineno&&(t+=":".concat(e.lineno,":").concat(e.colno)),new Error(t)}_createBrowserWorker(){this._loadableURL=ty({source:this.source,url:this.url});const e=new Worker(this._loadableURL,{name:this.name});return e.onmessage=e=>{e.data?this.onMessage(e.data):this.onError(new Error("No data received"))},e.onerror=e=>{this.onError(this._getErrorFromErrorEvent(e)),this.terminated=!0},e.onmessageerror=e=>console.error(e),e}_createNodeWorker(){let e;if(this.url){const t=this.url.includes(":/")||this.url.startsWith("/")?this.url:"./".concat(this.url);e=new $b(t,{eval:!1})}else{if(!this.source)throw new Error("no worker");e=new $b(this.source,{eval:!0})}return e.on("message",(e=>{this.onMessage(e)})),e.on("error",(e=>{this.onError(e)})),e.on("exit",(e=>{})),e}}class ay{static isSupported(){return ny.isSupported()}constructor(e){Zb(this,"name","unnamed"),Zb(this,"source",void 0),Zb(this,"url",void 0),Zb(this,"maxConcurrency",1),Zb(this,"maxMobileConcurrency",1),Zb(this,"onDebug",(()=>{})),Zb(this,"reuseWorkers",!0),Zb(this,"props",{}),Zb(this,"jobQueue",[]),Zb(this,"idleQueue",[]),Zb(this,"count",0),Zb(this,"isDestroyed",!1),this.source=e.source,this.url=e.url,this.setProps(e)}destroy(){this.idleQueue.forEach((e=>e.destroy())),this.isDestroyed=!0}setProps(e){this.props={...this.props,...e},void 0!==e.name&&(this.name=e.name),void 0!==e.maxConcurrency&&(this.maxConcurrency=e.maxConcurrency),void 0!==e.maxMobileConcurrency&&(this.maxMobileConcurrency=e.maxMobileConcurrency),void 0!==e.reuseWorkers&&(this.reuseWorkers=e.reuseWorkers),void 0!==e.onDebug&&(this.onDebug=e.onDebug)}async startJob(e,t=((e,t,i)=>e.done(i)),i=((e,t)=>e.error(t))){const s=new Promise((s=>(this.jobQueue.push({name:e,onMessage:t,onError:i,onStart:s}),this)));return this._startQueuedJob(),await s}async _startQueuedJob(){if(!this.jobQueue.length)return;const e=this._getAvailableWorker();if(!e)return;const t=this.jobQueue.shift();if(t){this.onDebug({message:"Starting job",name:t.name,workerThread:e,backlog:this.jobQueue.length});const i=new qb(t.name,e);e.onMessage=e=>t.onMessage(i,e.type,e.payload),e.onError=e=>t.onError(i,e),t.onStart(i);try{await i.result}finally{this.returnWorkerToQueue(e)}}}returnWorkerToQueue(e){this.isDestroyed||!this.reuseWorkers||this.count>this._getMaxConcurrency()?(e.destroy(),this.count--):this.idleQueue.push(e),this.isDestroyed||this._startQueuedJob()}_getAvailableWorker(){if(this.idleQueue.length>0)return this.idleQueue.shift()||null;if(this.count{}};class Ay{static isSupported(){return ny.isSupported()}static getWorkerFarm(e={}){return Ay._workerFarm=Ay._workerFarm||new Ay({}),Ay._workerFarm.setProps(e),Ay._workerFarm}constructor(e){Zb(this,"props",void 0),Zb(this,"workerPools",new Map),this.props={...ly},this.setProps(e),this.workerPools=new Map}destroy(){for(const e of this.workerPools.values())e.destroy();this.workerPools=new Map}setProps(e){this.props={...this.props,...e};for(const e of this.workerPools.values())e.setProps(this._getWorkerPoolProps())}getWorkerPool(e){const{name:t,source:i,url:s}=e;let r=this.workerPools.get(t);return r||(r=new ay({name:t,source:i,url:s}),r.setProps(this._getWorkerPoolProps()),this.workerPools.set(t,r)),r}_getWorkerPoolProps(){return{maxConcurrency:this.props.maxConcurrency,maxMobileConcurrency:this.props.maxMobileConcurrency,reuseWorkers:this.props.reuseWorkers,onDebug:this.props.onDebug}}}Zb(Ay,"_workerFarm",void 0);var hy=Object.freeze({__proto__:null,default:{}});const cy={};async function uy(e,t=null,i={}){return t&&(e=function(e,t,i){if(e.startsWith("http"))return e;const s=i.modules||{};if(s[e])return s[e];if(!Kb)return"modules/".concat(t,"/dist/libs/").concat(e);if(i.CDN)return Gb(i.CDN.startsWith("http")),"".concat(i.CDN,"/").concat(t,"@").concat("3.2.6","/dist/libs/").concat(e);if(Xb)return"../src/libs/".concat(e);return"modules/".concat(t,"/src/libs/").concat(e)}(e,t,i)),cy[e]=cy[e]||async function(e){if(e.endsWith("wasm")){const t=await fetch(e);return await t.arrayBuffer()}if(!Kb)try{return hy&&void 0}catch{return null}if(Xb)return importScripts(e);const t=await fetch(e);return function(e,t){if(!Kb)return;if(Xb)return eval.call(Wb,e),null;const i=document.createElement("script");i.id=t;try{i.appendChild(document.createTextNode(e))}catch(t){i.text=e}return document.body.appendChild(i),null}(await t.text(),e)}(e),await cy[e]}async function dy(e,t,i,s,r){const o=e.id,n=function(e,t={}){const i=t[e.id]||{},s="".concat(e.id,"-worker.js");let r=i.workerUrl;if(r||"compression"!==e.id||(r=t.workerUrl),"test"===t._workerType&&(r="modules/".concat(e.module,"/dist/").concat(s)),!r){let t=e.version;"latest"===t&&(t="latest");const i=t?"@".concat(t):"";r="https://unpkg.com/@loaders.gl/".concat(e.module).concat(i,"/dist/").concat(s)}return Gb(r),r}(e,i),a=Ay.getWorkerFarm(i).getWorkerPool({name:o,url:n});i=JSON.parse(JSON.stringify(i)),s=JSON.parse(JSON.stringify(s||{}));const l=await a.startJob("process-on-worker",py.bind(null,r));l.postMessage("process",{input:t,options:i,context:s});const A=await l.result;return await A.result}async function py(e,t,i,s){switch(i){case"done":t.done(s);break;case"error":t.error(new Error(s.error));break;case"process":const{id:r,input:o,options:n}=s;try{const i=await e(o,n);t.postMessage("done",{id:r,result:i})}catch(e){const i=e instanceof Error?e.message:"unknown error";t.postMessage("error",{id:r,error:i})}break;default:console.warn("parse-with-worker unknown message ".concat(i))}}function fy(e,t,i){if(e.byteLength<=t+i)return"";const s=new DataView(e);let r="";for(let e=0;e=0),Vb(t>0),e+(t-1)&~(t-1)}function yy(e,t,i){let s;if(e instanceof ArrayBuffer)s=new Uint8Array(e);else{const t=e.byteOffset,i=e.byteLength;s=new Uint8Array(e.buffer||e.arrayBuffer,t,i)}return t.set(s,i),i+by(s.byteLength,4)}async function xy(e){const t=[];for await(const i of e)t.push(i);return function(...e){const t=e.map((e=>e instanceof ArrayBuffer?new Uint8Array(e):e)),i=t.reduce(((e,t)=>e+t.byteLength),0),s=new Uint8Array(i);let r=0;for(const e of t)s.set(e,r),r+=e.byteLength;return s.buffer}(...t)}const By={};const wy=e=>"function"==typeof e,Py=e=>null!==e&&"object"==typeof e,Cy=e=>Py(e)&&e.constructor==={}.constructor,My=e=>"undefined"!=typeof Response&&e instanceof Response||e&&e.arrayBuffer&&e.text&&e.json,Ey=e=>"undefined"!=typeof Blob&&e instanceof Blob,Fy=e=>(e=>"undefined"!=typeof ReadableStream&&e instanceof ReadableStream||Py(e)&&wy(e.tee)&&wy(e.cancel)&&wy(e.getReader))(e)||(e=>Py(e)&&wy(e.read)&&wy(e.pipe)&&(e=>"boolean"==typeof e)(e.readable))(e),Iy=/^data:([-\w.]+\/[-\w.+]+)(;|,)/,Dy=/^([-\w.]+\/[-\w.+]+)/;function Sy(e){const t=Dy.exec(e);return t?t[1]:e}function Ty(e){const t=Iy.exec(e);return t?t[1]:""}const Ry=/\?.*/;function Ly(e){if(My(e)){const t=Uy(e.url||"");return{url:t,type:Sy(e.headers.get("content-type")||"")||Ty(t)}}return Ey(e)?{url:Uy(e.name||""),type:e.type||""}:"string"==typeof e?{url:Uy(e),type:Ty(e)}:{url:"",type:""}}function Uy(e){return e.replace(Ry,"")}async function ky(e){if(My(e))return e;const t={},i=function(e){return My(e)?e.headers["content-length"]||-1:Ey(e)?e.size:"string"==typeof e?e.length:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:-1}(e);i>=0&&(t["content-length"]=String(i));const{url:s,type:r}=Ly(e);r&&(t["content-type"]=r);const o=await async function(e){const t=5;if("string"==typeof e)return"data:,".concat(e.slice(0,t));if(e instanceof Blob){const t=e.slice(0,5);return await new Promise((e=>{const i=new FileReader;i.onload=t=>{var i;return e(null==t||null===(i=t.target)||void 0===i?void 0:i.result)},i.readAsDataURL(t)}))}if(e instanceof ArrayBuffer){const i=function(e){let t="";const i=new Uint8Array(e);for(let e=0;e=0)}();class Gy{constructor(e,t,i="sessionStorage"){this.storage=function(e){try{const t=window[e],i="__storage_test__";return t.setItem(i,i),t.removeItem(i),t}catch(e){return null}}(i),this.id=e,this.config={},Object.assign(this.config,t),this._loadConfiguration()}getConfiguration(){return this.config}setConfiguration(e){return this.config={},this.updateConfiguration(e)}updateConfiguration(e){if(Object.assign(this.config,e),this.storage){const e=JSON.stringify(this.config);this.storage.setItem(this.id,e)}return this}_loadConfiguration(){let e={};if(this.storage){const t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}}function zy(e,t,i,s=600){const r=e.src.replace(/\(/g,"%28").replace(/\)/g,"%29");e.width>s&&(i=Math.min(i,s/e.width));const o=e.width*i,n=e.height*i,a=["font-size:1px;","padding:".concat(Math.floor(n/2),"px ").concat(Math.floor(o/2),"px;"),"line-height:".concat(n,"px;"),"background:url(".concat(r,");"),"background-size:".concat(o,"px ").concat(n,"px;"),"color:transparent;"].join("");return["".concat(t," %c+"),a]}const Wy={BLACK:30,RED:31,GREEN:32,YELLOW:33,BLUE:34,MAGENTA:35,CYAN:36,WHITE:37,BRIGHT_BLACK:90,BRIGHT_RED:91,BRIGHT_GREEN:92,BRIGHT_YELLOW:93,BRIGHT_BLUE:94,BRIGHT_MAGENTA:95,BRIGHT_CYAN:96,BRIGHT_WHITE:97};function Ky(e){return"string"==typeof e?Wy[e.toUpperCase()]||Wy.WHITE:e}function Xy(e,t){if(!e)throw new Error(t||"Assertion failed")}function Jy(){let e;if(jy&&Qy.performance)e=Qy.performance.now();else if(Vy.hrtime){const t=Vy.hrtime();e=1e3*t[0]+t[1]/1e6}else e=Date.now();return e}const Yy={debug:jy&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},Zy={enabled:!0,level:0};function qy(){}const $y={},ex={once:!0};function tx(e){for(const t in e)for(const i in e[t])return i||"untitled";return"empty"}class ix{constructor({id:e}={id:""}){this.id=e,this.VERSION=Hy,this._startTs=Jy(),this._deltaTs=Jy(),this.LOG_THROTTLE_TIMEOUT=0,this._storage=new Gy("__probe-".concat(this.id,"__"),Zy),this.userData={},this.timeStamp("".concat(this.id," started")),function(e,t=["constructor"]){const i=Object.getPrototypeOf(e),s=Object.getOwnPropertyNames(i);for(const i of s)"function"==typeof e[i]&&(t.find((e=>i===e))||(e[i]=e[i].bind(e)))}(this),Object.seal(this)}set level(e){this.setLevel(e)}get level(){return this.getLevel()}isEnabled(){return this._storage.config.enabled}getLevel(){return this._storage.config.level}getTotal(){return Number((Jy()-this._startTs).toPrecision(10))}getDelta(){return Number((Jy()-this._deltaTs).toPrecision(10))}set priority(e){this.level=e}get priority(){return this.level}getPriority(){return this.level}enable(e=!0){return this._storage.updateConfiguration({enabled:e}),this}setLevel(e){return this._storage.updateConfiguration({level:e}),this}assert(e,t){Xy(e,t)}warn(e){return this._getLogFunction(0,e,Yy.warn,arguments,ex)}error(e){return this._getLogFunction(0,e,Yy.error,arguments)}deprecated(e,t){return this.warn("`".concat(e,"` is deprecated and will be removed in a later version. Use `").concat(t,"` instead"))}removed(e,t){return this.error("`".concat(e,"` has been removed. Use `").concat(t,"` instead"))}probe(e,t){return this._getLogFunction(e,t,Yy.log,arguments,{time:!0,once:!0})}log(e,t){return this._getLogFunction(e,t,Yy.debug,arguments)}info(e,t){return this._getLogFunction(e,t,console.info,arguments)}once(e,t){return this._getLogFunction(e,t,Yy.debug||Yy.info,arguments,ex)}table(e,t,i){return t?this._getLogFunction(e,t,console.table||qy,i&&[i],{tag:tx(t)}):qy}image({logLevel:e,priority:t,image:i,message:s="",scale:r=1}){return this._shouldLog(e||t)?jy?function({image:e,message:t="",scale:i=1}){if("string"==typeof e){const s=new Image;return s.onload=()=>{const e=zy(s,t,i);console.log(...e)},s.src=e,qy}const s=e.nodeName||"";if("img"===s.toLowerCase())return console.log(...zy(e,t,i)),qy;if("canvas"===s.toLowerCase()){const s=new Image;return s.onload=()=>console.log(...zy(s,t,i)),s.src=e.toDataURL(),qy}return qy}({image:i,message:s,scale:r}):function({image:e,message:t="",scale:i=1}){let s=null;try{s=module.require("asciify-image")}catch(e){}if(s)return()=>s(e,{fit:"box",width:"".concat(Math.round(80*i),"%")}).then((e=>console.log(e)));return qy}({image:i,message:s,scale:r}):qy}settings(){console.table?console.table(this._storage.config):console.log(this._storage.config)}get(e){return this._storage.config[e]}set(e,t){this._storage.updateConfiguration({[e]:t})}time(e,t){return this._getLogFunction(e,t,console.time?console.time:console.info)}timeEnd(e,t){return this._getLogFunction(e,t,console.timeEnd?console.timeEnd:console.info)}timeStamp(e,t){return this._getLogFunction(e,t,console.timeStamp||qy)}group(e,t,i={collapsed:!1}){i=rx({logLevel:e,message:t,opts:i});const{collapsed:s}=i;return i.method=(s?console.groupCollapsed:console.group)||console.info,this._getLogFunction(i)}groupCollapsed(e,t,i={}){return this.group(e,t,Object.assign({},i,{collapsed:!0}))}groupEnd(e){return this._getLogFunction(e,"",console.groupEnd||qy)}withGroup(e,t,i){this.group(e,t)();try{i()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&this.getLevel()>=sx(e)}_getLogFunction(e,t,i,s=[],r){if(this._shouldLog(e)){r=rx({logLevel:e,message:t,args:s,opts:r}),Xy(i=i||r.method),r.total=this.getTotal(),r.delta=this.getDelta(),this._deltaTs=Jy();const o=r.tag||r.message;if(r.once){if($y[o])return qy;$y[o]=Jy()}return t=function(e,t,i){if("string"==typeof t){const s=i.time?function(e,t=8){const i=Math.max(t-e.length,0);return"".concat(" ".repeat(i)).concat(e)}(function(e){let t;return t=e<10?"".concat(e.toFixed(2),"ms"):e<100?"".concat(e.toFixed(1),"ms"):e<1e3?"".concat(e.toFixed(0),"ms"):"".concat((e/1e3).toFixed(2),"s"),t}(i.total)):"";t=i.time?"".concat(e,": ").concat(s," ").concat(t):"".concat(e,": ").concat(t),t=function(e,t,i){return jy||"string"!=typeof e||(t&&(t=Ky(t),e="[".concat(t,"m").concat(e,"")),i&&(t=Ky(i),e="[".concat(i+10,"m").concat(e,""))),e}(t,i.color,i.background)}return t}(this.id,r.message,r),i.bind(console,t,...r.args)}return qy}}function sx(e){if(!e)return 0;let t;switch(typeof e){case"number":t=e;break;case"object":t=e.logLevel||e.priority||0;break;default:return 0}return Xy(Number.isFinite(t)&&t>=0),t}function rx(e){const{logLevel:t,message:i}=e;e.logLevel=sx(t);const s=e.args?Array.from(e.args):[];for(;s.length&&s.shift()!==i;);switch(e.args=s,typeof t){case"string":case"function":void 0!==i&&s.unshift(i),e.message=t;break;case"object":Object.assign(e,t)}"function"==typeof e.message&&(e.message=e.message());const r=typeof e.message;return Xy("string"===r||"object"===r),Object.assign(e,e.opts)}ix.VERSION=Hy;const ox=new ix({id:"loaders.gl"});class nx{log(){return()=>{}}info(){return()=>{}}warn(){return()=>{}}error(){return()=>{}}}const ax={fetch:null,mimeType:void 0,nothrow:!1,log:new class{constructor(){Zb(this,"console",void 0),this.console=console}log(...e){return this.console.log.bind(this.console,...e)}info(...e){return this.console.info.bind(this.console,...e)}warn(...e){return this.console.warn.bind(this.console,...e)}error(...e){return this.console.error.bind(this.console,...e)}},CDN:"https://unpkg.com/@loaders.gl",worker:!0,maxConcurrency:3,maxMobileConcurrency:1,reuseWorkers:Hb,_nodeWorkers:!1,_workerType:"",limit:0,_limitMB:0,batchSize:"auto",batchDebounceMs:0,metadata:!1,transforms:[]},lx={throws:"nothrow",dataType:"(no longer used)",uri:"baseUri",method:"fetch.method",headers:"fetch.headers",body:"fetch.body",mode:"fetch.mode",credentials:"fetch.credentials",cache:"fetch.cache",redirect:"fetch.redirect",referrer:"fetch.referrer",referrerPolicy:"fetch.referrerPolicy",integrity:"fetch.integrity",keepalive:"fetch.keepalive",signal:"fetch.signal"};function Ax(){globalThis.loaders=globalThis.loaders||{};const{loaders:e}=globalThis;return e._state=e._state||{},e._state}const hx=()=>{const e=Ax();return e.globalOptions=e.globalOptions||{...ax},e.globalOptions};function cx(e,t,i,s){return i=i||[],function(e,t){dx(e,null,ax,lx,t);for(const i of t){const s=e&&e[i.id]||{},r=i.options&&i.options[i.id]||{},o=i.deprecatedOptions&&i.deprecatedOptions[i.id]||{};dx(s,i.id,r,o,t)}}(e,i=Array.isArray(i)?i:[i]),function(e,t,i){const s={...e.options||{}};(function(e,t){t&&!("baseUri"in e)&&(e.baseUri=t)})(s,i),null===s.log&&(s.log=new nx);return fx(s,hx()),fx(s,t),s}(t,e,s)}function ux(e,t){const i=hx(),s=e||i;return"function"==typeof s.fetch?s.fetch:Py(s.fetch)?e=>Oy(e,s):null!=t&&t.fetch?null==t?void 0:t.fetch:Oy}function dx(e,t,i,s,r){const o=t||"Top level",n=t?"".concat(t,"."):"";for(const a in e){const l=!t&&Py(e[a]),A="baseUri"===a&&!t,h="workerUrl"===a&&t;if(!(a in i)&&!A&&!h)if(a in s)ox.warn("".concat(o," loader option '").concat(n).concat(a,"' no longer supported, use '").concat(s[a],"'"))();else if(!l){const e=px(a,r);ox.warn("".concat(o," loader option '").concat(n).concat(a,"' not recognized. ").concat(e))()}}}function px(e,t){const i=e.toLowerCase();let s="";for(const r of t)for(const t in r.options){if(e===t)return"Did you mean '".concat(r.id,".").concat(t,"'?");const o=t.toLowerCase();(i.startsWith(o)||o.startsWith(i))&&(s=s||"Did you mean '".concat(r.id,".").concat(t,"'?"))}return s}function fx(e,t){for(const i in t)if(i in t){const s=t[i];Cy(s)&&Cy(e[i])?e[i]={...e[i],...t[i]}:e[i]=t[i]}}function gx(e){var t;if(!e)return!1;Array.isArray(e)&&(e=e[0]);return Array.isArray(null===(t=e)||void 0===t?void 0:t.extensions)}function mx(e){var t,i;let s;return Vb(e,"null loader"),Vb(gx(e),"invalid loader"),Array.isArray(e)&&(s=e[1],e=e[0],e={...e,options:{...e.options,...s}}),(null!==(t=e)&&void 0!==t&&t.parseTextSync||null!==(i=e)&&void 0!==i&&i.parseText)&&(e.text=!0),e.text||(e.binary=!0),e}function _x(){return(()=>{const e=Ax();return e.loaderRegistry=e.loaderRegistry||[],e.loaderRegistry})()}function vx(){return!("object"==typeof process&&"[object process]"===String(process)&&!process.browser)||function(e){if("undefined"!=typeof window&&"object"==typeof window.process&&"renderer"===window.process.type)return!0;if("undefined"!=typeof process&&"object"==typeof process.versions&&Boolean(process.versions.electron))return!0;const t="object"==typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent,i=e||t;return!!(i&&i.indexOf("Electron")>=0)}()}const bx={self:"undefined"!=typeof self&&self,window:"undefined"!=typeof window&&window,global:"undefined"!=typeof global&&global,document:"undefined"!=typeof document&&document,process:"object"==typeof process&&process},yx=bx.window||bx.self||bx.global,xx=bx.process||{},Bx="undefined"!=typeof __VERSION__?__VERSION__:"untranspiled source";vx();class wx{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"sessionStorage";Zb(this,"storage",void 0),Zb(this,"id",void 0),Zb(this,"config",{}),this.storage=function(e){try{const t=window[e],i="__storage_test__";return t.setItem(i,i),t.removeItem(i),t}catch(e){return null}}(i),this.id=e,this.config={},Object.assign(this.config,t),this._loadConfiguration()}getConfiguration(){return this.config}setConfiguration(e){return this.config={},this.updateConfiguration(e)}updateConfiguration(e){if(Object.assign(this.config,e),this.storage){const e=JSON.stringify(this.config);this.storage.setItem(this.id,e)}return this}_loadConfiguration(){let e={};if(this.storage){const t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}}function Px(e,t,i){let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:600;const r=e.src.replace(/\(/g,"%28").replace(/\)/g,"%29");e.width>s&&(i=Math.min(i,s/e.width));const o=e.width*i,n=e.height*i,a=["font-size:1px;","padding:".concat(Math.floor(n/2),"px ").concat(Math.floor(o/2),"px;"),"line-height:".concat(n,"px;"),"background:url(".concat(r,");"),"background-size:".concat(o,"px ").concat(n,"px;"),"color:transparent;"].join("");return["".concat(t," %c+"),a]}let Cx;function Mx(e){return"string"==typeof e?Cx[e.toUpperCase()]||Cx.WHITE:e}function Ex(e,t){if(!e)throw new Error(t||"Assertion failed")}function Fx(){let e;var t,i;if(vx&&"performance"in yx)e=null==yx||null===(t=yx.performance)||void 0===t||null===(i=t.now)||void 0===i?void 0:i.call(t);else if("hrtime"in xx){var s;const t=null==xx||null===(s=xx.hrtime)||void 0===s?void 0:s.call(xx);e=1e3*t[0]+t[1]/1e6}else e=Date.now();return e}!function(e){e[e.BLACK=30]="BLACK",e[e.RED=31]="RED",e[e.GREEN=32]="GREEN",e[e.YELLOW=33]="YELLOW",e[e.BLUE=34]="BLUE",e[e.MAGENTA=35]="MAGENTA",e[e.CYAN=36]="CYAN",e[e.WHITE=37]="WHITE",e[e.BRIGHT_BLACK=90]="BRIGHT_BLACK",e[e.BRIGHT_RED=91]="BRIGHT_RED",e[e.BRIGHT_GREEN=92]="BRIGHT_GREEN",e[e.BRIGHT_YELLOW=93]="BRIGHT_YELLOW",e[e.BRIGHT_BLUE=94]="BRIGHT_BLUE",e[e.BRIGHT_MAGENTA=95]="BRIGHT_MAGENTA",e[e.BRIGHT_CYAN=96]="BRIGHT_CYAN",e[e.BRIGHT_WHITE=97]="BRIGHT_WHITE"}(Cx||(Cx={}));const Ix={debug:vx&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},Dx={enabled:!0,level:0};function Sx(){}const Tx={},Rx={once:!0};class Lx{constructor(){let{id:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{id:""};Zb(this,"id",void 0),Zb(this,"VERSION",Bx),Zb(this,"_startTs",Fx()),Zb(this,"_deltaTs",Fx()),Zb(this,"_storage",void 0),Zb(this,"userData",{}),Zb(this,"LOG_THROTTLE_TIMEOUT",0),this.id=e,this._storage=new wx("__probe-".concat(this.id,"__"),Dx),this.userData={},this.timeStamp("".concat(this.id," started")),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:["constructor"];const i=Object.getPrototypeOf(e),s=Object.getOwnPropertyNames(i);for(const i of s)"function"==typeof e[i]&&(t.find((e=>i===e))||(e[i]=e[i].bind(e)))}(this),Object.seal(this)}set level(e){this.setLevel(e)}get level(){return this.getLevel()}isEnabled(){return this._storage.config.enabled}getLevel(){return this._storage.config.level}getTotal(){return Number((Fx()-this._startTs).toPrecision(10))}getDelta(){return Number((Fx()-this._deltaTs).toPrecision(10))}set priority(e){this.level=e}get priority(){return this.level}getPriority(){return this.level}enable(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this._storage.updateConfiguration({enabled:e}),this}setLevel(e){return this._storage.updateConfiguration({level:e}),this}get(e){return this._storage.config[e]}set(e,t){this._storage.updateConfiguration({[e]:t})}settings(){console.table?console.table(this._storage.config):console.log(this._storage.config)}assert(e,t){Ex(e,t)}warn(e){return this._getLogFunction(0,e,Ix.warn,arguments,Rx)}error(e){return this._getLogFunction(0,e,Ix.error,arguments)}deprecated(e,t){return this.warn("`".concat(e,"` is deprecated and will be removed in a later version. Use `").concat(t,"` instead"))}removed(e,t){return this.error("`".concat(e,"` has been removed. Use `").concat(t,"` instead"))}probe(e,t){return this._getLogFunction(e,t,Ix.log,arguments,{time:!0,once:!0})}log(e,t){return this._getLogFunction(e,t,Ix.debug,arguments)}info(e,t){return this._getLogFunction(e,t,console.info,arguments)}once(e,t){for(var i=arguments.length,s=new Array(i>2?i-2:0),r=2;r{const t=Px(e,i,s);console.log(...t)},e.src=t,Sx}const r=t.nodeName||"";if("img"===r.toLowerCase())return console.log(...Px(t,i,s)),Sx;if("canvas"===r.toLowerCase()){const e=new Image;return e.onload=()=>console.log(...Px(e,i,s)),e.src=t.toDataURL(),Sx}return Sx}({image:s,message:r,scale:o}):function(e){let{image:t,message:i="",scale:s=1}=e,r=null;try{r=module.require("asciify-image")}catch(e){}if(r)return()=>r(t,{fit:"box",width:"".concat(Math.round(80*s),"%")}).then((e=>console.log(e)));return Sx}({image:s,message:r,scale:o}):Sx}time(e,t){return this._getLogFunction(e,t,console.time?console.time:console.info)}timeEnd(e,t){return this._getLogFunction(e,t,console.timeEnd?console.timeEnd:console.info)}timeStamp(e,t){return this._getLogFunction(e,t,console.timeStamp||Sx)}group(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{collapsed:!1};const s=kx({logLevel:e,message:t,opts:i}),{collapsed:r}=i;return s.method=(r?console.groupCollapsed:console.group)||console.info,this._getLogFunction(s)}groupCollapsed(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.group(e,t,Object.assign({},i,{collapsed:!0}))}groupEnd(e){return this._getLogFunction(e,"",console.groupEnd||Sx)}withGroup(e,t,i){this.group(e,t)();try{i()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&this.getLevel()>=Ux(e)}_getLogFunction(e,t,i,s,r){if(this._shouldLog(e)){r=kx({logLevel:e,message:t,args:s,opts:r}),Ex(i=i||r.method),r.total=this.getTotal(),r.delta=this.getDelta(),this._deltaTs=Fx();const o=r.tag||r.message;if(r.once){if(Tx[o])return Sx;Tx[o]=Fx()}return t=function(e,t,i){if("string"==typeof t){const s=i.time?function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8;const i=Math.max(t-e.length,0);return"".concat(" ".repeat(i)).concat(e)}(function(e){let t;return t=e<10?"".concat(e.toFixed(2),"ms"):e<100?"".concat(e.toFixed(1),"ms"):e<1e3?"".concat(e.toFixed(0),"ms"):"".concat((e/1e3).toFixed(2),"s"),t}(i.total)):"";t=i.time?"".concat(e,": ").concat(s," ").concat(t):"".concat(e,": ").concat(t),t=function(e,t,i){return vx||"string"!=typeof e||(t&&(t=Mx(t),e="[".concat(t,"m").concat(e,"")),i&&(t=Mx(i),e="[".concat(i+10,"m").concat(e,""))),e}(t,i.color,i.background)}return t}(this.id,r.message,r),i.bind(console,t,...r.args)}return Sx}}function Ux(e){if(!e)return 0;let t;switch(typeof e){case"number":t=e;break;case"object":t=e.logLevel||e.priority||0;break;default:return 0}return Ex(Number.isFinite(t)&&t>=0),t}function kx(e){const{logLevel:t,message:i}=e;e.logLevel=Ux(t);const s=e.args?Array.from(e.args):[];for(;s.length&&s.shift()!==i;);switch(typeof t){case"string":case"function":void 0!==i&&s.unshift(i),e.message=t;break;case"object":Object.assign(e,t)}"function"==typeof e.message&&(e.message=e.message());const r=typeof e.message;return Ex("string"===r||"object"===r),Object.assign(e,{args:s},e.opts)}function Ox(e){for(const t in e)for(const i in e[t])return i||"untitled";return"empty"}Zb(Lx,"VERSION",Bx);const Nx=new Lx({id:"loaders.gl"}),Qx=/\.([^.]+)$/;function Vx(e,t=[],i,s){if(!Hx(e))return null;if(t&&!Array.isArray(t))return mx(t);let r=[];t&&(r=r.concat(t)),null!=i&&i.ignoreRegisteredLoaders||r.push(..._x()),function(e){for(const t of e)mx(t)}(r);const o=function(e,t,i,s){const{url:r,type:o}=Ly(e),n=r||(null==s?void 0:s.url);let a=null,l="";null!=i&&i.mimeType&&(a=Gx(t,null==i?void 0:i.mimeType),l="match forced by supplied MIME type ".concat(null==i?void 0:i.mimeType));var A;a=a||function(e,t){const i=t&&Qx.exec(t),s=i&&i[1];return s?function(e,t){t=t.toLowerCase();for(const i of e)for(const e of i.extensions)if(e.toLowerCase()===t)return i;return null}(e,s):null}(t,n),l=l||(a?"matched url ".concat(n):""),a=a||Gx(t,o),l=l||(a?"matched MIME type ".concat(o):""),a=a||function(e,t){if(!t)return null;for(const i of e)if("string"==typeof t){if(zx(t,i))return i}else if(ArrayBuffer.isView(t)){if(Wx(t.buffer,t.byteOffset,i))return i}else if(t instanceof ArrayBuffer){if(Wx(t,0,i))return i}return null}(t,e),l=l||(a?"matched initial data ".concat(Kx(e)):""),a=a||Gx(t,null==i?void 0:i.fallbackMimeType),l=l||(a?"matched fallback MIME type ".concat(o):""),l&&Nx.log(1,"selectLoader selected ".concat(null===(A=a)||void 0===A?void 0:A.name,": ").concat(l,"."));return a}(e,r,i,s);if(!(o||null!=i&&i.nothrow))throw new Error(jx(e));return o}function Hx(e){return!(e instanceof Response&&204===e.status)}function jx(e){const{url:t,type:i}=Ly(e);let s="No valid loader found (";s+=t?"".concat(function(e){const t=e&&e.lastIndexOf("/");return t>=0?e.substr(t+1):""}(t),", "):"no url provided, ",s+="MIME type: ".concat(i?'"'.concat(i,'"'):"not provided",", ");const r=e?Kx(e):"";return s+=r?' first bytes: "'.concat(r,'"'):"first bytes: not available",s+=")",s}function Gx(e,t){for(const i of e){if(i.mimeTypes&&i.mimeTypes.includes(t))return i;if(t==="application/x.".concat(i.id))return i}return null}function zx(e,t){if(t.testText)return t.testText(e);return(Array.isArray(t.tests)?t.tests:[t.tests]).some((t=>e.startsWith(t)))}function Wx(e,t,i){return(Array.isArray(i.tests)?i.tests:[i.tests]).some((s=>function(e,t,i,s){if(s instanceof ArrayBuffer)return function(e,t,i){if(i=i||e.byteLength,e.byteLength60?"".concat(t.slice(0,60),"..."):t}catch(e){}return t}(e);throw new Error(t)}}(i),t.binary?await i.arrayBuffer():await i.text()}if(Fy(e)&&(e=Zx(e,i)),(r=e)&&"function"==typeof r[Symbol.iterator]||(e=>e&&"function"==typeof e[Symbol.asyncIterator])(e))return xy(e);var r;throw new Error(qx)}async function eB(e,t,i,s){Gb(!s||"object"==typeof s),!t||Array.isArray(t)||gx(t)||(s=void 0,i=t,t=void 0),e=await e,i=i||{};const{url:r}=Ly(e),o=function(e,t){if(!t&&e&&!Array.isArray(e))return e;let i;if(e&&(i=Array.isArray(e)?e:[e]),t&&t.loaders){const e=Array.isArray(t.loaders)?t.loaders:[t.loaders];i=i?[...i,...e]:e}return i&&i.length?i:null}(t,s),n=await async function(e,t=[],i,s){if(!Hx(e))return null;let r=Vx(e,t,{...i,nothrow:!0},s);if(r)return r;if(Ey(e)&&(r=Vx(e=await e.slice(0,10).arrayBuffer(),t,i,s)),!(r||null!=i&&i.nothrow))throw new Error(jx(e));return r}(e,o,i);return n?(s=function(e,t,i=null){if(i)return i;const s={fetch:ux(t,e),...e};return Array.isArray(s.loaders)||(s.loaders=null),s}({url:r,parse:eB,loaders:o},i=cx(i,n,o,r),s),await async function(e,t,i,s){if(function(e,t="3.2.6"){Gb(e,"no worker provided");const i=e.version}(e),My(t)){const e=t,{ok:i,redirected:r,status:o,statusText:n,type:a,url:l}=e,A=Object.fromEntries(e.headers.entries());s.response={headers:A,ok:i,redirected:r,status:o,statusText:n,type:a,url:l}}if(t=await $x(t,e,i),e.parseTextSync&&"string"==typeof t)return i.dataType="text",e.parseTextSync(t,i,s,e);if(function(e,t){return!!Ay.isSupported()&&!!(Kb||null!=t&&t._nodeWorkers)&&e.worker&&(null==t?void 0:t.worker)}(e,i))return await dy(e,t,i,s,eB);if(e.parseText&&"string"==typeof t)return await e.parseText(t,i,s,e);if(e.parse)return await e.parse(t,i,s,e);throw Gb(!e.parseSync),new Error("".concat(e.id," loader - no parser found and worker is disabled"))}(n,e,i,s)):null}const tB="https://unpkg.com/@loaders.gl/textures@".concat("3.2.6","/dist/libs/basis_encoder.wasm"),iB="https://unpkg.com/@loaders.gl/textures@".concat("3.2.6","/dist/libs/basis_encoder.js");let sB,rB;async function oB(e){const t=e.modules||{};return t.basis?t.basis:(sB=sB||async function(e){let t=null,i=null;return[t,i]=await Promise.all([await uy("basis_transcoder.js","textures",e),await uy("basis_transcoder.wasm","textures",e)]),t=t||globalThis.BASIS,await function(e,t){const i={};t&&(i.wasmBinary=t);return new Promise((t=>{e(i).then((e=>{const{BasisFile:i,initializeBasis:s}=e;s(),t({BasisFile:i})}))}))}(t,i)}(e),await sB)}async function nB(e){const t=e.modules||{};return t.basisEncoder?t.basisEncoder:(rB=rB||async function(e){let t=null,i=null;return[t,i]=await Promise.all([await uy(iB,"textures",e),await uy(tB,"textures",e)]),t=t||globalThis.BASIS,await function(e,t){const i={};t&&(i.wasmBinary=t);return new Promise((t=>{e(i).then((e=>{const{BasisFile:i,KTX2File:s,initializeBasis:r,BasisEncoder:o}=e;r(),t({BasisFile:i,KTX2File:s,BasisEncoder:o})}))}))}(t,i)}(e),await rB)}const aB=33776,lB=33779,AB=35840,hB=35842,cB=36196,uB=37808,dB=["","WEBKIT_","MOZ_"],pB={WEBGL_compressed_texture_s3tc:"dxt",WEBGL_compressed_texture_s3tc_srgb:"dxt-srgb",WEBGL_compressed_texture_etc1:"etc1",WEBGL_compressed_texture_etc:"etc2",WEBGL_compressed_texture_pvrtc:"pvrtc",WEBGL_compressed_texture_atc:"atc",WEBGL_compressed_texture_astc:"astc",EXT_texture_compression_rgtc:"rgtc"};let fB=null;function gB(e){if(!fB){e=e||function(){try{return document.createElement("canvas").getContext("webgl")}catch(e){return null}}()||void 0,fB=new Set;for(const t of dB)for(const i in pB)if(e&&e.getExtension("".concat(t).concat(i))){const e=pB[i];fB.add(e)}}return fB}var mB,_B,vB,bB,yB,xB,BB,wB,PB;(PB=mB||(mB={}))[PB.NONE=0]="NONE",PB[PB.BASISLZ=1]="BASISLZ",PB[PB.ZSTD=2]="ZSTD",PB[PB.ZLIB=3]="ZLIB",function(e){e[e.BASICFORMAT=0]="BASICFORMAT"}(_B||(_B={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.ETC1S=163]="ETC1S",e[e.UASTC=166]="UASTC"}(vB||(vB={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.SRGB=1]="SRGB"}(bB||(bB={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.LINEAR=1]="LINEAR",e[e.SRGB=2]="SRGB",e[e.ITU=3]="ITU",e[e.NTSC=4]="NTSC",e[e.SLOG=5]="SLOG",e[e.SLOG2=6]="SLOG2"}(yB||(yB={})),function(e){e[e.ALPHA_STRAIGHT=0]="ALPHA_STRAIGHT",e[e.ALPHA_PREMULTIPLIED=1]="ALPHA_PREMULTIPLIED"}(xB||(xB={})),function(e){e[e.RGB=0]="RGB",e[e.RRR=3]="RRR",e[e.GGG=4]="GGG",e[e.AAA=15]="AAA"}(BB||(BB={})),function(e){e[e.RGB=0]="RGB",e[e.RGBA=3]="RGBA",e[e.RRR=4]="RRR",e[e.RRRG=5]="RRRG"}(wB||(wB={}));const CB=[171,75,84,88,32,50,48,187,13,10,26,10];const MB={etc1:{basisFormat:0,compressed:!0,format:cB},etc2:{basisFormat:1,compressed:!0},bc1:{basisFormat:2,compressed:!0,format:aB},bc3:{basisFormat:3,compressed:!0,format:lB},bc4:{basisFormat:4,compressed:!0},bc5:{basisFormat:5,compressed:!0},"bc7-m6-opaque-only":{basisFormat:6,compressed:!0},"bc7-m5":{basisFormat:7,compressed:!0},"pvrtc1-4-rgb":{basisFormat:8,compressed:!0,format:AB},"pvrtc1-4-rgba":{basisFormat:9,compressed:!0,format:hB},"astc-4x4":{basisFormat:10,compressed:!0,format:uB},"atc-rgb":{basisFormat:11,compressed:!0},"atc-rgba-interpolated-alpha":{basisFormat:12,compressed:!0},rgba32:{basisFormat:13,compressed:!1},rgb565:{basisFormat:14,compressed:!1},bgr565:{basisFormat:15,compressed:!1},rgba4444:{basisFormat:16,compressed:!1}};function EB(e,t,i){const s=new e(new Uint8Array(t));try{if(!s.startTranscoding())throw new Error("Failed to start basis transcoding");const e=s.getNumImages(),t=[];for(let r=0;r{try{i.onload=()=>t(i),i.onerror=t=>s(new Error("Could not load image ".concat(e,": ").concat(t)))}catch(e){s(e)}}))}(o||s,t)}finally{o&&r.revokeObjectURL(o)}}const WB={};let KB=!0;async function XB(e,t,i){let s;if(jB(i)){s=await zB(e,t,i)}else s=GB(e,i);const r=t&&t.imagebitmap;return await async function(e,t=null){!function(e){for(const t in e||WB)return!1;return!0}(t)&&KB||(t=null);if(t)try{return await createImageBitmap(e,t)}catch(e){console.warn(e),KB=!1}return await createImageBitmap(e)}(s,r)}function JB(e){const t=YB(e);return function(e){const t=YB(e);if(!(t.byteLength>=24&&2303741511===t.getUint32(0,false)))return null;return{mimeType:"image/png",width:t.getUint32(16,false),height:t.getUint32(20,false)}}(t)||function(e){const t=YB(e);if(!(t.byteLength>=3&&65496===t.getUint16(0,false)&&255===t.getUint8(2)))return null;const{tableMarkers:i,sofMarkers:s}=function(){const e=new Set([65499,65476,65484,65501,65534]);for(let t=65504;t<65520;++t)e.add(t);const t=new Set([65472,65473,65474,65475,65477,65478,65479,65481,65482,65483,65485,65486,65487,65502]);return{tableMarkers:e,sofMarkers:t}}();let r=2;for(;r+9=10&&1195984440===t.getUint32(0,false)))return null;return{mimeType:"image/gif",width:t.getUint16(6,true),height:t.getUint16(8,true)}}(t)||function(e){const t=YB(e);if(!(t.byteLength>=14&&16973===t.getUint16(0,false)&&t.getUint32(2,true)===t.byteLength))return null;return{mimeType:"image/bmp",width:t.getUint32(18,true),height:t.getUint32(22,true)}}(t)}function YB(e){if(e instanceof DataView)return e;if(ArrayBuffer.isView(e))return new DataView(e.buffer);if(e instanceof ArrayBuffer)return new DataView(e);throw new Error("toDataView")}const ZB={id:"image",module:"images",name:"Images",version:"3.2.6",mimeTypes:["image/png","image/jpeg","image/gif","image/webp","image/bmp","image/vnd.microsoft.icon","image/svg+xml"],extensions:["png","jpg","jpeg","gif","webp","bmp","ico","svg"],parse:async function(e,t,i){const s=((t=t||{}).image||{}).type||"auto",{url:r}=i||{};let o;switch(function(e){switch(e){case"auto":case"data":return function(){if(kB)return"imagebitmap";if(UB)return"image";if(NB)return"data";throw new Error("Install '@loaders.gl/polyfills' to parse images under Node.js")}();default:return function(e){switch(e){case"auto":return kB||UB||NB;case"imagebitmap":return kB;case"image":return UB;case"data":return NB;default:throw new Error("@loaders.gl/images: image ".concat(e," not supported in this environment"))}}(e),e}}(s)){case"imagebitmap":o=await XB(e,t,r);break;case"image":o=await zB(e,t,r);break;case"data":o=await async function(e,t){const{mimeType:i}=JB(e)||{},s=globalThis._parseImageNode;return Vb(s),await s(e,i)}(e);break;default:Vb(!1)}return"data"===s&&(o=function(e){switch(QB(e)){case"data":return e;case"image":case"imagebitmap":const t=document.createElement("canvas"),i=t.getContext("2d");if(!i)throw new Error("getImageData");return t.width=e.width,t.height=e.height,i.drawImage(e,0,0),i.getImageData(0,0,e.width,e.height);default:throw new Error("getImageData")}}(o)),o},tests:[e=>Boolean(JB(new DataView(e)))],options:{image:{type:"auto",decode:!0}}},qB=["image/png","image/jpeg","image/gif"],$B={};function ew(e){return void 0===$B[e]&&($B[e]=function(e){switch(e){case"image/webp":return function(){if(!Hb)return!1;try{return 0===document.createElement("canvas").toDataURL("image/webp").indexOf("data:image/webp")}catch{return!1}}();case"image/svg":return Hb;default:if(!Hb){const{_parseImageNode:t}=globalThis;return Boolean(t)&&qB.includes(e)}return!0}}(e)),$B[e]}function tw(e,t){if(!e)throw new Error(t||"assert failed: gltf")}function iw(e,t){if(e.startsWith("data:")||e.startsWith("http:")||e.startsWith("https:"))return e;const i=t.baseUri||t.uri;if(!i)throw new Error("'baseUri' must be provided to resolve relative url ".concat(e));return i.substr(0,i.lastIndexOf("/")+1)+e}const sw=["SCALAR","VEC2","VEC3","VEC4"],rw=[[Int8Array,5120],[Uint8Array,5121],[Int16Array,5122],[Uint16Array,5123],[Uint32Array,5125],[Float32Array,5126],[Float64Array,5130]],ow=new Map(rw),nw={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},aw={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},lw={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array};function Aw(e){return sw[e-1]||sw[0]}function hw(e){const t=ow.get(e.constructor);if(!t)throw new Error("Illegal typed array");return t}function cw(e,t){const i=lw[e.componentType],s=nw[e.type],r=aw[e.componentType],o=e.count*s,n=e.count*s*r;return tw(n>=0&&n<=t.byteLength),{ArrayType:i,length:o,byteLength:n}}const uw={asset:{version:"2.0",generator:"loaders.gl"},buffers:[]};class dw{constructor(e){Zb(this,"gltf",void 0),Zb(this,"sourceBuffers",void 0),Zb(this,"byteLength",void 0),this.gltf=e||{json:{...uw},buffers:[]},this.sourceBuffers=[],this.byteLength=0,this.gltf.buffers&&this.gltf.buffers[0]&&(this.byteLength=this.gltf.buffers[0].byteLength,this.sourceBuffers=[this.gltf.buffers[0]])}get json(){return this.gltf.json}getApplicationData(e){return this.json[e]}getExtraData(e){return(this.json.extras||{})[e]}getExtension(e){const t=this.getUsedExtensions().find((t=>t===e)),i=this.json.extensions||{};return t?i[e]||!0:null}getRequiredExtension(e){const t=this.getRequiredExtensions().find((t=>t===e));return t?this.getExtension(e):null}getRequiredExtensions(){return this.json.extensionsRequired||[]}getUsedExtensions(){return this.json.extensionsUsed||[]}getObjectExtension(e,t){return(e.extensions||{})[t]}getScene(e){return this.getObject("scenes",e)}getNode(e){return this.getObject("nodes",e)}getSkin(e){return this.getObject("skins",e)}getMesh(e){return this.getObject("meshes",e)}getMaterial(e){return this.getObject("materials",e)}getAccessor(e){return this.getObject("accessors",e)}getTexture(e){return this.getObject("textures",e)}getSampler(e){return this.getObject("samplers",e)}getImage(e){return this.getObject("images",e)}getBufferView(e){return this.getObject("bufferViews",e)}getBuffer(e){return this.getObject("buffers",e)}getObject(e,t){if("object"==typeof t)return t;const i=this.json[e]&&this.json[e][t];if(!i)throw new Error("glTF file error: Could not find ".concat(e,"[").concat(t,"]"));return i}getTypedArrayForBufferView(e){const t=(e=this.getBufferView(e)).buffer,i=this.gltf.buffers[t];tw(i);const s=(e.byteOffset||0)+i.byteOffset;return new Uint8Array(i.arrayBuffer,s,e.byteLength)}getTypedArrayForAccessor(e){e=this.getAccessor(e);const t=this.getBufferView(e.bufferView),i=this.getBuffer(t.buffer).data,{ArrayType:s,length:r}=cw(e,t);return new s(i,t.byteOffset+e.byteOffset,r)}getTypedArrayForImageData(e){e=this.getAccessor(e);const t=this.getBufferView(e.bufferView),i=this.getBuffer(t.buffer).data,s=t.byteOffset||0;return new Uint8Array(i,s,t.byteLength)}addApplicationData(e,t){return this.json[e]=t,this}addExtraData(e,t){return this.json.extras=this.json.extras||{},this.json.extras[e]=t,this}addObjectExtension(e,t,i){return e.extensions=e.extensions||{},e.extensions[t]=i,this.registerUsedExtension(t),this}setObjectExtension(e,t,i){(e.extensions||{})[t]=i}removeObjectExtension(e,t){const i=e.extensions||{},s=i[t];return delete i[t],s}addExtension(e,t={}){return tw(t),this.json.extensions=this.json.extensions||{},this.json.extensions[e]=t,this.registerUsedExtension(e),t}addRequiredExtension(e,t={}){return tw(t),this.addExtension(e,t),this.registerRequiredExtension(e),t}registerUsedExtension(e){this.json.extensionsUsed=this.json.extensionsUsed||[],this.json.extensionsUsed.find((t=>t===e))||this.json.extensionsUsed.push(e)}registerRequiredExtension(e){this.registerUsedExtension(e),this.json.extensionsRequired=this.json.extensionsRequired||[],this.json.extensionsRequired.find((t=>t===e))||this.json.extensionsRequired.push(e)}removeExtension(e){this.json.extensionsRequired&&this._removeStringFromArray(this.json.extensionsRequired,e),this.json.extensionsUsed&&this._removeStringFromArray(this.json.extensionsUsed,e),this.json.extensions&&delete this.json.extensions[e]}setDefaultScene(e){this.json.scene=e}addScene(e){const{nodeIndices:t}=e;return this.json.scenes=this.json.scenes||[],this.json.scenes.push({nodes:t}),this.json.scenes.length-1}addNode(e){const{meshIndex:t,matrix:i}=e;this.json.nodes=this.json.nodes||[];const s={mesh:t};return i&&(s.matrix=i),this.json.nodes.push(s),this.json.nodes.length-1}addMesh(e){const{attributes:t,indices:i,material:s,mode:r=4}=e,o={primitives:[{attributes:this._addAttributes(t),mode:r}]};if(i){const e=this._addIndices(i);o.primitives[0].indices=e}return Number.isFinite(s)&&(o.primitives[0].material=s),this.json.meshes=this.json.meshes||[],this.json.meshes.push(o),this.json.meshes.length-1}addPointCloud(e){const t={primitives:[{attributes:this._addAttributes(e),mode:0}]};return this.json.meshes=this.json.meshes||[],this.json.meshes.push(t),this.json.meshes.length-1}addImage(e,t){const i=JB(e),s=t||(null==i?void 0:i.mimeType),r={bufferView:this.addBufferView(e),mimeType:s};return this.json.images=this.json.images||[],this.json.images.push(r),this.json.images.length-1}addBufferView(e){const t=e.byteLength;tw(Number.isFinite(t)),this.sourceBuffers=this.sourceBuffers||[],this.sourceBuffers.push(e);const i={buffer:0,byteOffset:this.byteLength,byteLength:t};return this.byteLength+=by(t,4),this.json.bufferViews=this.json.bufferViews||[],this.json.bufferViews.push(i),this.json.bufferViews.length-1}addAccessor(e,t){const i={bufferView:e,type:Aw(t.size),componentType:t.componentType,count:t.count,max:t.max,min:t.min};return this.json.accessors=this.json.accessors||[],this.json.accessors.push(i),this.json.accessors.length-1}addBinaryBuffer(e,t={size:3}){const i=this.addBufferView(e);let s={min:t.min,max:t.max};s.min&&s.max||(s=this._getAccessorMinMax(e,t.size));const r={size:t.size,componentType:hw(e),count:Math.round(e.length/t.size),min:s.min,max:s.max};return this.addAccessor(i,Object.assign(r,t))}addTexture(e){const{imageIndex:t}=e,i={source:t};return this.json.textures=this.json.textures||[],this.json.textures.push(i),this.json.textures.length-1}addMaterial(e){return this.json.materials=this.json.materials||[],this.json.materials.push(e),this.json.materials.length-1}createBinaryChunk(){var e,t;this.gltf.buffers=[];const i=this.byteLength,s=new ArrayBuffer(i),r=new Uint8Array(s);let o=0;for(const e of this.sourceBuffers||[])o=yy(e,r,o);null!==(e=this.json)&&void 0!==e&&null!==(t=e.buffers)&&void 0!==t&&t[0]?this.json.buffers[0].byteLength=i:this.json.buffers=[{byteLength:i}],this.gltf.binary=s,this.sourceBuffers=[s]}_removeStringFromArray(e,t){let i=!0;for(;i;){const s=e.indexOf(t);s>-1?e.splice(s,1):i=!1}}_addAttributes(e={}){const t={};for(const i in e){const s=e[i],r=this._getGltfAttributeName(i),o=this.addBinaryBuffer(s.value,s);t[r]=o}return t}_addIndices(e){return this.addBinaryBuffer(e,{size:1})}_getGltfAttributeName(e){switch(e.toLowerCase()){case"position":case"positions":case"vertices":return"POSITION";case"normal":case"normals":return"NORMAL";case"color":case"colors":return"COLOR_0";case"texcoord":case"texcoords":return"TEXCOORD_0";default:return e}}_getAccessorMinMax(e,t){const i={min:null,max:null};if(e.length96?s-71:s>64?s-65:s>47?s+4:s>46?63:62}let i=0;for(let s=0;st[e.name]));return new Mw(i,this.metadata)}selectAt(...e){const t=e.map((e=>this.fields[e])).filter(Boolean);return new Mw(t,this.metadata)}assign(e){let t,i=this.metadata;if(e instanceof Mw){const s=e;t=s.fields,i=Ew(Ew(new Map,this.metadata),s.metadata)}else t=e;const s=Object.create(null);for(const e of this.fields)s[e.name]=e;for(const e of t)s[e.name]=e;const r=Object.values(s);return new Mw(r,i)}}function Ew(e,t){return new Map([...e||new Map,...t||new Map])}class Fw{constructor(e,t,i=!1,s=new Map){Zb(this,"name",void 0),Zb(this,"type",void 0),Zb(this,"nullable",void 0),Zb(this,"metadata",void 0),this.name=e,this.type=t,this.nullable=i,this.metadata=s}get typeId(){return this.type&&this.type.typeId}clone(){return new Fw(this.name,this.type,this.nullable,this.metadata)}compareTo(e){return this.name===e.name&&this.type===e.type&&this.nullable===e.nullable&&this.metadata===e.metadata}toString(){return"".concat(this.type).concat(this.nullable?", nullable":"").concat(this.metadata?", metadata: ".concat(this.metadata):"")}}let Iw,Dw,Sw,Tw;!function(e){e[e.NONE=0]="NONE",e[e.Null=1]="Null",e[e.Int=2]="Int",e[e.Float=3]="Float",e[e.Binary=4]="Binary",e[e.Utf8=5]="Utf8",e[e.Bool=6]="Bool",e[e.Decimal=7]="Decimal",e[e.Date=8]="Date",e[e.Time=9]="Time",e[e.Timestamp=10]="Timestamp",e[e.Interval=11]="Interval",e[e.List=12]="List",e[e.Struct=13]="Struct",e[e.Union=14]="Union",e[e.FixedSizeBinary=15]="FixedSizeBinary",e[e.FixedSizeList=16]="FixedSizeList",e[e.Map=17]="Map",e[e.Dictionary=-1]="Dictionary",e[e.Int8=-2]="Int8",e[e.Int16=-3]="Int16",e[e.Int32=-4]="Int32",e[e.Int64=-5]="Int64",e[e.Uint8=-6]="Uint8",e[e.Uint16=-7]="Uint16",e[e.Uint32=-8]="Uint32",e[e.Uint64=-9]="Uint64",e[e.Float16=-10]="Float16",e[e.Float32=-11]="Float32",e[e.Float64=-12]="Float64",e[e.DateDay=-13]="DateDay",e[e.DateMillisecond=-14]="DateMillisecond",e[e.TimestampSecond=-15]="TimestampSecond",e[e.TimestampMillisecond=-16]="TimestampMillisecond",e[e.TimestampMicrosecond=-17]="TimestampMicrosecond",e[e.TimestampNanosecond=-18]="TimestampNanosecond",e[e.TimeSecond=-19]="TimeSecond",e[e.TimeMillisecond=-20]="TimeMillisecond",e[e.TimeMicrosecond=-21]="TimeMicrosecond",e[e.TimeNanosecond=-22]="TimeNanosecond",e[e.DenseUnion=-23]="DenseUnion",e[e.SparseUnion=-24]="SparseUnion",e[e.IntervalDayTime=-25]="IntervalDayTime",e[e.IntervalYearMonth=-26]="IntervalYearMonth"}(Iw||(Iw={}));class Rw{static isNull(e){return e&&e.typeId===Iw.Null}static isInt(e){return e&&e.typeId===Iw.Int}static isFloat(e){return e&&e.typeId===Iw.Float}static isBinary(e){return e&&e.typeId===Iw.Binary}static isUtf8(e){return e&&e.typeId===Iw.Utf8}static isBool(e){return e&&e.typeId===Iw.Bool}static isDecimal(e){return e&&e.typeId===Iw.Decimal}static isDate(e){return e&&e.typeId===Iw.Date}static isTime(e){return e&&e.typeId===Iw.Time}static isTimestamp(e){return e&&e.typeId===Iw.Timestamp}static isInterval(e){return e&&e.typeId===Iw.Interval}static isList(e){return e&&e.typeId===Iw.List}static isStruct(e){return e&&e.typeId===Iw.Struct}static isUnion(e){return e&&e.typeId===Iw.Union}static isFixedSizeBinary(e){return e&&e.typeId===Iw.FixedSizeBinary}static isFixedSizeList(e){return e&&e.typeId===Iw.FixedSizeList}static isMap(e){return e&&e.typeId===Iw.Map}static isDictionary(e){return e&&e.typeId===Iw.Dictionary}get typeId(){return Iw.NONE}compareTo(e){return this===e}}Dw=Symbol.toStringTag;class Lw extends Rw{constructor(e,t){super(),Zb(this,"isSigned",void 0),Zb(this,"bitWidth",void 0),this.isSigned=e,this.bitWidth=t}get typeId(){return Iw.Int}get[Dw](){return"Int"}toString(){return"".concat(this.isSigned?"I":"Ui","nt").concat(this.bitWidth)}}class Uw extends Lw{constructor(){super(!0,8)}}class kw extends Lw{constructor(){super(!0,16)}}class Ow extends Lw{constructor(){super(!0,32)}}class Nw extends Lw{constructor(){super(!1,8)}}class Qw extends Lw{constructor(){super(!1,16)}}class Vw extends Lw{constructor(){super(!1,32)}}const Hw=32,jw=64;Sw=Symbol.toStringTag;class Gw extends Rw{constructor(e){super(),Zb(this,"precision",void 0),this.precision=e}get typeId(){return Iw.Float}get[Sw](){return"Float"}toString(){return"Float".concat(this.precision)}}class zw extends Gw{constructor(){super(Hw)}}class Ww extends Gw{constructor(){super(jw)}}Tw=Symbol.toStringTag;class Kw extends Rw{constructor(e,t){super(),Zb(this,"listSize",void 0),Zb(this,"children",void 0),this.listSize=e,this.children=[t]}get typeId(){return Iw.FixedSizeList}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get[Tw](){return"FixedSizeList"}toString(){return"FixedSizeList[".concat(this.listSize,"]<").concat(this.valueType,">")}}function Xw(e,t,i){const s=function(e){switch(e.constructor){case Int8Array:return new Uw;case Uint8Array:return new Nw;case Int16Array:return new kw;case Uint16Array:return new Qw;case Int32Array:return new Ow;case Uint32Array:return new Vw;case Float32Array:return new zw;case Float64Array:return new Ww;default:throw new Error("array type not supported")}}(t.value),r=i||function(e){const t=new Map;"byteOffset"in e&&t.set("byteOffset",e.byteOffset.toString(10));"byteStride"in e&&t.set("byteStride",e.byteStride.toString(10));"normalized"in e&&t.set("normalized",e.normalized.toString());return t}(t);return new Fw(e,new Kw(t.size,new Fw("value",s)),!1,r)}function Jw(e,t,i){return Xw(e,t,i?Yw(i.metadata):void 0)}function Yw(e){const t=new Map;for(const i in e)t.set("".concat(i,".string"),JSON.stringify(e[i]));return t}const Zw={POSITION:"POSITION",NORMAL:"NORMAL",COLOR:"COLOR_0",TEX_COORD:"TEXCOORD_0"},qw={1:Int8Array,2:Uint8Array,3:Int16Array,4:Uint16Array,5:Int32Array,6:Uint32Array,9:Float32Array};class $w{constructor(e){Zb(this,"draco",void 0),Zb(this,"decoder",void 0),Zb(this,"metadataQuerier",void 0),this.draco=e,this.decoder=new this.draco.Decoder,this.metadataQuerier=new this.draco.MetadataQuerier}destroy(){this.draco.destroy(this.decoder),this.draco.destroy(this.metadataQuerier)}parseSync(e,t={}){const i=new this.draco.DecoderBuffer;i.Init(new Int8Array(e),e.byteLength),this._disableAttributeTransforms(t);const s=this.decoder.GetEncodedGeometryType(i),r=s===this.draco.TRIANGULAR_MESH?new this.draco.Mesh:new this.draco.PointCloud;try{let e;switch(s){case this.draco.TRIANGULAR_MESH:e=this.decoder.DecodeBufferToMesh(i,r);break;case this.draco.POINT_CLOUD:e=this.decoder.DecodeBufferToPointCloud(i,r);break;default:throw new Error("DRACO: Unknown geometry type.")}if(!e.ok()||!r.ptr){const t="DRACO decompression failed: ".concat(e.error_msg());throw new Error(t)}const o=this._getDracoLoaderData(r,s,t),n=this._getMeshData(r,o,t),a=function(e){let t=1/0,i=1/0,s=1/0,r=-1/0,o=-1/0,n=-1/0;const a=e.POSITION?e.POSITION.value:[],l=a&&a.length;for(let e=0;er?l:r,o=A>o?A:o,n=h>n?h:n}return[[t,i,s],[r,o,n]]}(n.attributes),l=function(e,t,i){const s=Yw(t.metadata),r=[],o=function(e){const t={};for(const i in e){const s=e[i];t[s.name||"undefined"]=s}return t}(t.attributes);for(const t in e){const i=Jw(t,e[t],o[t]);r.push(i)}if(i){const e=Jw("indices",i);r.push(e)}return new Mw(r,s)}(n.attributes,o,n.indices);return{loader:"draco",loaderData:o,header:{vertexCount:r.num_points(),boundingBox:a},...n,schema:l}}finally{this.draco.destroy(i),r&&this.draco.destroy(r)}}_getDracoLoaderData(e,t,i){const s=this._getTopLevelMetadata(e),r=this._getDracoAttributes(e,i);return{geometry_type:t,num_attributes:e.num_attributes(),num_points:e.num_points(),num_faces:e instanceof this.draco.Mesh?e.num_faces():0,metadata:s,attributes:r}}_getDracoAttributes(e,t){const i={};for(let s=0;sthis.decoder[e])).includes(s)){const t=new this.draco.AttributeQuantizationTransform;try{if(t.InitFromAttribute(e))return{quantization_bits:t.quantization_bits(),range:t.range(),min_values:new Float32Array([1,2,3]).map((e=>t.min_value(e)))}}finally{this.draco.destroy(t)}}return null}_getOctahedronTransform(e,t){const{octahedronAttributes:i=[]}=t,s=e.attribute_type();if(i.map((e=>this.decoder[e])).includes(s)){const t=new this.draco.AttributeQuantizationTransform;try{if(t.InitFromAttribute(e))return{quantization_bits:t.quantization_bits()}}finally{this.draco.destroy(t)}}return null}}const eP="https://www.gstatic.com/draco/versioned/decoders/".concat("1.4.1","/draco_decoder.js"),tP="https://www.gstatic.com/draco/versioned/decoders/".concat("1.4.1","/draco_wasm_wrapper.js"),iP="https://www.gstatic.com/draco/versioned/decoders/".concat("1.4.1","/draco_decoder.wasm");let sP;async function rP(e){const t=e.modules||{};return sP=t.draco3d?sP||t.draco3d.createDecoderModule({}).then((e=>({draco:e}))):sP||async function(e){let t,i;if("js"===(e.draco&&e.draco.decoderType))t=await uy(eP,"draco",e);else[t,i]=await Promise.all([await uy(tP,"draco",e),await uy(iP,"draco",e)]);return t=t||globalThis.DracoDecoderModule,await function(e,t){const i={};t&&(i.wasmBinary=t);return new Promise((t=>{e({...i,onModuleLoaded:e=>t({draco:e})})}))}(t,i)}(e),await sP}const oP={...Cw,parse:async function(e,t){const{draco:i}=await rP(t),s=new $w(i);try{return s.parseSync(e,null==t?void 0:t.draco)}finally{s.destroy()}}};function nP(e){const{buffer:t,size:i,count:s}=function(e){let t=e,i=1,s=0;e&&e.value&&(t=e.value,i=e.size||1);t&&(ArrayBuffer.isView(t)||(t=function(e,t,i=!1){if(!e)return null;if(Array.isArray(e))return new t(e);if(i&&!(e instanceof t))return new t(e);return e}(t,Float32Array)),s=t.length/i);return{buffer:t,size:i,count:s}}(e);return{value:t,size:i,byteOffset:0,count:s,type:Aw(i),componentType:hw(t)}}async function aP(e,t,i,s){const r=e.getObjectExtension(t,"KHR_draco_mesh_compression");if(!r)return;const o=e.getTypedArrayForBufferView(r.bufferView),n=vy(o.buffer,o.byteOffset),{parse:a}=s,l={...i};delete l["3d-tiles"];const A=await a(n,oP,l,s),h=function(e){const t={};for(const i in e){const s=e[i];if("indices"!==i){const e=nP(s);t[i]=e}}return t}(A.attributes);for(const[i,s]of Object.entries(h))if(i in t.attributes){const r=t.attributes[i],o=e.getAccessor(r);null!=o&&o.min&&null!=o&&o.max&&(s.min=o.min,s.max=o.max)}t.attributes=h,A.indices&&(t.indices=nP(A.indices)),function(e){if(!e.attributes&&Object.keys(e.attributes).length>0)throw new Error("glTF: Empty primitive detected: Draco decompression failure?")}(t)}function lP(e,t,i=4,s,r){var o;if(!s.DracoWriter)throw new Error("options.gltf.DracoWriter not provided");const n=s.DracoWriter.encodeSync({attributes:e}),a=null==r||null===(o=r.parseSync)||void 0===o?void 0:o.call(r,{attributes:e}),l=s._addFauxAttributes(a.attributes);return{primitives:[{attributes:l,mode:i,extensions:{KHR_draco_mesh_compression:{bufferView:s.addBufferView(n),attributes:l}}}]}}function*AP(e){for(const t of e.json.meshes||[])for(const e of t.primitives)yield e}var hP=Object.freeze({__proto__:null,name:"KHR_draco_mesh_compression",preprocess:function(e,t,i){const s=new dw(e);for(const e of AP(s))s.getObjectExtension(e,"KHR_draco_mesh_compression")},decode:async function(e,t,i){var s;if(null==t||null===(s=t.gltf)||void 0===s||!s.decompressMeshes)return;const r=new dw(e),o=[];for(const e of AP(r))r.getObjectExtension(e,"KHR_draco_mesh_compression")&&o.push(aP(r,e,t,i));await Promise.all(o),r.removeExtension("KHR_draco_mesh_compression")},encode:function(e,t={}){const i=new dw(e);for(const e of i.json.meshes||[])lP(e),i.addRequiredExtension("KHR_draco_mesh_compression")}});var cP=Object.freeze({__proto__:null,name:"KHR_lights_punctual",decode:async function(e){const t=new dw(e),{json:i}=t,s=t.getExtension("KHR_lights_punctual");s&&(t.json.lights=s.lights,t.removeExtension("KHR_lights_punctual"));for(const e of i.nodes||[]){const i=t.getObjectExtension(e,"KHR_lights_punctual");i&&(e.light=i.light),t.removeObjectExtension(e,"KHR_lights_punctual")}},encode:async function(e){const t=new dw(e),{json:i}=t;if(i.lights){const e=t.addExtension("KHR_lights_punctual");tw(!e.lights),e.lights=i.lights,delete i.lights}if(t.json.lights){for(const e of t.json.lights){const i=e.node;t.addObjectExtension(i,"KHR_lights_punctual",e)}delete t.json.lights}}});function uP(e,t){const i=Object.assign({},e.values);return Object.keys(e.uniforms||{}).forEach((t=>{e.uniforms[t].value&&!(t in i)&&(i[t]=e.uniforms[t].value)})),Object.keys(i).forEach((e=>{"object"==typeof i[e]&&void 0!==i[e].index&&(i[e].texture=t.getTexture(i[e].index))})),i}const dP=[Bw,ww,Pw,hP,cP,Object.freeze({__proto__:null,name:"KHR_materials_unlit",decode:async function(e){const t=new dw(e),{json:i}=t;t.removeExtension("KHR_materials_unlit");for(const e of i.materials||[]){e.extensions&&e.extensions.KHR_materials_unlit&&(e.unlit=!0),t.removeObjectExtension(e,"KHR_materials_unlit")}},encode:function(e){const t=new dw(e),{json:i}=t;if(t.materials)for(const e of i.materials||[])e.unlit&&(delete e.unlit,t.addObjectExtension(e,"KHR_materials_unlit",{}),t.addExtension("KHR_materials_unlit"))}}),Object.freeze({__proto__:null,name:"KHR_techniques_webgl",decode:async function(e){const t=new dw(e),{json:i}=t,s=t.getExtension("KHR_techniques_webgl");if(s){const e=function(e,t){const{programs:i=[],shaders:s=[],techniques:r=[]}=e,o=new TextDecoder;return s.forEach((e=>{if(!Number.isFinite(e.bufferView))throw new Error("KHR_techniques_webgl: no shader code");e.code=o.decode(t.getTypedArrayForBufferView(e.bufferView))})),i.forEach((e=>{e.fragmentShader=s[e.fragmentShader],e.vertexShader=s[e.vertexShader]})),r.forEach((e=>{e.program=i[e.program]})),r}(s,t);for(const s of i.materials||[]){const i=t.getObjectExtension(s,"KHR_techniques_webgl");i&&(s.technique=Object.assign({},i,e[i.technique]),s.technique.values=uP(s.technique,t)),t.removeObjectExtension(s,"KHR_techniques_webgl")}t.removeExtension("KHR_techniques_webgl")}},encode:async function(e,t){}})];function pP(e,t){var i;const s=(null==t||null===(i=t.gltf)||void 0===i?void 0:i.excludeExtensions)||{};return!(e in s&&!s[e])}const fP={accessors:"accessor",animations:"animation",buffers:"buffer",bufferViews:"bufferView",images:"image",materials:"material",meshes:"mesh",nodes:"node",samplers:"sampler",scenes:"scene",skins:"skin",textures:"texture"},gP={accessor:"accessors",animations:"animation",buffer:"buffers",bufferView:"bufferViews",image:"images",material:"materials",mesh:"meshes",node:"nodes",sampler:"samplers",scene:"scenes",skin:"skins",texture:"textures"};class mP{constructor(){Zb(this,"idToIndexMap",{animations:{},accessors:{},buffers:{},bufferViews:{},images:{},materials:{},meshes:{},nodes:{},samplers:{},scenes:{},skins:{},textures:{}}),Zb(this,"json",void 0)}normalize(e,t){this.json=e.json;const i=e.json;switch(i.asset&&i.asset.version){case"2.0":return;case void 0:case"1.0":break;default:return void console.warn("glTF: Unknown version ".concat(i.asset.version))}if(!t.normalize)throw new Error("glTF v1 is not supported.");console.warn("Converting glTF v1 to glTF v2 format. This is experimental and may fail."),this._addAsset(i),this._convertTopLevelObjectsToArrays(i),function(e){const t=new dw(e),{json:i}=t;for(const e of i.images||[]){const i=t.getObjectExtension(e,"KHR_binary_glTF");i&&Object.assign(e,i),t.removeObjectExtension(e,"KHR_binary_glTF")}i.buffers&&i.buffers[0]&&delete i.buffers[0].uri,t.removeExtension("KHR_binary_glTF")}(e),this._convertObjectIdsToArrayIndices(i),this._updateObjects(i),this._updateMaterial(i)}_addAsset(e){e.asset=e.asset||{},e.asset.version="2.0",e.asset.generator=e.asset.generator||"Normalized to glTF 2.0 by loaders.gl"}_convertTopLevelObjectsToArrays(e){for(const t in fP)this._convertTopLevelObjectToArray(e,t)}_convertTopLevelObjectToArray(e,t){const i=e[t];if(i&&!Array.isArray(i)){e[t]=[];for(const s in i){const r=i[s];r.id=r.id||s;const o=e[t].length;e[t].push(r),this.idToIndexMap[t][s]=o}}}_convertObjectIdsToArrayIndices(e){for(const t in fP)this._convertIdsToIndices(e,t);"scene"in e&&(e.scene=this._convertIdToIndex(e.scene,"scene"));for(const t of e.textures)this._convertTextureIds(t);for(const t of e.meshes)this._convertMeshIds(t);for(const t of e.nodes)this._convertNodeIds(t);for(const t of e.scenes)this._convertSceneIds(t)}_convertTextureIds(e){e.source&&(e.source=this._convertIdToIndex(e.source,"image"))}_convertMeshIds(e){for(const t of e.primitives){const{attributes:e,indices:i,material:s}=t;for(const t in e)e[t]=this._convertIdToIndex(e[t],"accessor");i&&(t.indices=this._convertIdToIndex(i,"accessor")),s&&(t.material=this._convertIdToIndex(s,"material"))}}_convertNodeIds(e){e.children&&(e.children=e.children.map((e=>this._convertIdToIndex(e,"node")))),e.meshes&&(e.meshes=e.meshes.map((e=>this._convertIdToIndex(e,"mesh"))))}_convertSceneIds(e){e.nodes&&(e.nodes=e.nodes.map((e=>this._convertIdToIndex(e,"node"))))}_convertIdsToIndices(e,t){e[t]||(console.warn("gltf v1: json doesn't contain attribute ".concat(t)),e[t]=[]);for(const i of e[t])for(const e in i){const t=i[e],s=this._convertIdToIndex(t,e);i[e]=s}}_convertIdToIndex(e,t){const i=gP[t];if(i in this.idToIndexMap){const s=this.idToIndexMap[i][e];if(!Number.isFinite(s))throw new Error("gltf v1: failed to resolve ".concat(t," with id ").concat(e));return s}return e}_updateObjects(e){for(const e of this.json.buffers)delete e.type}_updateMaterial(e){for(const s of e.materials){var t,i;s.pbrMetallicRoughness={baseColorFactor:[1,1,1,1],metallicFactor:1,roughnessFactor:1};const r=(null===(t=s.values)||void 0===t?void 0:t.tex)||(null===(i=s.values)||void 0===i?void 0:i.texture2d_0),o=e.textures.findIndex((e=>e.id===r));-1!==o&&(s.pbrMetallicRoughness.baseColorTexture={index:o})}}}const _P={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},vP={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},bP=10240,yP=10241,xP=10242,BP=10243,wP=10497,PP={magFilter:bP,minFilter:yP,wrapS:xP,wrapT:BP},CP={[bP]:9729,[yP]:9986,[xP]:wP,[BP]:wP};class MP{constructor(){Zb(this,"baseUri",""),Zb(this,"json",{}),Zb(this,"buffers",[]),Zb(this,"images",[])}postProcess(e,t={}){const{json:i,buffers:s=[],images:r=[],baseUri:o=""}=e;return tw(i),this.baseUri=o,this.json=i,this.buffers=s,this.images=r,this._resolveTree(this.json,t),this.json}_resolveTree(e,t={}){e.bufferViews&&(e.bufferViews=e.bufferViews.map(((e,t)=>this._resolveBufferView(e,t)))),e.images&&(e.images=e.images.map(((e,t)=>this._resolveImage(e,t)))),e.samplers&&(e.samplers=e.samplers.map(((e,t)=>this._resolveSampler(e,t)))),e.textures&&(e.textures=e.textures.map(((e,t)=>this._resolveTexture(e,t)))),e.accessors&&(e.accessors=e.accessors.map(((e,t)=>this._resolveAccessor(e,t)))),e.materials&&(e.materials=e.materials.map(((e,t)=>this._resolveMaterial(e,t)))),e.meshes&&(e.meshes=e.meshes.map(((e,t)=>this._resolveMesh(e,t)))),e.nodes&&(e.nodes=e.nodes.map(((e,t)=>this._resolveNode(e,t)))),e.skins&&(e.skins=e.skins.map(((e,t)=>this._resolveSkin(e,t)))),e.scenes&&(e.scenes=e.scenes.map(((e,t)=>this._resolveScene(e,t)))),void 0!==e.scene&&(e.scene=e.scenes[this.json.scene])}getScene(e){return this._get("scenes",e)}getNode(e){return this._get("nodes",e)}getSkin(e){return this._get("skins",e)}getMesh(e){return this._get("meshes",e)}getMaterial(e){return this._get("materials",e)}getAccessor(e){return this._get("accessors",e)}getCamera(e){return null}getTexture(e){return this._get("textures",e)}getSampler(e){return this._get("samplers",e)}getImage(e){return this._get("images",e)}getBufferView(e){return this._get("bufferViews",e)}getBuffer(e){return this._get("buffers",e)}_get(e,t){if("object"==typeof t)return t;const i=this.json[e]&&this.json[e][t];return i||console.warn("glTF file error: Could not find ".concat(e,"[").concat(t,"]")),i}_resolveScene(e,t){return e.id=e.id||"scene-".concat(t),e.nodes=(e.nodes||[]).map((e=>this.getNode(e))),e}_resolveNode(e,t){return e.id=e.id||"node-".concat(t),e.children&&(e.children=e.children.map((e=>this.getNode(e)))),void 0!==e.mesh?e.mesh=this.getMesh(e.mesh):void 0!==e.meshes&&e.meshes.length&&(e.mesh=e.meshes.reduce(((e,t)=>{const i=this.getMesh(t);return e.id=i.id,e.primitives=e.primitives.concat(i.primitives),e}),{primitives:[]})),void 0!==e.camera&&(e.camera=this.getCamera(e.camera)),void 0!==e.skin&&(e.skin=this.getSkin(e.skin)),e}_resolveSkin(e,t){return e.id=e.id||"skin-".concat(t),e.inverseBindMatrices=this.getAccessor(e.inverseBindMatrices),e}_resolveMesh(e,t){return e.id=e.id||"mesh-".concat(t),e.primitives&&(e.primitives=e.primitives.map((e=>{const t=(e={...e}).attributes;e.attributes={};for(const i in t)e.attributes[i]=this.getAccessor(t[i]);return void 0!==e.indices&&(e.indices=this.getAccessor(e.indices)),void 0!==e.material&&(e.material=this.getMaterial(e.material)),e}))),e}_resolveMaterial(e,t){if(e.id=e.id||"material-".concat(t),e.normalTexture&&(e.normalTexture={...e.normalTexture},e.normalTexture.texture=this.getTexture(e.normalTexture.index)),e.occlusionTexture&&(e.occlustionTexture={...e.occlustionTexture},e.occlusionTexture.texture=this.getTexture(e.occlusionTexture.index)),e.emissiveTexture&&(e.emmisiveTexture={...e.emmisiveTexture},e.emissiveTexture.texture=this.getTexture(e.emissiveTexture.index)),e.emissiveFactor||(e.emissiveFactor=e.emmisiveTexture?[1,1,1]:[0,0,0]),e.pbrMetallicRoughness){e.pbrMetallicRoughness={...e.pbrMetallicRoughness};const t=e.pbrMetallicRoughness;t.baseColorTexture&&(t.baseColorTexture={...t.baseColorTexture},t.baseColorTexture.texture=this.getTexture(t.baseColorTexture.index)),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture={...t.metallicRoughnessTexture},t.metallicRoughnessTexture.texture=this.getTexture(t.metallicRoughnessTexture.index))}return e}_resolveAccessor(e,t){var i,s;if(e.id=e.id||"accessor-".concat(t),void 0!==e.bufferView&&(e.bufferView=this.getBufferView(e.bufferView)),e.bytesPerComponent=(i=e.componentType,vP[i]),e.components=(s=e.type,_P[s]),e.bytesPerElement=e.bytesPerComponent*e.components,e.bufferView){const t=e.bufferView.buffer,{ArrayType:i,byteLength:s}=cw(e,e.bufferView),r=(e.bufferView.byteOffset||0)+(e.byteOffset||0)+t.byteOffset;let o=t.arrayBuffer.slice(r,r+s);e.bufferView.byteStride&&(o=this._getValueFromInterleavedBuffer(t,r,e.bufferView.byteStride,e.bytesPerElement,e.count)),e.value=new i(o)}return e}_getValueFromInterleavedBuffer(e,t,i,s,r){const o=new Uint8Array(r*s);for(let n=0;n20);const s=t.getUint32(i+0,FP),r=t.getUint32(i+4,FP);return i+=8,Vb(0===r),DP(e,t,i,s),i+=s,i+=SP(e,t,i,e.header.byteLength)}(e,r,i);case 2:return function(e,t,i,s){return Vb(e.header.byteLength>20),function(e,t,i,s){for(;i+8<=e.header.byteLength;){const r=t.getUint32(i+0,FP),o=t.getUint32(i+4,FP);switch(i+=8,o){case 1313821514:DP(e,t,i,r);break;case 5130562:SP(e,t,i,r);break;case 0:s.strict||DP(e,t,i,r);break;case 1:s.strict||SP(e,t,i,r)}i+=by(r,4)}}(e,t,i,s),i+e.header.byteLength}(e,r,i,{});default:throw new Error("Invalid GLB version ".concat(e.version,". Only supports v1 and v2."))}}function DP(e,t,i,s){const r=new Uint8Array(t.buffer,i,s),o=new TextDecoder("utf8").decode(r);return e.json=JSON.parse(o),by(s,4)}function SP(e,t,i,s){return e.header.hasBinChunk=!0,e.binChunks.push({byteOffset:i,byteLength:s,arrayBuffer:t.buffer}),by(s,4)}async function TP(e,t,i=0,s,r){var o,n,a,l;!function(e,t,i,s){s.uri&&(e.baseUri=s.uri);if(t instanceof ArrayBuffer&&!function(e,t=0,i={}){const s=new DataView(e),{magic:r=EP}=i,o=s.getUint32(t,!1);return o===r||o===EP}(t,i,s)){t=(new TextDecoder).decode(t)}if("string"==typeof t)e.json=gy(t);else if(t instanceof ArrayBuffer){const r={};i=IP(r,t,i,s.glb),tw("glTF"===r.type,"Invalid GLB magic string ".concat(r.type)),e._glb=r,e.json=r.json}else tw(!1,"GLTF: must be ArrayBuffer or string");const r=e.json.buffers||[];if(e.buffers=new Array(r.length).fill(null),e._glb&&e._glb.header.hasBinChunk){const{binChunks:t}=e._glb;e.buffers[0]={arrayBuffer:t[0].arrayBuffer,byteOffset:t[0].byteOffset,byteLength:t[0].byteLength}}const o=e.json.images||[];e.images=new Array(o.length).fill({})}(e,t,i,s),function(e,t={}){(new mP).normalize(e,t)}(e,{normalize:null==s||null===(o=s.gltf)||void 0===o?void 0:o.normalize}),function(e,t={},i){const s=dP.filter((e=>pP(e.name,t)));for(const o of s){var r;null===(r=o.preprocess)||void 0===r||r.call(o,e,t,i)}}(e,s,r);const A=[];if(null!=s&&null!==(n=s.gltf)&&void 0!==n&&n.loadBuffers&&e.json.buffers&&await async function(e,t,i){const s=e.json.buffers||[];for(let n=0;npP(e.name,t)));for(const o of s){var r;await(null===(r=o.decode)||void 0===r?void 0:r.call(o,e,t,i))}}(e,s,r);return A.push(h),await Promise.all(A),null!=s&&null!==(l=s.gltf)&&void 0!==l&&l.postProcess?function(e,t){return(new MP).postProcess(e,t)}(e,s):e}async function RP(e,t,i,s,r){const{fetch:o,parse:n}=r;let a;if(t.uri){const e=iw(t.uri,s),i=await o(e);a=await i.arrayBuffer()}if(Number.isFinite(t.bufferView)){const i=function(e,t,i){const s=e.bufferViews[i];tw(s);const r=t[s.buffer];tw(r);const o=(s.byteOffset||0)+r.byteOffset;return new Uint8Array(r.arrayBuffer,o,s.byteLength)}(e.json,e.buffers,t.bufferView);a=vy(i.buffer,i.byteOffset,i.byteLength)}tw(a,"glTF image has no data");let l=await n(a,[ZB,RB],{mimeType:t.mimeType,basis:s.basis||{format:TB()}},r);l&&l[0]&&(l={compressed:!0,mipmaps:!1,width:l[0].width,height:l[0].height,data:l[0]}),e.images=e.images||[],e.images[i]=l}const LP={name:"glTF",id:"gltf",module:"gltf",version:"3.2.6",extensions:["gltf","glb"],mimeTypes:["model/gltf+json","model/gltf-binary"],text:!0,binary:!0,tests:["glTF"],parse:async function(e,t={},i){(t={...LP.options,...t}).gltf={...LP.options.gltf,...t.gltf};const{byteOffset:s=0}=t;return await TP({},e,s,t,i)},options:{gltf:{normalize:!0,loadBuffers:!0,loadImages:!0,decompressMeshes:!0,postProcess:!0},log:console},deprecatedOptions:{fetchImages:"gltf.loadImages",createImages:"gltf.loadImages",decompress:"gltf.decompressMeshes",postProcess:"gltf.postProcess",gltf:{decompress:"gltf.decompressMeshes"}}};class UP{constructor(e){}load(e,t,i,s,r,o,n){!function(e,t,i,s,r,o,n){const a=e.viewer.scene.canvas.spinner;a.processes++;"glb"===t.split(".").pop()?e.dataSource.getGLB(t,(n=>{s.basePath=kP(t),OP(e,t,n,i,s,r,o),a.processes--}),(e=>{a.processes--,n(e)})):e.dataSource.getGLTF(t,(n=>{s.basePath=kP(t),OP(e,t,n,i,s,r,o),a.processes--}),(e=>{a.processes--,n(e)}))}(e,t,i,s=s||{},r,(function(){I.scheduleTask((function(){r.scene.fire("modelLoaded",r.id),r.fire("loaded",!0,!1)})),o&&o()}),(function(t){e.error(t),n&&n(t),r.fire("error",t)}))}parse(e,t,i,s,r,o,n){OP(e,"",t,i,s=s||{},r,(function(){r.scene.fire("modelLoaded",r.id),r.fire("loaded",!0,!1),o&&o()}))}}function kP(e){const t=e.lastIndexOf("/");return 0!==t?e.substring(0,t+1):""}function OP(e,t,i,s,r,o,n){const a=e.viewer.scene.canvas.spinner;a.processes++,eB(i,LP,{baseUri:r.basePath}).then((i=>{const l={src:t,entityId:r.entityId,metaModelJSON:s,autoMetaModel:r.autoMetaModel,metaObjects:[],loadBuffer:r.loadBuffer,basePath:r.basePath,handlenode:r.handlenode,backfaces:!!r.backfaces,gltfData:i,scene:o.scene,plugin:e,sceneModel:o,numObjects:0,nodes:[],nextId:0,log:t=>{e.log(t)}};!function(e){const t=e.gltfData.textures;if(t)for(let i=0,s=t.length;i{const i=t.mesh;i&&(i.instances||=0,i.instances+=1),t.children&&e(t.children)}))}(s);const r=[];let o=null;!function t(i,s,n){i.forEach((i=>{const a=i.name;let l=null!=a&&a||0===s&&"entity-"+e.nextId++;if(l){for(;e.sceneModel.objects[l];)l="entity-"+e.nextId++;r.push(o),o=[]}const A=function(e,t){let i;e.matrix&&(i=e.matrix,t=t?d.mulMat4(t,i,d.mat4()):i);e.translation&&(i=d.translationMat4v(e.translation),t=t?d.mulMat4(t,i,d.mat4()):i);e.rotation&&(i=d.quaternionToMat4(e.rotation),t=t?d.mulMat4(t,i,d.mat4()):i);e.scale&&(i=d.scalingMat4v(e.scale),t=t?d.mulMat4(t,i,d.mat4()):i);return t}(i,n);i.mesh&&function(e,t,i,s){const r=e.mesh;if(!r)return;const o=r.primitives.length;if(o>0)for(let e=0;e0&&(e.sceneModel.createEntity({id:l,meshIds:o,isObject:!0}),e.autoMetaModel&&e.metaObjects.push({id:l,type:"Default",name:l,parent:e.sceneModel.id})),o=r.pop())}))}(s,0,null)}(l),o.finalize(),r.autoMetaModel&&e.viewer.metaScene.createMetaModel(o.id,{metaObjects:l.metaObjects}),a.processes--,n()}))}function NP(e,t){if(!t.source||!t.source.image)return;const i="texture-"+e.nextId++;let s=1005;switch(t.sampler.minFilter){case 9728:s=1003;break;case 9729:s=1006;break;case 9984:s=1004;break;case 9985:s=1007;break;case 9986:s=1005;break;case 9987:s=1008}let r=1006;switch(t.sampler.magFilter){case 9728:r=1003;break;case 9729:r=1006}let o=1e3;switch(t.sampler.wrapS){case 33071:o=1001;break;case 33648:o=1002;break;case 10497:o=1e3}let n=1e3;switch(t.sampler.wrapT){case 33071:n=1001;break;case 33648:n=1002;break;case 10497:n=1e3}let a=1e3;switch(t.sampler.wrapR){case 33071:a=1001;break;case 33648:a=1002;break;case 10497:a=1e3}e.sceneModel.createTexture({id:i,image:t.source.image,flipY:!!t.flipY,minFilter:s,magFilter:r,wrapS:o,wrapT:n,wrapR:a,encoding:3001}),t._textureId=i}function QP(e,t){const i={};switch(t.normalTexture&&(i.normalTextureId=t.normalTexture.texture._textureId),t.occlusionTexture&&(i.occlusionTextureId=t.occlusionTexture.texture._textureId),t.emissiveTexture&&(i.emissiveTextureId=t.emissiveTexture.texture._textureId),t.alphaMode){case"OPAQUE":break;case"MASK":const e=t.alphaCutoff;i.alphaCutoff=void 0!==e?e:.5}const s=t.pbrMetallicRoughness;if(t.pbrMetallicRoughness){const r=t.pbrMetallicRoughness,o=r.baseColorTexture||r.colorTexture;o&&(o.texture?i.colorTextureId=o.texture._textureId:i.colorTextureId=e.gltfData.textures[o.index]._textureId),s.metallicRoughnessTexture&&(i.metallicRoughnessTextureId=s.metallicRoughnessTexture.texture._textureId)}const r=t.extensions;if(r){const t=r.KHR_materials_pbrSpecularGlossiness;if(t){t.specularTexture;const s=t.specularColorTexture;null!=s&&(i.colorTextureId=e.gltfData.textures[s.index]._textureId)}}return void 0!==i.normalTextureId||void 0!==i.occlusionTextureId||void 0!==i.emissiveTextureId||void 0!==i.colorTextureId||void 0!==i.metallicRoughnessTextureId?(i.id=`textureSet-${e.nextId++};`,e.sceneModel.createTextureSet(i),i.id):null}function VP(e,t){const i=t.extensions,s={color:new Float32Array([1,1,1,1]),opacity:1,metallic:0,roughness:1,doubleSided:!0};if(i){const e=i.KHR_materials_pbrSpecularGlossiness;if(e){const t=e.diffuseFactor;null!=t&&s.color.set(t)}const t=i.KHR_materials_common;if(t){const e=t.technique,i=t.values||{},r="BLINN"===e,o="PHONG"===e,n="LAMBERT"===e,a=i.diffuse;a&&(r||o||n)&&(y.isString(a)||s.color.set(a));const l=i.transparency;null!=l&&(s.opacity=l);const A=i.transparent;null!=A&&(s.opacity=A)}}const r=t.pbrMetallicRoughness;if(r){const e=r.baseColorFactor;e&&(s.color[0]=e[0],s.color[1]=e[1],s.color[2]=e[2],s.opacity=e[3]);const t=r.metallicFactor;null!=t&&(s.metallic=t);const i=r.roughnessFactor;null!=i&&(s.roughness=i)}return s.doubleSided=!1!==t.doubleSided,s}const HP={DEFAULT:{}};class jP extends z{constructor(e,t={}){super("GLTFLoader",e,t),this._sceneModelLoader=new UP(this,t),this.dataSource=t.dataSource,this.objectDefaults=t.objectDefaults}set dataSource(e){this._dataSource=e||new pu}get dataSource(){return this._dataSource}set objectDefaults(e){this._objectDefaults=e||HP}get objectDefaults(){return this._objectDefaults}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 Gc(this.viewer.scene,y.apply(e,{isModel:!0,dtxEnabled:e.dtxEnabled})),i=t.id;if(!e.src&&!e.gltf)return this.error("load() param expected: src or gltf"),t;if(e.metaModelSrc||e.metaModelJSON){const s=s=>{this.viewer.metaScene.createMetaModel(i,s,{}),this.viewer.scene.canvas.spinner.processes--,e.src?this._sceneModelLoader.load(this,e.src,s,e,t):this._sceneModelLoader.parse(this,e.gltf,s,e,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--,s(e)}),(e=>{this.error(`load(): Failed to load model metadata for model '${i} from '${t}' - ${e}`),this.viewer.scene.canvas.spinner.processes--}))}else e.metaModelJSON&&s(e.metaModelJSON)}else e.src?this._sceneModelLoader.load(this,e.src,null,e,t):this._sceneModelLoader.parse(this,e.gltf,null,e,t);return t.once("destroyed",(()=>{this.viewer.metaScene.destroyMetaModel(i)})),t}destroy(){super.destroy()}}function GP(e,t,i={}){const s="lightgrey",r=i.hoverColor||"rgba(0,0,0,0.4)",o=i.textColor||"black",n=500,a=n+n/3,l=a/24,A=[{boundary:[6,6,6,6],color:i.frontColor||i.color||"#55FF55"},{boundary:[18,6,6,6],color:i.backColor||i.color||"#55FF55"},{boundary:[12,6,6,6],color:i.rightColor||i.color||"#FF5555"},{boundary:[0,6,6,6],color:i.leftColor||i.color||"#FF5555"},{boundary:[6,0,6,6],color:i.topColor||i.color||"#7777FF"},{boundary:[6,12,6,6],color:i.bottomColor||i.color||"#7777FF"}],h=[{label:"NavCube.front",boundaries:[[7,7,4,4]],dir:[0,1,0],up:[0,0,1]},{label:"NavCube.back",boundaries:[[19,7,4,4]],dir:[0,-1,0],up:[0,0,1]},{label:"NavCube.right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,0,1]},{label:"NavCube.left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,0,1]},{label:"NavCube.top",boundaries:[[7,1,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"NavCube.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]}];i.frontColor||i.color,i.backColor||i.color,i.rightColor||i.color,i.leftColor||i.color,i.topColor||i.color,i.bottomColor||i.color;const c=[{yUp:"",label:"NavCube.front",boundaries:[[7,7,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"NavCube.back",boundaries:[[19,7,4,4]],dir:[0,0,1],up:[0,1,0]},{label:"NavCube.right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,1,0]},{label:"NavCube.left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,1,0]},{label:"NavCube.top",boundaries:[[7,1,4,4]],dir:[0,-1,0],up:[0,0,-1]},{label:"NavCube.bottom",boundaries:[[7,13,4,4]],dir:[0,1,0],up:[0,0,1]},{boundaries:[[7,5,4,2]],dir:[0,-.7071,-.7071],up:[0,.7071,-.7071]},{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,-.7071,.7071],up:[0,.7071,.7071]},{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:[.5,.7071,-.5],up:[-.5,.7071,.5]},{boundaries:[[23,11,1,1],[6,17,1,1],[0,11,1,1]],dir:[.5,.7071,.5],up:[-.5,.7071,-.5]},{boundaries:[[5,5,2,2]],dir:[.5,-.7071,-.5],up:[.5,.7071,-.5]},{boundaries:[[11,17,1,1],[17,11,2,1]],dir:[-.5,.7071,.5],up:[.5,.7071,-.5]},{boundaries:[[17,6,2,1],[11,0,1,1]],dir:[-.5,-.7071,.5],up:[-.5,.7071,.5]},{boundaries:[[11,11,2,2]],dir:[-.5,.7071,-.5],up:[.5,.7071,.5]},{boundaries:[[0,6,1,1],[6,0,1,1],[23,6,1,1]],dir:[.5,-.7071,.5],up:[.5,.7071,.5]},{boundaries:[[11,5,2,2]],dir:[-.5,-.7071,-.5],up:[-.5,.7071,-.5]}];for(let e=0,t=h.length;e=r[0]*l&&t<=(r[0]+r[2])*l&&i>=r[1]*l&&i<=(r[1]+r[3])*l)return s}}return-1},this.setAreaHighlighted=function(e,t){var i=u[e];if(!i)throw"Area not found: "+e;i.highlighted=!!t,g()},this.getAreaDir=function(e){var t=u[e];if(!t)throw"Unknown area: "+e;return t.dir},this.getAreaUp=function(e){var t=u[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)}}const zP=d.vec3(),WP=d.vec3();d.mat4();class KP extends z{constructor(e,t={}){super("NavCube",e,t),e.navCube=this;try{this._navCubeScene=new vi(e,{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 Vt(i,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new Vt(i,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new Vt(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,i.edgeMaterial.edgeColor=[.2,.2,.2],i.edgeMaterial.edgeAlpha=.6,this._zUp=Boolean(e.camera.zUp);var s=this;this.setIsProjectNorth(t.isProjectNorth),this.setProjectNorthOffsetAngle(t.projectNorthOffsetAngle);const r=function(){const e=d.mat4();return function(t,i,r){return d.identityMat4(e),d.rotationMat4v(t*s._projectNorthOffsetAngle*d.DEGTORAD,[0,1,0],e),d.transformVec3(e,i,r)}}();this._synchCamera=function(){var t=d.rotationMat4c(-90*d.DEGTORAD,1,0,0),i=d.vec3(),o=d.vec3(),n=d.vec3();return function(){var a=e.camera.eye,l=e.camera.look,A=e.camera.up;i=d.mulVec3Scalar(d.normalizeVec3(d.subVec3(a,l,i)),5),s._isProjectNorth&&s._projectNorthOffsetAngle&&(i=r(-1,i,zP),A=r(-1,A,WP)),s._zUp?(d.transformVec3(t,i,o),d.transformVec3(t,A,n),s._navCubeCamera.look=[0,0,0],s._navCubeCamera.eye=d.transformVec3(t,i,o),s._navCubeCamera.up=d.transformPoint3(t,A,n)):(s._navCubeCamera.look=[0,0,0],s._navCubeCamera.eye=i,s._navCubeCamera.up=A)}}(),this._cubeTextureCanvas=new GP(e,i,t),this._cubeSampler=new so(i,{image:this._cubeTextureCanvas.getImage(),flipY:!0,wrapS:1001,wrapT:1001}),this._cubeMesh=new wr(i,{geometry:new ei(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 oi(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=!1===t.shadowVisible?null:new wr(i,{geometry:new ei(i,Cr({center:[0,0,0],radiusTop:.001,radiusBottom:1.4,height:.01,radialSegments:20,heightSegments:1,openEnded:!0})),material:new oi(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="ortho"===e||"perspective"===e?e:"perspective")}));var o=-1;function n(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 a,l,A=null,h=null,c=!1,u=!1,p=.5;s._navCubeCanvas.addEventListener("mouseenter",s._onMouseEnter=function(e){u=!0}),s._navCubeCanvas.addEventListener("mouseleave",s._onMouseLeave=function(e){u=!1}),s._navCubeCanvas.addEventListener("mousedown",s._onMouseDown=function(e){if(1===e.which){A=e.x,h=e.y,a=e.clientX,l=e.clientY;var t=n(e),s=i.pick({canvasPos:t});c=!!s}}),document.addEventListener("mouseup",s._onMouseUp=function(e){if(1===e.which&&(c=!1,null!==A)){var t=n(e),a=i.pick({canvasPos:t,pickSurface:!0});if(a&&a.uv){var l=s._cubeTextureCanvas.getArea(a.uv);if(l>=0&&(document.body.style.cursor="pointer",o>=0&&(s._cubeTextureCanvas.setAreaHighlighted(o,!1),s._repaint(),o=-1),l>=0)){if(s._cubeTextureCanvas.setAreaHighlighted(l,!0),o=l,s._repaint(),e.xA+3||e.yh+3)return;var u=s._cubeTextureCanvas.getAreaDir(l);if(u){var d=s._cubeTextureCanvas.getAreaUp(l);s._isProjectNorth&&s._projectNorthOffsetAngle&&(u=r(1,u,zP),d=r(1,d,WP)),f(u,d,(function(){o>=0&&(s._cubeTextureCanvas.setAreaHighlighted(o,!1),s._repaint(),o=-1),document.body.style.cursor="pointer",o>=0&&(s._cubeTextureCanvas.setAreaHighlighted(o,!1),s._repaint(),o=-1),l>=0&&(s._cubeTextureCanvas.setAreaHighlighted(l,!1),o=-1,s._repaint())}))}}}}}),document.addEventListener("mousemove",s._onMouseMove=function(t){if(o>=0&&(s._cubeTextureCanvas.setAreaHighlighted(o,!1),s._repaint(),o=-1),1!==t.buttons||c){if(c){var r=t.clientX,A=t.clientY;return document.body.style.cursor="move",void function(t,i){var s=(t-a)*-p,r=(i-l)*-p;e.camera.orbitYaw(s),e.camera.orbitPitch(-r),a=t,l=i}(r,A)}if(u){var h=n(t),d=i.pick({canvasPos:h,pickSurface:!0});if(d){if(d.uv){document.body.style.cursor="pointer";var f=s._cubeTextureCanvas.getArea(d.uv);if(f===o)return;o>=0&&s._cubeTextureCanvas.setAreaHighlighted(o,!1),f>=0&&(s._cubeTextureCanvas.setAreaHighlighted(f,!0),s._repaint(),o=f)}}else document.body.style.cursor="default",o>=0&&(s._cubeTextureCanvas.setAreaHighlighted(o,!1),s._repaint(),o=-1)}}});var f=function(){var t=d.vec3();return function(i,r,o){var n=s._fitVisible?e.scene.getAABB(e.scene.visibleObjectIds):e.scene.aabb,a=d.getAABB3Diag(n);d.getAABB3Center(n,t);var l=Math.abs(a/Math.tan(s._cameraFitFOV*d.DEGTORAD));e.cameraControl.pivotPos=t,s._cameraFly?e.cameraFlight.flyTo({look:t,eye:[t[0]-l*i[0],t[1]-l*i[1],t[2]-l*i[2]],up:r||[0,1,0],orthoScale:1.1*a,fitFOV:s._cameraFitFOV,duration:s._cameraFlyDuration},o):e.cameraFlight.jumpTo({look:t,eye:[t[0]-l*i[0],t[1]-l*i[1],t[2]-l*i[2]],up:r||[0,1,0],orthoScale:1.1*a,fitFOV:s._cameraFitFOV},o)}}();this._onUpdated=e.localeService.on("updated",(()=>{this._cubeTextureCanvas.clear(),this._repaint()})),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){if("language"===e)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&&(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}setIsProjectNorth(e=!1){this._isProjectNorth=e}getIsProjectNorth(){return this._isProjectNorth}setProjectNorthOffsetAngle(e){this._projectNorthOffsetAngle=e}getProjectNorthOffsetAngle(){return this._projectNorthOffsetAngle}destroy(){this._navCubeCanvas&&(this.viewer.localeService.off(this._onUpdated),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()}}const XP=d.vec3();class JP{load(e,t,i={}){var s=e.scene.canvas.spinner;s.processes++,YP(e,t,(function(t){!function(e,t,i){for(var s=t.basePath,r=Object.keys(t.materialLibraries),o=r.length,n=0,a=o;n=0?i-1:i+t/3)}function r(e,t){var i=parseInt(e,10);return 3*(i>=0?i-1:i+t/3)}function o(e,t){var i=parseInt(e,10);return 2*(i>=0?i-1:i+t/2)}function n(e,t,i,s){var r=e.positions,o=e.object.geometry.positions;o.push(r[t+0]),o.push(r[t+1]),o.push(r[t+2]),o.push(r[i+0]),o.push(r[i+1]),o.push(r[i+2]),o.push(r[s+0]),o.push(r[s+1]),o.push(r[s+2])}function a(e,t){var i=e.positions,s=e.object.geometry.positions;s.push(i[t+0]),s.push(i[t+1]),s.push(i[t+2])}function l(e,t,i,s){var r=e.normals,o=e.object.geometry.normals;o.push(r[t+0]),o.push(r[t+1]),o.push(r[t+2]),o.push(r[i+0]),o.push(r[i+1]),o.push(r[i+2]),o.push(r[s+0]),o.push(r[s+1]),o.push(r[s+2])}function A(e,t,i,s){var r=e.uv,o=e.object.geometry.uv;o.push(r[t+0]),o.push(r[t+1]),o.push(r[i+0]),o.push(r[i+1]),o.push(r[s+0]),o.push(r[s+1])}function h(e,t){var i=e.uv,s=e.object.geometry.uv;s.push(i[t+0]),s.push(i[t+1])}function c(e,t,i,a,h,c,u,d,p,f,g,m,_){var v,b=e.positions.length,y=s(t,b),x=s(i,b),B=s(a,b);if(void 0===h?n(e,y,x,B):(n(e,y,x,v=s(h,b)),n(e,x,B,v)),void 0!==c){var w=e.uv.length;y=o(c,w),x=o(u,w),B=o(d,w),void 0===h?A(e,y,x,B):(A(e,y,x,v=o(p,w)),A(e,x,B,v))}if(void 0!==f){var P=e.normals.length;y=r(f,P),x=f===g?y:r(g,P),B=f===m?y:r(m,P),void 0===h?l(e,y,x,B):(l(e,y,x,v=r(_,P)),l(e,x,B,v))}}function u(e,t,i){e.object.geometry.type="Line";for(var r=e.positions.length,n=e.uv.length,l=0,A=t.length;l=0?n.substring(0,a):n).toLowerCase(),A=(A=a>=0?n.substring(a+1):"").trim(),l.toLowerCase()){case"newmtl":i(e,u),u={id:A},d=!0;break;case"ka":u.ambient=s(A);break;case"kd":u.diffuse=s(A);break;case"ks":u.specular=s(A);break;case"map_kd":u.diffuseMap||(u.diffuseMap=t(e,o,A,"sRGB"));break;case"map_ks":u.specularMap||(u.specularMap=t(e,o,A,"linear"));break;case"map_bump":case"bump":u.normalMap||(u.normalMap=t(e,o,A));break;case"ns":u.shininess=parseFloat(A);break;case"d":(h=parseFloat(A))<1&&(u.alpha=h,u.alphaMode="blend");break;case"tr":(h=parseFloat(A))>0&&(u.alpha=1-h,u.alphaMode="blend")}d&&i(e,u)};function t(e,t,i,s){var r={},o=i.split(/\s+/),n=o.indexOf("-bm");return n>=0&&o.splice(n,2),(n=o.indexOf("-s"))>=0&&(r.scale=[parseFloat(o[n+1]),parseFloat(o[n+2])],o.splice(n,4)),(n=o.indexOf("-o"))>=0&&(r.translate=[parseFloat(o[n+1]),parseFloat(o[n+2])],o.splice(n,4)),r.src=t+o.join(" ").trim(),r.flipY=!0,r.encoding=s||"linear",new so(e,r).id}function i(e,t){new oi(e,t)}function s(t){var i=t.split(e,3);return[parseFloat(i[0]),parseFloat(i[1]),parseFloat(i[2])]}}();function eC(e,t){for(var i=0,s=t.objects.length;i0&&(n.normals=o.normals),o.uv.length>0&&(n.uv=o.uv);for(var a=new Array(n.positions.length/3),l=0;l{this.viewer.metaScene.createMetaModel(i,r),this._sceneGraphLoader.load(t,s,e)}),(e=>{this.error(`load(): Failed to load model modelMetadata for model '${i} from '${r}' - ${e}`)}))}else this._sceneGraphLoader.load(t,s,e);return t.once("destroyed",(()=>{this.viewer.metaScene.destroyMetaModel(i)})),t}destroy(){super.destroy()}}const sC=new Float64Array([0,0,1]),rC=new Float64Array(4);class oC{constructor(e){this.id=null,this._viewer=e.viewer,this._visible=!1,this._pos=d.vec3(),this._origin=d.vec3(),this._rtcPos=d.vec3(),this._baseDir=d.vec3(),this._rootNode=null,this._displayMeshes=null,this._affordanceMeshes=null,this._ignoreNextSectionPlaneDirUpdate=!1,this._createNodes(),this._bindEvents()}_setSectionPlane(e){this._sectionPlane&&(this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._onSectionPlanePos=null,this._onSectionPlaneDir=null,this._sectionPlane=null),e&&(this.id=e.id,this._setPos(e.pos),this._setDir(e.dir),this._sectionPlane=e,this._onSectionPlanePos=e.on("pos",(()=>{this._setPos(this._sectionPlane.pos)})),this._onSectionPlaneDir=e.on("dir",(()=>{this._ignoreNextSectionPlaneDirUpdate?this._ignoreNextSectionPlaneDirUpdate=!1:this._setDir(this._sectionPlane.dir)})))}get sectionPlane(){return this._sectionPlane}_setPos(e){this._pos.set(e),Y(this._pos,this._origin,this._rtcPos),this._rootNode.origin=this._origin,this._rootNode.position=this._rtcPos}_setDir(e){this._baseDir.set(e),this._rootNode.quaternion=d.vec3PairToQuaternion(sC,e,rC)}_setSectionPlaneDir(e){this._sectionPlane&&(this._ignoreNextSectionPlaneDirUpdate=!0,this._sectionPlane.dir=e)}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=!1,t=this._viewer.scene,i=.01;this._rootNode=new Vr(t,{position:[0,0,0],scale:[5,5,5],isObject:!1});const s=this._rootNode,r={arrowHead:new ei(s,Cr({radiusTop:.001,radiusBottom:.07,radialSegments:32,heightSegments:1,height:.2,openEnded:!1})),arrowHeadBig:new ei(s,Cr({radiusTop:.001,radiusBottom:.09,radialSegments:32,heightSegments:1,height:.25,openEnded:!1})),arrowHeadHandle:new ei(s,Cr({radiusTop:.09,radiusBottom:.09,radialSegments:8,heightSegments:1,height:.37,openEnded:!1})),curve:new ei(s,go({radius:.8,tube:i,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),curveHandle:new ei(s,go({radius:.8,tube:.06,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),hoop:new ei(s,go({radius:.8,tube:i,radialSegments:64,tubeSegments:8,arc:2*Math.PI})),axis:new ei(s,Cr({radiusTop:i,radiusBottom:i,radialSegments:20,heightSegments:1,height:1,openEnded:!1})),axisHandle:new ei(s,Cr({radiusTop:.08,radiusBottom:.08,radialSegments:20,heightSegments:1,height:1,openEnded:!1}))},o={pickable:new oi(s,{diffuse:[1,1,0],alpha:0,alphaMode:"blend"}),red:new oi(s,{diffuse:[1,0,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightRed:new ai(s,{edges:!1,fill:!0,fillColor:[1,0,0],fillAlpha:.6}),green:new oi(s,{diffuse:[0,1,0],emissive:[0,1,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightGreen:new ai(s,{edges:!1,fill:!0,fillColor:[0,1,0],fillAlpha:.6}),blue:new oi(s,{diffuse:[0,0,1],emissive:[0,0,1],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightBlue:new ai(s,{edges:!1,fill:!0,fillColor:[0,0,1],fillAlpha:.2}),center:new oi(s,{diffuse:[0,0,0],emissive:[0,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80}),highlightBall:new ai(s,{edges:!1,fill:!0,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1}),highlightPlane:new ai(s,{edges:!0,edgeWidth:3,fill:!1,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1})};this._displayMeshes={plane:s.addChild(new wr(s,{geometry:new ei(s,{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 oi(s,{emissive:[0,0,0],diffuse:[0,0,0],backfaces:!0}),opacity:.6,ghosted:!0,ghostMaterial:new ai(s,{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],isObject:!1}),e),planeFrame:s.addChild(new wr(s,{geometry:new ei(s,go({center:[0,0,0],radius:1.7,tube:.02,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new oi(s,{emissive:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],shininess:0}),highlightMaterial:new ai(s,{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],isObject:!1}),e),xCurve:s.addChild(new wr(s,{geometry:r.curve,material:o.red,matrix:function(){const e=d.rotationMat4v(90*d.DEGTORAD,[0,1,0],d.identityMat4()),t=d.rotationMat4v(270*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xCurveHandle:s.addChild(new wr(s,{geometry:r.curveHandle,material:o.pickable,matrix:function(){const e=d.rotationMat4v(90*d.DEGTORAD,[0,1,0],d.identityMat4()),t=d.rotationMat4v(270*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xCurveArrow1:s.addChild(new wr(s,{geometry:r.arrowHead,material:o.red,matrix:function(){const e=d.translateMat4c(0,-.07,-.8,d.identityMat4()),t=d.scaleMat4v([.6,.6,.6],d.identityMat4()),i=d.rotationMat4v(0*d.DEGTORAD,[0,0,1],d.identityMat4());return d.mulMat4(d.mulMat4(e,t,d.identityMat4()),i,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xCurveArrow2:s.addChild(new wr(s,{geometry:r.arrowHead,material:o.red,matrix:function(){const e=d.translateMat4c(0,-.8,-.07,d.identityMat4()),t=d.scaleMat4v([.6,.6,.6],d.identityMat4()),i=d.rotationMat4v(90*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(d.mulMat4(e,t,d.identityMat4()),i,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yCurve:s.addChild(new wr(s,{geometry:r.curve,material:o.green,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),yCurveHandle:s.addChild(new wr(s,{geometry:r.curveHandle,material:o.pickable,rotation:[-90,0,0],pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),yCurveArrow1:s.addChild(new wr(s,{geometry:r.arrowHead,material:o.green,matrix:function(){const e=d.translateMat4c(.07,0,-.8,d.identityMat4()),t=d.scaleMat4v([.6,.6,.6],d.identityMat4()),i=d.rotationMat4v(90*d.DEGTORAD,[0,0,1],d.identityMat4());return d.mulMat4(d.mulMat4(e,t,d.identityMat4()),i,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yCurveArrow2:s.addChild(new wr(s,{geometry:r.arrowHead,material:o.green,matrix:function(){const e=d.translateMat4c(.8,0,-.07,d.identityMat4()),t=d.scaleMat4v([.6,.6,.6],d.identityMat4()),i=d.rotationMat4v(90*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(d.mulMat4(e,t,d.identityMat4()),i,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurve:s.addChild(new wr(s,{geometry:r.curve,material:o.blue,matrix:d.rotationMat4v(180*d.DEGTORAD,[1,0,0],d.identityMat4()),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveHandle:s.addChild(new wr(s,{geometry:r.curveHandle,material:o.pickable,matrix:d.rotationMat4v(180*d.DEGTORAD,[1,0,0],d.identityMat4()),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveCurveArrow1:s.addChild(new wr(s,{geometry:r.arrowHead,material:o.blue,matrix:function(){const e=d.translateMat4c(.8,-.07,0,d.identityMat4()),t=d.scaleMat4v([.6,.6,.6],d.identityMat4());return d.mulMat4(e,t,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveArrow2:s.addChild(new wr(s,{geometry:r.arrowHead,material:o.blue,matrix:function(){const e=d.translateMat4c(.05,-.8,0,d.identityMat4()),t=d.scaleMat4v([.6,.6,.6],d.identityMat4()),i=d.rotationMat4v(90*d.DEGTORAD,[0,0,1],d.identityMat4());return d.mulMat4(d.mulMat4(e,t,d.identityMat4()),i,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),center:s.addChild(new wr(s,{geometry:new ei(s,Mr({radius:.05})),material:o.center,pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisArrow:s.addChild(new wr(s,{geometry:r.arrowHead,material:o.red,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[0,0,1],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisArrowHandle:s.addChild(new wr(s,{geometry:r.arrowHeadHandle,material:o.pickable,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[0,0,1],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxis:s.addChild(new wr(s,{geometry:r.axis,material:o.red,matrix:function(){const e=d.translateMat4c(0,.5,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[0,0,1],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisHandle:s.addChild(new wr(s,{geometry:r.axisHandle,material:o.pickable,matrix:function(){const e=d.translateMat4c(0,.5,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[0,0,1],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrow:s.addChild(new wr(s,{geometry:r.arrowHead,material:o.green,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(180*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrowHandle:s.addChild(new wr(s,{geometry:r.arrowHeadHandle,material:o.pickable,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(180*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,opacity:.2,isObject:!1}),e),yShaft:s.addChild(new wr(s,{geometry:r.axis,material:o.green,position:[0,-.5,0],pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yShaftHandle:s.addChild(new wr(s,{geometry:r.axisHandle,material:o.pickable,position:[0,-.5,0],pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrow:s.addChild(new wr(s,{geometry:r.arrowHead,material:o.blue,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[.8,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrowHandle:s.addChild(new wr(s,{geometry:r.arrowHeadHandle,material:o.pickable,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[.8,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zShaft:s.addChild(new wr(s,{geometry:r.axis,material:o.blue,matrix:function(){const e=d.translateMat4c(0,.5,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),clippable:!1,pickable:!1,collidable:!0,visible:!1,isObject:!1}),e),zAxisHandle:s.addChild(new wr(s,{geometry:r.axisHandle,material:o.pickable,matrix:function(){const e=d.translateMat4c(0,.5,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),clippable:!1,pickable:!0,collidable:!0,visible:!1,isObject:!1}),e)},this._affordanceMeshes={planeFrame:s.addChild(new wr(s,{geometry:new ei(s,go({center:[0,0,0],radius:2,tube:i,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new oi(s,{ambient:[1,1,1],diffuse:[0,0,0],emissive:[1,1,0]}),highlighted:!0,highlightMaterial:new ai(s,{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],isObject:!1}),e),xHoop:s.addChild(new wr(s,{geometry:r.hoop,material:o.red,highlighted:!0,highlightMaterial:o.highlightRed,matrix:function(){const e=d.rotationMat4v(90*d.DEGTORAD,[0,1,0],d.identityMat4()),t=d.rotationMat4v(270*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yHoop:s.addChild(new wr(s,{geometry:r.hoop,material:o.green,highlighted:!0,highlightMaterial:o.highlightGreen,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zHoop:s.addChild(new wr(s,{geometry:r.hoop,material:o.blue,highlighted:!0,highlightMaterial:o.highlightBlue,matrix:d.rotationMat4v(180*d.DEGTORAD,[1,0,0],d.identityMat4()),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xAxisArrow:s.addChild(new wr(s,{geometry:r.arrowHeadBig,material:o.red,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[0,0,1],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrow:s.addChild(new wr(s,{geometry:r.arrowHeadBig,material:o.green,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(180*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrow:s.addChild(new wr(s,{geometry:r.arrowHeadBig,material:o.blue,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[.8,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e)}}_bindEvents(){const e=this;var t=!1;const i=-1,s=0,r=1,o=2,n=3,a=4,l=5,A=this._rootNode;var h=null,c=null;const u=d.vec2(),p=d.vec3([1,0,0]),f=d.vec3([0,1,0]),g=d.vec3([0,0,1]),m=this._viewer.scene.canvas.canvas,_=this._viewer.camera,v=this._viewer.scene;{const e=d.vec3([0,0,0]);let t=-1;this._onCameraViewMatrix=v.camera.on("viewMatrix",(()=>{})),this._onCameraProjMatrix=v.camera.on("projMatrix",(()=>{})),this._onSceneTick=v.on("tick",(()=>{const i=Math.abs(d.lenVec3(d.subVec3(v.camera.eye,this._pos,e)));if(i!==t&&"perspective"===_.projection){const e=.07*(Math.tan(_.perspective.fov*d.DEGTORAD)*i);A.scale=[e,e,e],t=i}if("ortho"===_.projection){const e=_.ortho.scale/10;A.scale=[e,e,e],t=i}}))}const b=function(){const e=new Float64Array(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}}(),y=function(){const t=d.mat4();return function(i,s){return d.quaternionToMat4(e._rootNode.quaternion,t),d.transformVec3(t,i,s),d.normalizeVec3(s),s}}();var x=function(){const e=d.vec3();return function(t){const i=Math.abs(t[0]);return i>Math.abs(t[1])&&i>Math.abs(t[2])?d.cross3Vec3(t,[0,1,0],e):d.cross3Vec3(t,[1,0,0],e),d.cross3Vec3(e,t,e),d.normalizeVec3(e),e}}();const B=function(){const t=d.vec3(),i=d.vec3(),s=d.vec4();return function(r,o,n){y(r,s);const a=x(s,o,n);P(o,a,t),P(n,a,i),d.subVec3(i,t);const l=d.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 w=function(){const t=d.vec4(),i=d.vec4(),s=d.vec4(),r=d.vec4();return function(o,n,a){y(o,r);if(!(P(n,r,t)&&P(a,r,i))){const e=x(r,n,a);P(n,e,t,1),P(a,e,i,1);var l=d.dotVec3(t,r);t[0]-=l*r[0],t[1]-=l*r[1],t[2]-=l*r[2],l=d.dotVec3(i,r),i[0]-=l*r[0],i[1]-=l*r[1],i[2]-=l*r[2]}d.normalizeVec3(t),d.normalizeVec3(i),l=d.dotVec3(t,i),l=d.clamp(l,-1,1);var A=Math.acos(l)*d.RADTODEG;d.cross3Vec3(t,i,s),d.dotVec3(s,r)<0&&(A=-A),e._rootNode.rotate(o,A),C()}}(),P=function(){const t=d.vec4([0,0,0,1]),i=d.mat4();return function(s,r,o,n){n=n||0,t[0]=s[0]/m.width*2-1,t[1]=-(s[1]/m.height*2-1),t[2]=0,t[3]=1,d.mulMat4(_.projMatrix,_.viewMatrix,i),d.inverseMat4(i),d.transformVec4(i,t,t),d.mulVec4Scalar(t,1/t[3]);var a=_.eye;d.subVec4(t,a,t);const l=e._sectionPlane.pos;var A=-d.dotVec3(l,r)-n,h=d.dotVec3(r,t);if(Math.abs(h)>.005){var c=-(d.dotVec3(r,a)+A)/h;return d.mulVec3Scalar(t,c,o),d.addVec3(o,a),d.subVec3(o,l,o),!0}return!1}}();const C=function(){const t=d.vec3(),i=d.mat4();return function(){e.sectionPlane&&(d.quaternionToMat4(A.quaternion,i),d.transformVec3(i,[0,0,1],t),e._setSectionPlaneDir(t))}}();var M,E=!1;this._onCameraControlHover=this._viewer.cameraControl.on("hoverEnter",(e=>{if(!this._visible)return;if(E)return;var A;t=!1,M&&(M.visible=!1);switch(e.entity.id){case this._displayMeshes.xAxisArrowHandle.id:case this._displayMeshes.xAxisHandle.id:A=this._affordanceMeshes.xAxisArrow,h=s;break;case this._displayMeshes.yAxisArrowHandle.id:case this._displayMeshes.yShaftHandle.id:A=this._affordanceMeshes.yAxisArrow,h=r;break;case this._displayMeshes.zAxisArrowHandle.id:case this._displayMeshes.zAxisHandle.id:A=this._affordanceMeshes.zAxisArrow,h=o;break;case this._displayMeshes.xCurveHandle.id:A=this._affordanceMeshes.xHoop,h=n;break;case this._displayMeshes.yCurveHandle.id:A=this._affordanceMeshes.yHoop,h=a;break;case this._displayMeshes.zCurveHandle.id:A=this._affordanceMeshes.zHoop,h=l;break;default:return void(h=i)}A&&(A.visible=!0),M=A,t=!0})),this._onCameraControlHoverLeave=this._viewer.cameraControl.on("hoverOutEntity",(e=>{this._visible&&(M&&(M.visible=!1),M=null,h=i)})),m.addEventListener("mousedown",this._canvasMouseDownListener=e=>{if(e.preventDefault(),this._visible&&t&&(this._viewer.cameraControl.pointerEnabled=!1,1===e.which)){E=!0;var i=b(e);c=h,u[0]=i[0],u[1]=i[1]}}),m.addEventListener("mousemove",this._canvasMouseMoveListener=e=>{if(!this._visible)return;if(!E)return;var t=b(e);const i=t[0],A=t[1];switch(c){case s:B(p,u,t);break;case r:B(f,u,t);break;case o:B(g,u,t);break;case n:w(p,u,t);break;case a:w(f,u,t);break;case l:w(g,u,t)}u[0]=i,u[1]=A}),m.addEventListener("mouseup",this._canvasMouseUpListener=e=>{this._visible&&(this._viewer.cameraControl.pointerEnabled=!0,E&&(e.which,E=!1,t=!1))}),m.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._setSectionPlane(null),this._rootNode.destroy(),this._displayMeshes={},this._affordanceMeshes={}}}class nC{constructor(e,t,i){this.id=i.id,this._sectionPlane=i,this._mesh=new wr(t,{id:i.id,geometry:new ei(t,ti({xSize:.5,ySize:.5,zSize:.001})),material:new oi(t,{emissive:[1,1,1],diffuse:[0,0,0],backfaces:!1}),edgeMaterial:new Ai(t,{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),highlightMaterial:new ai(t,{fill:!0,fillColor:[.5,1,.5],fillAlpha:.7,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),selectedMaterial:new ai(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=d.vec3([0,0,0]),t=d.vec3(),i=d.vec3([0,0,1]),s=d.vec4(4),r=d.vec3(),o=()=>{const o=this._sectionPlane.scene.center,n=[-this._sectionPlane.dir[0],-this._sectionPlane.dir[1],-this._sectionPlane.dir[2]];d.subVec3(o,this._sectionPlane.pos,e);const a=-d.dotVec3(n,e);d.normalizeVec3(n),d.mulVec3Scalar(n,a,t);const l=d.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 aC{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 vi(this._viewer,{canvasId:this._canvas.id,transparent:!0}),this._scene.clearLights(),new Vt(this._scene,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new Vt(this._scene,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new Vt(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=d.rotationMat4c(-90*d.DEGTORAD,1,0,0),i=d.vec3(),s=d.vec3(),r=d.vec3();this._synchCamera=()=>{const o=this._viewer.camera.eye,n=this._viewer.camera.look,a=this._viewer.camera.up;d.mulVec3Scalar(d.normalizeVec3(d.subVec3(o,n,i)),7),this._zUp?(d.transformVec3(t,i,s),d.transformVec3(t,a,r),e.look=[0,0,0],e.eye=d.transformVec3(t,i,s),e.up=d.transformPoint3(t,a,r)):(e.look=[0,0,0],e.eye=i,e.up=a)}}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}));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 nC(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._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 lC=d.AABB3(),AC=d.vec3();class hC extends z{constructor(e,t={}){if(super("SectionPlanes",e),this._freeControls=[],this._sectionPlanes=e.scene.sectionPlanes,this._controls={},this._shownControlId=null,null!==t.overviewCanvasId&&void 0!==t.overviewCanvasId){const e=document.getElementById(t.overviewCanvasId);e?this._overview=new aC(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;lC.set(this.viewer.scene.aabb),d.getAABB3Center(lC,AC),lC[0]+=t[0]-AC[0],lC[1]+=t[1]-AC[1],lC[2]+=t[2]-AC[2],lC[3]+=t[0]-AC[0],lC[4]+=t[1]-AC[1],lC[5]+=t[2]-AC[2],this.viewer.cameraFlight.flyTo({aabb:lC,fitFOV:65})},onClickedNothing:()=>{this.hideControl()}}):this.warn("Can't find overview canvas: '"+t.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={}){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);return new Dr(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 oC(this);t._setSectionPlane(e),t.setVisible(!1),this._controls[e.id]=t,this._overview&&this._overview.addSectionPlane(e),e.once("destroyed",(()=>{this._sectionPlaneDestroyed(e)}))}flipSectionPlanes(){const e=this.viewer.scene.sectionPlanes;for(let t in e){e[t].flipDir()}}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{this._registerModelStoreys(e),this.fire("storeys",this.storeys)}))}_registerModelStoreys(e){const t=this.viewer,i=t.scene,s=t.metaScene,r=s.metaModels[e],o=i.models[e];if(!r||!r.rootMetaObjects)return;const n=r.rootMetaObjects;for(let t=0,r=n.length;t.5?a.length:0,h=new cC(this,o.aabb,l,e,n,A);h._onModelDestroyed=o.once("destroyed",(()=>{this._deregisterModelStoreys(e),this.fire("storeys",this.storeys)})),this.storeys[n]=h,this.modelStoreys[e]||(this.modelStoreys[e]={}),this.modelStoreys[e][n]=h}}}_deregisterModelStoreys(e){const t=this.modelStoreys[e];if(t){const i=this.viewer.scene;for(let e in t)if(t.hasOwnProperty(e)){const s=t[e],r=i.models[s.modelId];r&&r.off(s._onModelDestroyed),delete this.storeys[e]}delete this.modelStoreys[e]}}get fitStoreyMaps(){return this._fitStoreyMaps}gotoStoreyCamera(e,t={}){const i=this.storeys[e];if(!i)return this.error("IfcBuildingStorey not found with this ID: "+e),void(t.done&&t.done());const s=this.viewer,r=s.scene.camera,o=i.storeyAABB;if(o[3]{t.done()})):(s.cameraFlight.jumpTo(y.apply(t,{eye:h,look:n,up:c,orthoScale:A})),s.camera.ortho.scale=A)}showStoreyObjects(e,t={}){if(!this.storeys[e])return void this.error("IfcBuildingStorey not found with this ID: "+e);const i=this.viewer,s=i.scene;i.metaScene.metaObjects[e]&&(t.hideOthers&&s.setObjectsVisible(i.scene.visibleObjectIds,!1),this.withStoreyObjects(e,((e,t)=>{e&&(e.visible=!0)})))}withStoreyObjects(e,t){const i=this.viewer,s=i.scene,r=i.metaScene,o=r.metaObjects[e];if(!o)return;const n=o.getObjectIDsInSubtree();for(var a=0,l=n.length;athis.storeys[i[1]].storeyAABB[4]?i[1]:null}worldPosToStoreyMap(e,t,i){const s=e.storeyId,r=this.storeys[s];if(!r)return this.error("IfcBuildingStorey not found with this ID: "+s),!1;const o=this._fitStoreyMaps?r.storeyAABB:r.modelAABB,n=o[0],a=o[1],l=o[2],A=o[3]-n,h=o[4]-a,c=o[5]-l,u=this.viewer.camera.worldUp,d=u[0]>u[1]&&u[0]>u[2],p=!d&&u[1]>u[0]&&u[1]>u[2];!d&&!p&&u[2]>u[0]&&(u[2],u[1]);const f=e.width/A,g=p?e.height/c:e.height/h;return i[0]=Math.floor(e.width-(t[0]-n)*f),i[1]=Math.floor(e.height-(t[2]-l)*g),i[0]>=0&&i[0]=0&&i[1]<=e.height}worldDirToStoreyMap(e,t,i){const s=this.viewer.camera,r=s.eye,o=s.look,n=d.subVec3(o,r,dC),a=s.worldUp,l=a[0]>a[1]&&a[0]>a[2],A=!l&&a[1]>a[0]&&a[1]>a[2];!l&&!A&&a[2]>a[0]&&(a[2],a[1]),l?(i[0]=n[1],i[1]=n[2]):A?(i[0]=n[0],i[1]=n[2]):(i[0]=n[0],i[1]=n[1]),d.normalizeVec2(i)}destroy(){this.viewer.scene.off(this._onModelLoaded),super.destroy()}}const gC=new Float64Array([0,0,1]),mC=new Float64Array(4);class _C{constructor(e){this.id=null,this._viewer=e.viewer,this._plugin=e,this._visible=!1,this._pos=d.vec3(),this._origin=d.vec3(),this._rtcPos=d.vec3(),this._baseDir=d.vec3(),this._rootNode=null,this._displayMeshes=null,this._affordanceMeshes=null,this._ignoreNextSectionPlaneDirUpdate=!1,this._createNodes(),this._bindEvents()}_setSectionPlane(e){this._sectionPlane&&(this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._onSectionPlanePos=null,this._onSectionPlaneDir=null,this._sectionPlane=null),e&&(this.id=e.id,this._setPos(e.pos),this._setDir(e.dir),this._sectionPlane=e,this._onSectionPlanePos=e.on("pos",(()=>{this._setPos(this._sectionPlane.pos)})),this._onSectionPlaneDir=e.on("dir",(()=>{this._ignoreNextSectionPlaneDirUpdate?this._ignoreNextSectionPlaneDirUpdate=!1:this._setDir(this._sectionPlane.dir)})))}get sectionPlane(){return this._sectionPlane}_setPos(e){this._pos.set(e),Y(this._pos,this._origin,this._rtcPos),this._rootNode.origin=this._origin,this._rootNode.position=this._rtcPos}_setDir(e){this._baseDir.set(e),this._rootNode.quaternion=d.vec3PairToQuaternion(gC,e,mC)}_setSectionPlaneDir(e){this._sectionPlane&&(this._ignoreNextSectionPlaneDirUpdate=!0,this._sectionPlane.dir=e)}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=!1,t=this._viewer.scene,i=.01;this._rootNode=new Vr(t,{position:[0,0,0],scale:[5,5,5]});const s=this._rootNode,r={arrowHead:new ei(s,Cr({radiusTop:.001,radiusBottom:.07,radialSegments:32,heightSegments:1,height:.2,openEnded:!1})),arrowHeadBig:new ei(s,Cr({radiusTop:.001,radiusBottom:.09,radialSegments:32,heightSegments:1,height:.25,openEnded:!1})),axis:new ei(s,Cr({radiusTop:i,radiusBottom:i,radialSegments:20,heightSegments:1,height:1,openEnded:!1}))},o={red:new oi(s,{diffuse:[1,0,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),green:new oi(s,{diffuse:[0,1,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),blue:new oi(s,{diffuse:[0,0,1],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightRed:new ai(s,{edges:!1,fill:!0,fillColor:[1,0,0],fillAlpha:.6})};this._displayMeshes={plane:s.addChild(new wr(s,{geometry:new ei(s,{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 oi(s,{emissive:[0,0,0],diffuse:[0,0,0],backfaces:!0}),opacity:.6,ghosted:!0,pickable:!1,collidable:!0,clippable:!1,visible:!1,scale:[2.4,2.4,1]}),e),planeFrame:s.addChild(new wr(s,{geometry:new ei(s,go({center:[0,0,0],radius:1.7,tube:.02,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new oi(s,{emissive:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],shininess:0}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,.1],rotation:[0,0,45]}),e),center:s.addChild(new wr(s,{geometry:new ei(s,Mr({radius:.05})),material:o.center,pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),zAxisArrow:s.addChild(new wr(s,{geometry:r.arrowHead,material:o.blue,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[.8,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),zShaft:s.addChild(new wr(s,{geometry:r.axis,material:o.blue,matrix:function(){const e=d.translateMat4c(0,.5,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),clippable:!1,pickable:!1,collidable:!0,visible:!1}),e)},this._affordanceMeshes={planeFrame:s.addChild(new wr(s,{geometry:new ei(s,go({center:[0,0,0],radius:2,tube:i,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new oi(s,{ambient:[1,1,1],diffuse:[0,0,0],emissive:[1,1,0]}),highlighted:!0,highlightMaterial:new ai(s,{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]}),e),zAxisArrow:s.addChild(new wr(s,{geometry:r.arrowHeadBig,material:o.blue,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[.8,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e)}}_bindEvents(){const e=this._rootNode,t=d.vec2(),i=this._viewer.camera,s=this._viewer.scene;let r=0,o=!1;{const t=d.vec3([0,0,0]);let n=-1;this._onCameraViewMatrix=s.camera.on("viewMatrix",(()=>{})),this._onCameraProjMatrix=s.camera.on("projMatrix",(()=>{})),this._onSceneTick=s.on("tick",(()=>{o=!1;const l=Math.abs(d.lenVec3(d.subVec3(s.camera.eye,this._pos,t)));if(l!==n&&"perspective"===i.projection){const t=.07*(Math.tan(i.perspective.fov*d.DEGTORAD)*l);e.scale=[t,t,t],n=l}if("ortho"===i.projection){const t=i.ortho.scale/10;e.scale=[t,t,t],n=l}0!==r&&(a(r),r=0)}))}const n=function(){const e=new Float64Array(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}}(),a=e=>{const t=this._sectionPlane.pos,i=this._sectionPlane.dir;d.addVec3(t,d.mulVec3Scalar(i,.1*e*this._plugin.getDragSensitivity(),d.vec3())),this._sectionPlane.pos=t};{let e=!1;this._plugin._controlElement.addEventListener("mousedown",this._canvasMouseDownListener=i=>{if(i.preventDefault(),this._visible&&(this._viewer.cameraControl.pointerEnabled=!1,1===i.which)){e=!0;var s=n(i);t[0]=s[0],t[1]=s[1]}}),this._plugin._controlElement.addEventListener("mousemove",this._canvasMouseMoveListener=i=>{if(!this._visible)return;if(!e)return;if(o)return;var s=n(i);const r=s[0],l=s[1];a(l-t[1]),t[0]=r,t[1]=l}),this._plugin._controlElement.addEventListener("mouseup",this._canvasMouseUpListener=t=>{this._visible&&(this._viewer.cameraControl.pointerEnabled=!0,e&&(t.which,e=!1))}),this._plugin._controlElement.addEventListener("wheel",this._canvasWheelListener=e=>{this._visible&&(r+=Math.max(-1,Math.min(1,40*-e.deltaY)))})}{let e,t,i=null;this._plugin._controlElement.addEventListener("touchstart",this._handleTouchStart=t=>{t.stopPropagation(),t.preventDefault(),this._visible&&(e=t.touches[0].clientY,i=e,r=0)}),this._plugin._controlElement.addEventListener("touchmove",this._handleTouchMove=e=>{e.stopPropagation(),e.preventDefault(),this._visible&&(o||(o=!0,t=e.touches[0].clientY,null!==i&&(r+=t-i),i=t))}),this._plugin._controlElement.addEventListener("touchend",this._handleTouchEnd=i=>{i.stopPropagation(),i.preventDefault(),this._visible&&(e=null,t=null,r=0)})}}_destroy(){this._unbindEvents(),this._destroyNodes()}_unbindEvents(){const e=this._viewer,t=e.scene,i=t.canvas.canvas,s=e.camera,r=this._plugin._controlElement;t.off(this._onSceneTick),i.removeEventListener("mousedown",this._canvasMouseDownListener),i.removeEventListener("mousemove",this._canvasMouseMoveListener),i.removeEventListener("mouseup",this._canvasMouseUpListener),i.removeEventListener("wheel",this._canvasWheelListener),r.removeEventListener("touchstart",this._handleTouchStart),r.removeEventListener("touchmove",this._handleTouchMove),r.removeEventListener("touchend",this._handleTouchEnd),s.off(this._onCameraViewMatrix),s.off(this._onCameraProjMatrix)}_destroyNodes(){this._setSectionPlane(null),this._rootNode.destroy(),this._displayMeshes={},this._affordanceMeshes={}}}class vC{constructor(e,t,i){this.id=i.id,this._sectionPlane=i,this._mesh=new wr(t,{id:i.id,geometry:new ei(t,ti({xSize:.5,ySize:.5,zSize:.001})),material:new oi(t,{emissive:[1,1,1],diffuse:[0,0,0],backfaces:!1}),edgeMaterial:new Ai(t,{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),highlightMaterial:new ai(t,{fill:!0,fillColor:[.5,1,.5],fillAlpha:.7,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),selectedMaterial:new ai(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=d.vec3([0,0,0]),t=d.vec3(),i=d.vec3([0,0,1]),s=d.vec4(4),r=d.vec3(),o=()=>{const o=this._sectionPlane.scene.center,n=[-this._sectionPlane.dir[0],-this._sectionPlane.dir[1],-this._sectionPlane.dir[2]];d.subVec3(o,this._sectionPlane.pos,e);const a=-d.dotVec3(n,e);d.normalizeVec3(n),d.mulVec3Scalar(n,a,t);const l=d.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 bC{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 vi(this._viewer,{canvasId:this._canvas.id,transparent:!0}),this._scene.clearLights(),new Vt(this._scene,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new Vt(this._scene,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new Vt(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=d.rotationMat4c(-90*d.DEGTORAD,1,0,0),i=d.vec3(),s=d.vec3(),r=d.vec3();this._synchCamera=()=>{const o=this._viewer.camera.eye,n=this._viewer.camera.look,a=this._viewer.camera.up;d.mulVec3Scalar(d.normalizeVec3(d.subVec3(o,n,i)),7),this._zUp?(d.transformVec3(t,i,s),d.transformVec3(t,a,r),e.look=[0,0,0],e.eye=d.transformVec3(t,i,s),e.up=d.transformPoint3(t,a,r)):(e.look=[0,0,0],e.eye=i,e.up=a)}}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}));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 vC(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._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 yC=d.AABB3(),xC=d.vec3();class BC extends z{constructor(e,t={}){if(super("FaceAlignedSectionPlanesPlugin",e),this._freeControls=[],this._sectionPlanes=e.scene.sectionPlanes,this._controls={},this._shownControlId=null,this._dragSensitivity=t.dragSensitivity||1,null!==t.overviewCanvasId&&void 0!==t.overviewCanvasId){const e=document.getElementById(t.overviewCanvasId);e?this._overview=new bC(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;yC.set(this.viewer.scene.aabb),d.getAABB3Center(yC,xC),yC[0]+=t[0]-xC[0],yC[1]+=t[1]-xC[1],yC[2]+=t[2]-xC[2],yC[3]+=t[0]-xC[0],yC[4]+=t[1]-xC[1],yC[5]+=t[2]-xC[2],this.viewer.cameraFlight.flyTo({aabb:yC,fitFOV:65})},onClickedNothing:()=>{this.hideControl()}}):this.warn("Can't find overview canvas: '"+t.overviewCanvasId+"' - will create plugin without overview")}null===t.controlElementId||void 0===t.controlElementId?this.error("Parameter expected: controlElementId"):(this._controlElement=document.getElementById(t.controlElementId),this._controlElement||this.warn("Can't find control element: '"+t.controlElementId+"' - will create plugin without control element")),this._onSceneSectionPlaneCreated=e.scene.on("sectionPlaneCreated",(e=>{this._sectionPlaneCreated(e)}))}setDragSensitivity(e){this._dragSensitivity=e||1}getDragSensitivity(){return this._dragSensitivity}setOverviewVisible(e){this._overview&&this._overview.setVisible(e)}getOverviewVisible(){if(this._overview)return this._overview.getVisible()}get sectionPlanes(){return this._sectionPlanes}createSectionPlane(e={}){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);return new Dr(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 _C(this);t._setSectionPlane(e),t.setVisible(!1),this._controls[e.id]=t,this._overview&&this._overview.addSectionPlane(e),e.once("destroyed",(()=>{this._sectionPlaneDestroyed(e)}))}flipSectionPlanes(){const e=this.viewer.scene.sectionPlanes;for(let t in e){e[t].flipDir()}}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(let 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){let 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(let t=0,i=e.length;t-1?e+"&_="+t:e+"?_="+t}getSTL(e,t,i){e=this._cacheBusterURL(e);const s=new XMLHttpRequest;s.overrideMimeType("application/json"),s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i(s.statusText))},s.send(null)}}const CC=d.vec3();class MC{load(e,t,i,s,r,o){s=s||{};const n=e.viewer.scene.canvas.spinner;n.processes++,e.dataSource.getSTL(i,(function(i){!function(e,t,i,s){try{const r=TC(i);EC(r)?FC(e,r,t,s):IC(e,SC(i),t,s)}catch(e){t.fire("error",e)}}(e,t,i,s);try{const o=TC(i);EC(o)?FC(e,o,t,s):IC(e,SC(i),t,s),n.processes--,I.scheduleTask((function(){t.fire("loaded",!0,!1)})),r&&r()}catch(i){n.processes--,e.error(i),o&&o(i),t.fire("error",i)}}),(function(i){n.processes--,e.error(i),o&&o(i),t.fire("error",i)}))}parse(e,t,i,s){const r=e.viewer.scene.canvas.spinner;r.processes++;try{const o=TC(i);EC(o)?FC(e,o,t,s):IC(e,SC(i),t,s),r.processes--,I.scheduleTask((function(){t.fire("loaded",!0,!1)}))}catch(e){r.processes--,t.fire("error",e)}}}function EC(e){const t=new DataView(e);if(84+50*t.getUint32(80,!0)===t.byteLength)return!0;const i=[115,111,108,105,100];for(var s=0;s<5;s++)if(i[s]!==t.getUint8(s,!1))return!0;return!1}function FC(e,t,i,s){const r=new DataView(t),o=r.getUint32(80,!0);let n,a,l,A,h,c,u,d=!1,p=null,f=null,g=null,m=!1;for(let e=0;e<70;e++)1129270351===r.getUint32(e,!1)&&82===r.getUint8(e+4)&&61===r.getUint8(e+5)&&(d=!0,A=[],h=r.getUint8(e+6)/255,c=r.getUint8(e+7)/255,u=r.getUint8(e+8)/255,r.getUint8(e+9));const _=new zr(i,{roughness:.5});let v=[],b=[],y=s.splitMeshes;for(let e=0;e>5&31)/31,l=(e>>10&31)/31):(n=h,a=c,l=u),(y&&n!==p||a!==f||l!==g)&&(null!==p&&(m=!0),p=n,f=a,g=l)}for(let e=1;e<=3;e++){let i=t+12*e;v.push(r.getFloat32(i,!0)),v.push(r.getFloat32(i+4,!0)),v.push(r.getFloat32(i+8,!0)),b.push(o,x,B),d&&A.push(n,a,l,1)}y&&m&&(DC(i,v,b,A,_,s),v=[],b=[],A=A?[]:null,m=!1)}v.length>0&&DC(i,v,b,A,_,s)}function IC(e,t,i,s){const r=/facet([\s\S]*?)endfacet/g;let o=0;const n=/[\s]+([+-]?(?:\d+.\d+|\d+.|\d+|.\d+)(?:[eE][+-]?\d+)?)/.source,a=new RegExp("vertex"+n+n+n,"g"),l=new RegExp("normal"+n+n+n,"g"),A=[],h=[];let c,u,d,p,f,g,m;for(;null!==(p=r.exec(t));){for(f=0,g=0,m=p[0];null!==(p=l.exec(m));)c=parseFloat(p[1]),u=parseFloat(p[2]),d=parseFloat(p[3]),g++;for(;null!==(p=a.exec(m));)A.push(parseFloat(p[1]),parseFloat(p[2]),parseFloat(p[3])),h.push(c,u,d),f++;1!==g&&e.error("Error in normal of face "+o),3!==f&&e.error("Error in positions of face "+o),o++}DC(i,A,h,null,new zr(i,{roughness:.5}),s)}function DC(e,t,i,s,r,o){const n=new Int32Array(t.length/3);for(let e=0,t=n.length;e0?i:null,s=s&&s.length>0?s:null,o.smoothNormals&&d.faceToVertexNormals(t,i,o);const a=CC;Z(t,t,a);const l=new ei(e,{primitive:"triangles",positions:t,normals:i,colors:s,indices:n}),A=new wr(e,{origin:0!==a[0]||0!==a[1]||0!==a[2]?a:null,geometry:l,material:r,edges:o.edges});e.addChild(A)}function SC(e){return"string"!=typeof e?function(e){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let i=0,s=e.length;i0){const i=document.createElement("a");i.href="#",i.id=`switch-${e.nodeId}`,i.textContent="+",i.classList.add("plus"),t&&i.addEventListener("click",t),o.appendChild(i)}const n=document.createElement("input");n.id=`checkbox-${e.nodeId}`,n.type="checkbox",n.checked=e.checked,n.style["pointer-events"]="all",i&&n.addEventListener("change",i),o.appendChild(n);const a=document.createElement("span");return a.textContent=e.title,o.appendChild(a),s&&(a.oncontextmenu=s),r&&(a.onclick=r),o}createDisabledNodeElement(e){const t=document.createElement("li"),i=document.createElement("a");i.href="#",i.textContent="!",i.classList.add("warn"),i.classList.add("warning"),t.appendChild(i);const s=document.createElement("span");return s.textContent=e,t.appendChild(s),t}addChildren(e,t){const i=document.createElement("ul");t.forEach((e=>{i.appendChild(e)})),e.parentElement.appendChild(i)}expand(e,t,i){e.classList.remove("plus"),e.classList.add("minus"),e.textContent="-",e.removeEventListener("click",t),e.addEventListener("click",i)}collapse(e,t,i){if(!e)return;const s=e.parentElement;if(!s)return;const r=s.querySelector("ul");r&&(s.removeChild(r),e.classList.remove("minus"),e.classList.add("plus"),e.textContent="+",e.removeEventListener("click",i),e.addEventListener("click",t))}isExpanded(e){return void 0!==e.parentElement.getElementsByTagName("li")[0]}getId(e){return e.parentElement.id}getIdFromCheckbox(e){return e.id.replace("checkbox-","")}getSwitchElement(e){return document.getElementById(`switch-${e}`)}isChecked(e){return e.checked}setCheckbox(e,t,i=!1){const s=document.getElementById(`checkbox-${e}`);s&&(t!==s.checked&&(s.checked=t),i!==s.indeterminate&&(s.indeterminate=i,i&&(s.checked=!1)))}setXRayed(e,t){const i=document.getElementById(e);i&&(t?i.classList.add("xrayed-node"):i.classList.remove("xrayed-node"))}setHighlighted(e,t){const i=document.getElementById(e);i&&(t?(i.scrollIntoView({block:"center"}),i.classList.add("highlighted-node")):i.classList.remove("highlighted-node"))}}const UC=[];class kC extends z{constructor(e,t={}){super("TreeViewPlugin",e),this.errors=[],this.valid=!0;const i=t.containerElement||document.getElementById(t.containerElementId);if(i instanceof HTMLElement){for(let e=0;;e++)if(!UC[e]){UC[e]=this,this._index=e,this._id=`tree-${e}`;break}if(this._containerElement=i,this._metaModels={},this._autoAddModels=!1!==t.autoAddModels,this._autoExpandDepth=t.autoExpandDepth||0,this._sortNodes=!1!==t.sortNodes,this._viewer=e,this._rootElement=null,this._muteSceneEvents=!1,this._muteTreeEvents=!1,this._rootNodes=[],this._objectNodes={},this._nodeNodes={},this._rootNames={},this._sortNodes=t.sortNodes,this._pruneEmptyNodes=t.pruneEmptyNodes,this._showListItemElementId=null,this._renderService=t.renderService||new LC,this._showIndeterminate=t.showIndeterminate??!1,!this._renderService)throw new Error("TreeViewPlugin: no render service set");if(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--,this._renderService.setCheckbox(i.nodeId,s);let r=i.parent;for(;r;){r.checked=s,s?r.numVisibleEntities++:r.numVisibleEntities--;const e=this._showIndeterminate&&r.numVisibleEntities>0&&r.numVisibleEntities0,e),r=r.parent}this._muteTreeEvents=!1})),this._onObjectXrayed=this._viewer.scene.on("objectXRayed",(e=>{if(this._muteSceneEvents)return;const t=e.id,i=this._objectNodes[t];if(!i)return;this._muteTreeEvents=!0;const s=e.xrayed;s!==i.xrayed&&(i.xrayed=s,this._renderService.setXRayed(i.nodeId,s),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=this._renderService.isChecked(t),s=this._renderService.getIdFromCheckbox(t),r=this._nodeNodes[s],o=this._viewer.scene.objects;let n=0;this._withNodeTree(r,(e=>{const t=e.objectId,s=o[t],r=0===e.children.length;e.numVisibleEntities=i?e.numEntities:0,r&&i!==e.checked&&n++,e.checked=i,this._renderService.setCheckbox(e.nodeId,i),s&&(s.visible=i)}));let a=r.parent;for(;a;){a.checked=i,i?a.numVisibleEntities+=n:a.numVisibleEntities-=n;const e=this._showIndeterminate&&a.numVisibleEntities>0&&a.numVisibleEntities0,e),a=a.parent}this._muteSceneEvents=!1},this._hierarchy=t.hierarchy||"containment",this._autoExpandDepth=t.autoExpandDepth||0,this._autoAddModels){const e=Object.keys(this.viewer.metaScene.metaModels);for(let t=0,i=e.length;t{this.viewer.metaScene.metaModels[e]&&this.addModel(e)}))}this.hierarchy=t.hierarchy}else this.error("Mandatory config expected: valid containerElementId or 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&&(this._hierarchy=e,this._createNodes())}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._metaModels[e]?this.warn("Model already added: "+e):(this._metaModels[e]=s,t&&t.rootName&&(this._rootNames[e]=t.rootName),i.on("destroyed",(()=>{this.removeModel(i.id)})),this._createNodes()):this.error("MetaModel not found: "+e)}removeModel(e){if(!this._containerElement)return;this._metaModels[e]&&(this._rootNames[e]&&delete this._rootNames[e],delete this._metaModels[e],this._createNodes())}showNode(e){this.unShowNode();const t=this._objectNodes[e];if(!t)return;this.collapse();const i=t.nodeId,s=this._renderService.getSwitchElement(i);if(s)return this._expandSwitchElement(s),s.scrollIntoView(),!0;const r=[];r.unshift(t);let o=t.parent;for(;o;)r.unshift(o),o=o.parent;for(let e=0,t=r.length;e{if(s===e)return;const r=this._renderService.getSwitchElement(i.nodeId);if(r){this._expandSwitchElement(r);const e=i.children;for(var o=0,n=e.length;o0;return this.valid}_validateMetaModelForStoreysHierarchy(e=0,t,i){return!0}_createEnabledNodes(){switch(this._pruneEmptyNodes&&this._findEmptyNodes(),this._hierarchy){case"storeys":this._createStoreysNodes(),0===this._rootNodes.length&&this.error("Failed to build storeys hierarchy");break;case"types":this._createTypesNodes();break;default:this._createContainmentNodes()}this._sortNodes&&this._doSortNodes(),this._synchNodesToEntities(),this._createTrees(),this.expandToDepth(this._autoExpandDepth)}_createDisabledNodes(){const e=this._renderService.createRootNode();this._rootElement=e,this._containerElement.appendChild(e);const t=this._viewer.metaScene.rootMetaObjects;for(let i in t){const s=t[i],r=s.type,o=s.name,n=o&&""!==o&&"Undefined"!==o&&"Default"!==o?o:r,a=this._renderService.createDisabledNodeElement(n);e.appendChild(a)}}_findEmptyNodes(){const e=this._viewer.metaScene.rootMetaObjects;for(let t in e)this._findEmptyNodes2(e[t])}_findEmptyNodes2(e,t=0){const i=this.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{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]s?1:0}_synchNodesToEntities(){const e=Object.keys(this.viewer.metaScene.metaObjects),t=this._viewer.metaScene.metaObjects,i=this._viewer.scene.objects;for(let s=0,r=e.length;sthis._createNodeElement(e))),t=this._renderService.createRootNode();e.forEach((e=>{t.appendChild(e)})),this._containerElement.appendChild(t),this._rootElement=t}_createNodeElement(e){return this._renderService.createNodeElement(e,this._switchExpandHandler,this._checkboxChangeHandler,(t=>{this.fire("contextmenu",{event:t,viewer:this._viewer,treeViewPlugin:this,treeViewNode:e}),t.preventDefault()}),(t=>{this.fire("nodeTitleClicked",{event:t,viewer:this._viewer,treeViewPlugin:this,treeViewNode:e}),t.preventDefault()}))}_expandSwitchElement(e){if(this._renderService.isExpanded(e))return;const t=this._renderService.getId(e),i=this._nodeNodes[t].children.map((e=>this._createNodeElement(e)));this._renderService.addChildren(e,i),this._renderService.expand(e,this._switchExpandHandler,this._switchCollapseHandler)}_collapseNode(e){const t=this._renderService.getSwitchElement(e);this._collapseSwitchElement(t)}_collapseSwitchElement(e){this._renderService.collapse(e,this._switchExpandHandler,this._switchCollapseHandler)}}class OC{constructor(e){this._scene=e,this._objects=[],this._objectsViewCulled=[],this._objectsDetailCulled=[],this._objectsChanged=[],this._objectsChangedList=[],this._modelInfos={},this._numObjects=0,this._lenObjectsChangedList=0,this._dirty=!0,this._onModelLoaded=e.on("modelLoaded",(t=>{const i=e.models[t];i&&this._addModel(i)})),this._onTick=e.on("tick",(()=>{this._dirty&&this._build(),this._applyChanges()}))}_addModel(e){const t={model:e,onDestroyed:e.on("destroyed",(()=>{this._removeModel(e)}))};this._modelInfos[e.id]=t,this._dirty=!0}_removeModel(e){const t=this._modelInfos[e.id];t&&(t.model.off(t.onDestroyed),delete this._modelInfos[e.id],this._dirty=!0)}_build(){if(!this._dirty)return;this._applyChanges();const e=this._scene.objects;for(let e=0;e0){for(let e=0;e{delete NC[t],i._destroy()}))),i}(e.scene),this._maxTreeDepth=t.maxTreeDepth||8,this._modelInfos={},this._frustum=new N,this._kdRoot=null,this._frustumDirty=!1,this._kdTreeDirty=!1,this._onViewMatrix=e.scene.camera.on("viewMatrix",(()=>{this._frustumDirty=!0})),this._onProjMatrix=e.scene.camera.on("projMatMatrix",(()=>{this._frustumDirty=!0})),this._onModelLoaded=e.scene.on("modelLoaded",(e=>{const t=this.viewer.scene.models[e];t&&this._addModel(t)})),this._onSceneTick=e.scene.on("tick",(()=>{this._doCull()}))}set enabled(e){this._enabled=e}get enabled(){return this._enabled}_addModel(e){const t={model:e,onDestroyed:e.on("destroyed",(()=>{this._removeModel(e)}))};this._modelInfos[e.id]=t,this._kdTreeDirty=!0}_removeModel(e){const t=this._modelInfos[e.id];t&&(t.model.off(t.onDestroyed),delete this._modelInfos[e.id],this._kdTreeDirty=!0)}_doCull(){const e=this._frustumDirty||this._kdTreeDirty;if(this._frustumDirty&&this._buildFrustum(),this._kdTreeDirty&&this._buildKDTree(),e){const e=this._kdRoot;e&&this._visitKDNode(e)}}_buildFrustum(){const e=this.viewer.scene.camera;Q(this._frustum,e.viewMatrix,e.projMatrix),this._frustumDirty=!1}_buildKDTree(){const e=this.viewer.scene;this._kdRoot,this._kdRoot={aabb:e.getAABB(),intersection:N.INTERSECT};for(let e=0,t=this._objectCullStates.numObjects;e=this._maxTreeDepth)return e.objects=e.objects||[],e.objects.push(i),void d.expandAABB3(e.aabb,r);if(e.left&&d.containsAABB3(e.left.aabb,r))return void this._insertEntityIntoKDTree(e.left,t,i,s+1);if(e.right&&d.containsAABB3(e.right.aabb,r))return void this._insertEntityIntoKDTree(e.right,t,i,s+1);const o=e.aabb;QC[0]=o[3]-o[0],QC[1]=o[4]-o[1],QC[2]=o[5]-o[2];let n=0;if(QC[1]>QC[n]&&(n=1),QC[2]>QC[n]&&(n=2),!e.left){const a=o.slice();if(a[n+3]=(o[n]+o[n+3])/2,e.left={aabb:a,intersection:N.INTERSECT},d.containsAABB3(a,r))return void this._insertEntityIntoKDTree(e.left,t,i,s+1)}if(!e.right){const a=o.slice();if(a[n]=(o[n]+o[n+3])/2,e.right={aabb:a,intersection:N.INTERSECT},d.containsAABB3(a,r))return void this._insertEntityIntoKDTree(e.right,t,i,s+1)}e.objects=e.objects||[],e.objects.push(i),d.expandAABB3(e.aabb,r)}_visitKDNode(e,t=N.INTERSECT){if(t!==N.INTERSECT&&e.intersects===t)return;t===N.INTERSECT&&(t=V(this._frustum,e.aabb),e.intersects=t);const i=t===N.OUTSIDE,s=e.objects;if(s&&s.length>0)for(let e=0,t=s.length;e-1?e+"&_="+t:e+"?_="+t}getManifest(e,t,i){y.loadJSON(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getMetaModel(e,t,i){y.loadJSON(this._cacheBusterURL(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),i=new Uint8Array(e);for(var n=0;n=0;)e[t]=0}const i=new Uint8Array([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]),s=new Uint8Array([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]),r=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),o=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),n=new Array(576);t(n);const a=new Array(60);t(a);const l=new Array(512);t(l);const A=new Array(256);t(A);const h=new Array(29);t(h);const c=new Array(30);function u(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}let d,p,f;function g(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}t(c);const m=e=>e<256?l[e]:l[256+(e>>>7)],_=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},v=(e,t,i)=>{e.bi_valid>16-i?(e.bi_buf|=t<>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<{v(e,i[2*t],i[2*t+1])},y=(e,t)=>{let i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1},x=(e,t,i)=>{const s=new Array(16);let r,o,n=0;for(r=1;r<=15;r++)n=n+i[r-1]<<1,s[r]=n;for(o=0;o<=t;o++){let t=e[2*o+1];0!==t&&(e[2*o]=y(s[t]++,t))}},B=e=>{let t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},w=e=>{e.bi_valid>8?_(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},P=(e,t,i,s)=>{const r=2*t,o=2*i;return e[r]{const s=e.heap[i];let r=i<<1;for(;r<=e.heap_len&&(r{let o,n,a,l,u=0;if(0!==e.sym_next)do{o=255&e.pending_buf[e.sym_buf+u++],o+=(255&e.pending_buf[e.sym_buf+u++])<<8,n=e.pending_buf[e.sym_buf+u++],0===o?b(e,n,t):(a=A[n],b(e,a+256+1,t),l=i[a],0!==l&&(n-=h[a],v(e,n,l)),o--,a=m(o),b(e,a,r),l=s[a],0!==l&&(o-=c[a],v(e,o,l)))}while(u{const i=t.dyn_tree,s=t.stat_desc.static_tree,r=t.stat_desc.has_stree,o=t.stat_desc.elems;let n,a,l,A=-1;for(e.heap_len=0,e.heap_max=573,n=0;n>1;n>=1;n--)C(e,i,n);l=o;do{n=e.heap[1],e.heap[1]=e.heap[e.heap_len--],C(e,i,1),a=e.heap[1],e.heap[--e.heap_max]=n,e.heap[--e.heap_max]=a,i[2*l]=i[2*n]+i[2*a],e.depth[l]=(e.depth[n]>=e.depth[a]?e.depth[n]:e.depth[a])+1,i[2*n+1]=i[2*a+1]=l,e.heap[1]=l++,C(e,i,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const i=t.dyn_tree,s=t.max_code,r=t.stat_desc.static_tree,o=t.stat_desc.has_stree,n=t.stat_desc.extra_bits,a=t.stat_desc.extra_base,l=t.stat_desc.max_length;let A,h,c,u,d,p,f=0;for(u=0;u<=15;u++)e.bl_count[u]=0;for(i[2*e.heap[e.heap_max]+1]=0,A=e.heap_max+1;A<573;A++)h=e.heap[A],u=i[2*i[2*h+1]+1]+1,u>l&&(u=l,f++),i[2*h+1]=u,h>s||(e.bl_count[u]++,d=0,h>=a&&(d=n[h-a]),p=i[2*h],e.opt_len+=p*(u+d),o&&(e.static_len+=p*(r[2*h+1]+d)));if(0!==f){do{for(u=l-1;0===e.bl_count[u];)u--;e.bl_count[u]--,e.bl_count[u+1]+=2,e.bl_count[l]--,f-=2}while(f>0);for(u=l;0!==u;u--)for(h=e.bl_count[u];0!==h;)c=e.heap[--A],c>s||(i[2*c+1]!==u&&(e.opt_len+=(u-i[2*c+1])*i[2*c],i[2*c+1]=u),h--)}})(e,t),x(i,A,e.bl_count)},F=(e,t,i)=>{let s,r,o=-1,n=t[1],a=0,l=7,A=4;for(0===n&&(l=138,A=3),t[2*(i+1)+1]=65535,s=0;s<=i;s++)r=n,n=t[2*(s+1)+1],++a{let s,r,o=-1,n=t[1],a=0,l=7,A=4;for(0===n&&(l=138,A=3),s=0;s<=i;s++)if(r=n,n=t[2*(s+1)+1],!(++a{v(e,0+(s?1:0),3),w(e),_(e,i),_(e,~i),i&&e.pending_buf.set(e.window.subarray(t,t+i),e.pending),e.pending+=i};var T={_tr_init:e=>{D||((()=>{let e,t,o,g,m;const _=new Array(16);for(o=0,g=0;g<28;g++)for(h[g]=o,e=0;e<1<>=7;g<30;g++)for(c[g]=m<<7,e=0;e<1<{let r,l,A=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0})(e)),E(e,e.l_desc),E(e,e.d_desc),A=(e=>{let t;for(F(e,e.dyn_ltree,e.l_desc.max_code),F(e,e.dyn_dtree,e.d_desc.max_code),E(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*o[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t})(e),r=e.opt_len+3+7>>>3,l=e.static_len+3+7>>>3,l<=r&&(r=l)):r=l=i+5,i+4<=r&&-1!==t?S(e,t,i,s):4===e.strategy||l===r?(v(e,2+(s?1:0),3),M(e,n,a)):(v(e,4+(s?1:0),3),((e,t,i,s)=>{let r;for(v(e,t-257,5),v(e,i-1,5),v(e,s-4,4),r=0;r(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(A[i]+256+1)]++,e.dyn_dtree[2*m(t)]++),e.sym_next===e.sym_end),_tr_align:e=>{v(e,2,3),b(e,256,n),(e=>{16===e.bi_valid?(_(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)}},R=(e,t,i,s)=>{let r=65535&e|0,o=e>>>16&65535|0,n=0;for(;0!==i;){n=i>2e3?2e3:i,i-=n;do{r=r+t[s++]|0,o=o+r|0}while(--n);r%=65521,o%=65521}return r|o<<16|0};const L=new Uint32Array((()=>{let e,t=[];for(var 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})());var U=(e,t,i,s)=>{const r=L,o=s+i;e^=-1;for(let i=s;i>>8^r[255&(e^t[i])];return-1^e},k={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"},O={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_MEM_ERROR:-4,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};const{_tr_init:N,_tr_stored_block:Q,_tr_flush_block:V,_tr_tally:H,_tr_align:j}=T,{Z_NO_FLUSH:G,Z_PARTIAL_FLUSH:z,Z_FULL_FLUSH:W,Z_FINISH:K,Z_BLOCK:X,Z_OK:J,Z_STREAM_END:Y,Z_STREAM_ERROR:Z,Z_DATA_ERROR:q,Z_BUF_ERROR:$,Z_DEFAULT_COMPRESSION:ee,Z_FILTERED:te,Z_HUFFMAN_ONLY:ie,Z_RLE:se,Z_FIXED:re,Z_DEFAULT_STRATEGY:oe,Z_UNKNOWN:ne,Z_DEFLATED:ae}=O,le=258,Ae=262,he=42,ce=113,ue=666,de=(e,t)=>(e.msg=k[t],t),pe=e=>2*e-(e>4?9:0),fe=e=>{let t=e.length;for(;--t>=0;)e[t]=0},ge=e=>{let t,i,s,r=e.w_size;t=e.hash_size,s=t;do{i=e.head[--s],e.head[s]=i>=r?i-r:0}while(--t);t=r,s=t;do{i=e.prev[--s],e.prev[s]=i>=r?i-r:0}while(--t)};let me=(e,t,i)=>(t<{const t=e.state;let i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,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))},ve=(e,t)=>{V(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,_e(e.strm)},be=(e,t)=>{e.pending_buf[e.pending++]=t},ye=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},xe=(e,t,i,s)=>{let r=e.avail_in;return r>s&&(r=s),0===r?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),i),1===e.state.wrap?e.adler=R(e.adler,t,r,i):2===e.state.wrap&&(e.adler=U(e.adler,t,r,i)),e.next_in+=r,e.total_in+=r,r)},Be=(e,t)=>{let i,s,r=e.max_chain_length,o=e.strstart,n=e.prev_length,a=e.nice_match;const l=e.strstart>e.w_size-Ae?e.strstart-(e.w_size-Ae):0,A=e.window,h=e.w_mask,c=e.prev,u=e.strstart+le;let d=A[o+n-1],p=A[o+n];e.prev_length>=e.good_match&&(r>>=2),a>e.lookahead&&(a=e.lookahead);do{if(i=t,A[i+n]===p&&A[i+n-1]===d&&A[i]===A[o]&&A[++i]===A[o+1]){o+=2,i++;do{}while(A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&on){if(e.match_start=t,n=s,s>=a)break;d=A[o+n-1],p=A[o+n]}}}while((t=c[t&h])>l&&0!=--r);return n<=e.lookahead?n:e.lookahead},we=e=>{const t=e.w_size;let i,s,r;do{if(s=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-Ae)&&(e.window.set(e.window.subarray(t,t+t-s),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),ge(e),s+=t),0===e.strm.avail_in)break;if(i=xe(e.strm,e.window,e.strstart+e.lookahead,s),e.lookahead+=i,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=me(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=me(e,e.ins_h,e.window[r+3-1]),e.prev[r&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=r,r++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead{let i,s,r,o=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,n=0,a=e.strm.avail_in;do{if(i=65535,r=e.bi_valid+42>>3,e.strm.avail_outs+e.strm.avail_in&&(i=s+e.strm.avail_in),i>r&&(i=r),i>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,_e(e.strm),s&&(s>i&&(s=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+s),e.strm.next_out),e.strm.next_out+=s,e.strm.avail_out-=s,e.strm.total_out+=s,e.block_start+=s,i-=s),i&&(xe(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i)}while(0===n);return a-=e.strm.avail_in,a&&(a>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=a&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-a,e.strm.next_in),e.strstart),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.block_start=e.strstart),e.high_waterr&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,r+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),r>e.strm.avail_in&&(r=e.strm.avail_in),r&&(xe(e.strm,e.window,e.strstart,r),e.strstart+=r,e.insert+=r>e.w_size-e.insert?e.w_size-e.insert:r),e.high_water>3,r=e.pending_buf_size-r>65535?65535:e.pending_buf_size-r,o=r>e.w_size?e.w_size:r,s=e.strstart-e.block_start,(s>=o||(s||t===K)&&t!==G&&0===e.strm.avail_in&&s<=r)&&(i=s>r?r:s,n=t===K&&0===e.strm.avail_in&&i===s?1:0,Q(e,e.block_start,i,n),e.block_start+=i,_e(e.strm)),n?3:1)},Ce=(e,t)=>{let i,s;for(;;){if(e.lookahead=3&&(e.ins_h=me(e,e.ins_h,e.window[e.strstart+3-1]),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-Ae&&(e.match_length=Be(e,i)),e.match_length>=3)if(s=H(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=me(e,e.ins_h,e.window[e.strstart+3-1]),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=me(e,e.ins_h,e.window[e.strstart+1]);else s=H(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(s&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===K?(ve(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(ve(e,!1),0===e.strm.avail_out)?1:2},Me=(e,t)=>{let i,s,r;for(;;){if(e.lookahead=3&&(e.ins_h=me(e,e.ins_h,e.window[e.strstart+3-1]),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=2,0!==i&&e.prev_length4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,s=H(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=me(e,e.ins_h,e.window[e.strstart+3-1]),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=2,e.strstart++,s&&(ve(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(s=H(e,0,e.window[e.strstart-1]),s&&ve(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(s=H(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===K?(ve(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(ve(e,!1),0===e.strm.avail_out)?1:2};function Ee(e,t,i,s,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=s,this.func=r}const Fe=[new Ee(0,0,0,0,Pe),new Ee(4,4,8,4,Ce),new Ee(4,5,16,8,Ce),new Ee(4,6,32,32,Ce),new Ee(4,4,16,16,Me),new Ee(8,16,32,32,Me),new Ee(8,16,128,128,Me),new Ee(8,32,128,256,Me),new Ee(32,128,258,1024,Me),new Ee(32,258,258,4096,Me)];function Ie(){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=ae,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 Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),fe(this.dyn_ltree),fe(this.dyn_dtree),fe(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),fe(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),fe(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const De=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==he&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==ce&&t.status!==ue?1:0},Se=e=>{if(De(e))return de(e,Z);e.total_in=e.total_out=0,e.data_type=ne;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?he:ce,e.adler=2===t.wrap?0:1,t.last_flush=-2,N(t),J},Te=e=>{const t=Se(e);var i;return t===J&&((i=e.state).window_size=2*i.w_size,fe(i.head),i.max_lazy_match=Fe[i.level].max_lazy,i.good_match=Fe[i.level].good_length,i.nice_match=Fe[i.level].nice_length,i.max_chain_length=Fe[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),t},Re=(e,t,i,s,r,o)=>{if(!e)return Z;let n=1;if(t===ee&&(t=6),s<0?(n=0,s=-s):s>15&&(n=2,s-=16),r<1||r>9||i!==ae||s<8||s>15||t<0||t>9||o<0||o>re||8===s&&1!==n)return de(e,Z);8===s&&(s=9);const a=new Ie;return e.state=a,a.strm=e,a.status=he,a.wrap=n,a.gzhead=null,a.w_bits=s,a.w_size=1<De(e)||2!==e.state.wrap?Z:(e.state.gzhead=t,J),ke=(e,t)=>{if(De(e)||t>X||t<0)return e?de(e,Z):Z;const i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===ue&&t!==K)return de(e,0===e.avail_out?$:Z);const s=i.last_flush;if(i.last_flush=t,0!==i.pending){if(_e(e),0===e.avail_out)return i.last_flush=-1,J}else if(0===e.avail_in&&pe(t)<=pe(s)&&t!==K)return de(e,$);if(i.status===ue&&0!==e.avail_in)return de(e,$);if(i.status===he&&0===i.wrap&&(i.status=ce),i.status===he){let t=ae+(i.w_bits-8<<4)<<8,s=-1;if(s=i.strategy>=ie||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=s<<6,0!==i.strstart&&(t|=32),t+=31-t%31,ye(i,t),0!==i.strstart&&(ye(i,e.adler>>>16),ye(i,65535&e.adler)),e.adler=1,i.status=ce,_e(e),0!==i.pending)return i.last_flush=-1,J}if(57===i.status)if(e.adler=0,be(i,31),be(i,139),be(i,8),i.gzhead)be(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),be(i,255&i.gzhead.time),be(i,i.gzhead.time>>8&255),be(i,i.gzhead.time>>16&255),be(i,i.gzhead.time>>24&255),be(i,9===i.level?2:i.strategy>=ie||i.level<2?4:0),be(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(be(i,255&i.gzhead.extra.length),be(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=U(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(be(i,0),be(i,0),be(i,0),be(i,0),be(i,0),be(i,9===i.level?2:i.strategy>=ie||i.level<2?4:0),be(i,3),i.status=ce,_e(e),0!==i.pending)return i.last_flush=-1,J;if(69===i.status){if(i.gzhead.extra){let t=i.pending,s=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+s>i.pending_buf_size;){let r=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+r),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>t&&(e.adler=U(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex+=r,_e(e),0!==i.pending)return i.last_flush=-1,J;t=0,s-=r}let r=new Uint8Array(i.gzhead.extra);i.pending_buf.set(r.subarray(i.gzindex,i.gzindex+s),i.pending),i.pending+=s,i.gzhead.hcrc&&i.pending>t&&(e.adler=U(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let t,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(e.adler=U(e.adler,i.pending_buf,i.pending-s,s)),_e(e),0!==i.pending)return i.last_flush=-1,J;s=0}t=i.gzindexs&&(e.adler=U(e.adler,i.pending_buf,i.pending-s,s)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let t,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(e.adler=U(e.adler,i.pending_buf,i.pending-s,s)),_e(e),0!==i.pending)return i.last_flush=-1,J;s=0}t=i.gzindexs&&(e.adler=U(e.adler,i.pending_buf,i.pending-s,s))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(_e(e),0!==i.pending))return i.last_flush=-1,J;be(i,255&e.adler),be(i,e.adler>>8&255),e.adler=0}if(i.status=ce,_e(e),0!==i.pending)return i.last_flush=-1,J}if(0!==e.avail_in||0!==i.lookahead||t!==G&&i.status!==ue){let s=0===i.level?Pe(i,t):i.strategy===ie?((e,t)=>{let i;for(;;){if(0===e.lookahead&&(we(e),0===e.lookahead)){if(t===G)return 1;break}if(e.match_length=0,i=H(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===K?(ve(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(ve(e,!1),0===e.strm.avail_out)?1:2})(i,t):i.strategy===se?((e,t)=>{let i,s,r,o;const n=e.window;for(;;){if(e.lookahead<=le){if(we(e),e.lookahead<=le&&t===G)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=e.strstart-1,s=n[r],s===n[++r]&&s===n[++r]&&s===n[++r])){o=e.strstart+le;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]&&re.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=H(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=H(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===K?(ve(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(ve(e,!1),0===e.strm.avail_out)?1:2})(i,t):Fe[i.level].func(i,t);if(3!==s&&4!==s||(i.status=ue),1===s||3===s)return 0===e.avail_out&&(i.last_flush=-1),J;if(2===s&&(t===z?j(i):t!==X&&(Q(i,0,0,!1),t===W&&(fe(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),_e(e),0===e.avail_out))return i.last_flush=-1,J}return t!==K?J:i.wrap<=0?Y:(2===i.wrap?(be(i,255&e.adler),be(i,e.adler>>8&255),be(i,e.adler>>16&255),be(i,e.adler>>24&255),be(i,255&e.total_in),be(i,e.total_in>>8&255),be(i,e.total_in>>16&255),be(i,e.total_in>>24&255)):(ye(i,e.adler>>>16),ye(i,65535&e.adler)),_e(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?J:Y)},Oe=e=>{if(De(e))return Z;const t=e.state.status;return e.state=null,t===ce?de(e,q):J},Ne=(e,t)=>{let i=t.length;if(De(e))return Z;const s=e.state,r=s.wrap;if(2===r||1===r&&s.status!==he||s.lookahead)return Z;if(1===r&&(e.adler=R(e.adler,t,i,0)),s.wrap=0,i>=s.w_size){0===r&&(fe(s.head),s.strstart=0,s.block_start=0,s.insert=0);let e=new Uint8Array(s.w_size);e.set(t.subarray(i-s.w_size,i),0),t=e,i=s.w_size}const o=e.avail_in,n=e.next_in,a=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,we(s);s.lookahead>=3;){let e=s.strstart,t=s.lookahead-2;do{s.ins_h=me(s,s.ins_h,s.window[e+3-1]),s.prev[e&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=e,e++}while(--t);s.strstart=e,s.lookahead=2,we(s)}return s.strstart+=s.lookahead,s.block_start=s.strstart,s.insert=s.lookahead,s.lookahead=0,s.match_length=s.prev_length=2,s.match_available=0,e.next_in=n,e.input=a,e.avail_in=o,s.wrap=r,J};const Qe=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var Ve=function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const t in i)Qe(i,t)&&(e[t]=i[t])}}return e},He=e=>{let t=0;for(let i=0,s=e.length;i=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;Ge[254]=Ge[254]=1;var ze=e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,i,s,r,o,n=e.length,a=0;for(r=0;r>>6,t[o++]=128|63&i):i<65536?(t[o++]=224|i>>>12,t[o++]=128|i>>>6&63,t[o++]=128|63&i):(t[o++]=240|i>>>18,t[o++]=128|i>>>12&63,t[o++]=128|i>>>6&63,t[o++]=128|63&i);return t},We=(e,t)=>{const i=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let s,r;const o=new Array(2*i);for(r=0,s=0;s4)o[r++]=65533,s+=n-1;else{for(t&=2===n?31:3===n?15:7;n>1&&s1?o[r++]=65533:t<65536?o[r++]=t:(t-=65536,o[r++]=55296|t>>10&1023,o[r++]=56320|1023&t)}}return((e,t)=>{if(t<65534&&e.subarray&&je)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let i="";for(let s=0;s{(t=t||e.length)>e.length&&(t=e.length);let i=t-1;for(;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+Ge[e[i]]>t?i:t},Xe=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};const Je=Object.prototype.toString,{Z_NO_FLUSH:Ye,Z_SYNC_FLUSH:Ze,Z_FULL_FLUSH:qe,Z_FINISH:$e,Z_OK:et,Z_STREAM_END:tt,Z_DEFAULT_COMPRESSION:it,Z_DEFAULT_STRATEGY:st,Z_DEFLATED:rt}=O;function ot(e){this.options=Ve({level:it,method:rt,chunkSize:16384,windowBits:15,memLevel:8,strategy:st},e||{});let 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 Xe,this.strm.avail_out=0;let i=Le(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==et)throw new Error(k[i]);if(t.header&&Ue(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?ze(t.dictionary):"[object ArrayBuffer]"===Je.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,i=Ne(this.strm,e),i!==et)throw new Error(k[i]);this._dict_set=!0}}function nt(e,t){const i=new ot(t);if(i.push(e,!0),i.err)throw i.msg||k[i.err];return i.result}ot.prototype.push=function(e,t){const i=this.strm,s=this.options.chunkSize;let r,o;if(this.ended)return!1;for(o=t===~~t?t:!0===t?$e:Ye,"string"==typeof e?i.input=ze(e):"[object ArrayBuffer]"===Je.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(s),i.next_out=0,i.avail_out=s),(o===Ze||o===qe)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(r=ke(i,o),r===tt)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),r=Oe(this.strm),this.onEnd(r),this.ended=!0,r===et;if(0!==i.avail_out){if(o>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},ot.prototype.onData=function(e){this.chunks.push(e)},ot.prototype.onEnd=function(e){e===et&&(this.result=He(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var at={Deflate:ot,deflate:nt,deflateRaw:function(e,t){return(t=t||{}).raw=!0,nt(e,t)},gzip:function(e,t){return(t=t||{}).gzip=!0,nt(e,t)},constants:O};const lt=16209;var At=function(e,t){let i,s,r,o,n,a,l,A,h,c,u,d,p,f,g,m,_,v,b,y,x,B,w,P;const C=e.state;i=e.next_in,w=e.input,s=i+(e.avail_in-5),r=e.next_out,P=e.output,o=r-(t-e.avail_out),n=r+(e.avail_out-257),a=C.dmax,l=C.wsize,A=C.whave,h=C.wnext,c=C.window,u=C.hold,d=C.bits,p=C.lencode,f=C.distcode,g=(1<>>24,u>>>=v,d-=v,v=_>>>16&255,0===v)P[r++]=65535&_;else{if(!(16&v)){if(0==(64&v)){_=p[(65535&_)+(u&(1<>>=v,d-=v),d<15&&(u+=w[i++]<>>24,u>>>=v,d-=v,v=_>>>16&255,!(16&v)){if(0==(64&v)){_=f[(65535&_)+(u&(1<a){e.msg="invalid distance too far back",C.mode=lt;break e}if(u>>>=v,d-=v,v=r-o,y>v){if(v=y-v,v>A&&C.sane){e.msg="invalid distance too far back",C.mode=lt;break e}if(x=0,B=c,0===h){if(x+=l-v,v2;)P[r++]=B[x++],P[r++]=B[x++],P[r++]=B[x++],b-=3;b&&(P[r++]=B[x++],b>1&&(P[r++]=B[x++]))}else{x=r-y;do{P[r++]=P[x++],P[r++]=P[x++],P[r++]=P[x++],b-=3}while(b>2);b&&(P[r++]=P[x++],b>1&&(P[r++]=P[x++]))}break}}break}}while(i>3,i-=b,d-=b<<3,u&=(1<{const l=a.bits;let A,h,c,u,d,p,f=0,g=0,m=0,_=0,v=0,b=0,y=0,x=0,B=0,w=0,P=null;const C=new Uint16Array(16),M=new Uint16Array(16);let E,F,I,D=null;for(f=0;f<=15;f++)C[f]=0;for(g=0;g=1&&0===C[_];_--);if(v>_&&(v=_),0===_)return r[o++]=20971520,r[o++]=20971520,a.bits=1,0;for(m=1;m<_&&0===C[m];m++);for(v0&&(0===e||1!==_))return-1;for(M[1]=0,f=1;f<15;f++)M[f+1]=M[f]+C[f];for(g=0;g852||2===e&&B>592)return 1;for(;;){E=f-y,n[g]+1=p?(F=D[n[g]-p],I=P[n[g]-p]):(F=96,I=0),A=1<>y)+h]=E<<24|F<<16|I|0}while(0!==h);for(A=1<>=1;if(0!==A?(w&=A-1,w+=A):w=0,g++,0==--C[f]){if(f===_)break;f=t[i+n[g]]}if(f>v&&(w&u)!==c){for(0===y&&(y=v),d+=m,b=f-y,x=1<852||2===e&&B>592)return 1;c=w&u,r[c]=v<<24|b<<16|d-o|0}}return 0!==w&&(r[d+w]=f-y<<24|64<<16|0),a.bits=v,0};const{Z_FINISH:ft,Z_BLOCK:gt,Z_TREES:mt,Z_OK:_t,Z_STREAM_END:vt,Z_NEED_DICT:bt,Z_STREAM_ERROR:yt,Z_DATA_ERROR:xt,Z_MEM_ERROR:Bt,Z_BUF_ERROR:wt,Z_DEFLATED:Pt}=O,Ct=16180,Mt=16190,Et=16191,Ft=16192,It=16194,Dt=16199,St=16200,Tt=16206,Rt=16209,Lt=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function Ut(){this.strm=null,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 Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const kt=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode16211?1:0},Ot=e=>{if(kt(e))return yt;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=Ct,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,_t},Nt=e=>{if(kt(e))return yt;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,Ot(e)},Qt=(e,t)=>{let i;if(kt(e))return yt;const s=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?yt:(null!==s.window&&s.wbits!==t&&(s.window=null),s.wrap=i,s.wbits=t,Nt(e))},Vt=(e,t)=>{if(!e)return yt;const i=new Ut;e.state=i,i.strm=e,i.window=null,i.mode=Ct;const s=Qt(e,t);return s!==_t&&(e.state=null),s};let Ht,jt,Gt=!0;const zt=e=>{if(Gt){Ht=new Int32Array(512),jt=new Int32Array(32);let t=0;for(;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(pt(1,e.lens,0,288,Ht,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;pt(2,e.lens,0,32,jt,0,e.work,{bits:5}),Gt=!1}e.lencode=Ht,e.lenbits=9,e.distcode=jt,e.distbits=5},Wt=(e,t,i,s)=>{let r;const o=e.state;return null===o.window&&(o.wsize=1<=o.wsize?(o.window.set(t.subarray(i-o.wsize,i),0),o.wnext=0,o.whave=o.wsize):(r=o.wsize-o.wnext,r>s&&(r=s),o.window.set(t.subarray(i-s,i-s+r),o.wnext),(s-=r)?(o.window.set(t.subarray(i-s,i),0),o.wnext=s,o.whave=o.wsize):(o.wnext+=r,o.wnext===o.wsize&&(o.wnext=0),o.whave{let i,s,r,o,n,a,l,A,h,c,u,d,p,f,g,m,_,v,b,y,x,B,w=0;const P=new Uint8Array(4);let C,M;const E=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(kt(e)||!e.output||!e.input&&0!==e.avail_in)return yt;i=e.state,i.mode===Et&&(i.mode=Ft),n=e.next_out,r=e.output,l=e.avail_out,o=e.next_in,s=e.input,a=e.avail_in,A=i.hold,h=i.bits,c=a,u=l,B=_t;e:for(;;)switch(i.mode){case Ct:if(0===i.wrap){i.mode=Ft;break}for(;h<16;){if(0===a)break e;a--,A+=s[o++]<>>8&255,i.check=U(i.check,P,2,0),A=0,h=0,i.mode=16181;break}if(i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&A)<<8)+(A>>8))%31){e.msg="incorrect header check",i.mode=Rt;break}if((15&A)!==Pt){e.msg="unknown compression method",i.mode=Rt;break}if(A>>>=4,h-=4,x=8+(15&A),0===i.wbits&&(i.wbits=x),x>15||x>i.wbits){e.msg="invalid window size",i.mode=Rt;break}i.dmax=1<>8&1),512&i.flags&&4&i.wrap&&(P[0]=255&A,P[1]=A>>>8&255,i.check=U(i.check,P,2,0)),A=0,h=0,i.mode=16182;case 16182:for(;h<32;){if(0===a)break e;a--,A+=s[o++]<>>8&255,P[2]=A>>>16&255,P[3]=A>>>24&255,i.check=U(i.check,P,4,0)),A=0,h=0,i.mode=16183;case 16183:for(;h<16;){if(0===a)break e;a--,A+=s[o++]<>8),512&i.flags&&4&i.wrap&&(P[0]=255&A,P[1]=A>>>8&255,i.check=U(i.check,P,2,0)),A=0,h=0,i.mode=16184;case 16184:if(1024&i.flags){for(;h<16;){if(0===a)break e;a--,A+=s[o++]<>>8&255,i.check=U(i.check,P,2,0)),A=0,h=0}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&i.flags&&(d=i.length,d>a&&(d=a),d&&(i.head&&(x=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(s.subarray(o,o+d),x)),512&i.flags&&4&i.wrap&&(i.check=U(i.check,s,d,o)),a-=d,o+=d,i.length-=d),i.length))break e;i.length=0,i.mode=16186;case 16186:if(2048&i.flags){if(0===a)break e;d=0;do{x=s[o+d++],i.head&&x&&i.length<65536&&(i.head.name+=String.fromCharCode(x))}while(x&&d>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=Et;break;case 16189:for(;h<32;){if(0===a)break e;a--,A+=s[o++]<>>=7&h,h-=7&h,i.mode=Tt;break}for(;h<3;){if(0===a)break e;a--,A+=s[o++]<>>=1,h-=1,3&A){case 0:i.mode=16193;break;case 1:if(zt(i),i.mode=Dt,t===mt){A>>>=2,h-=2;break e}break;case 2:i.mode=16196;break;case 3:e.msg="invalid block type",i.mode=Rt}A>>>=2,h-=2;break;case 16193:for(A>>>=7&h,h-=7&h;h<32;){if(0===a)break e;a--,A+=s[o++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=Rt;break}if(i.length=65535&A,A=0,h=0,i.mode=It,t===mt)break e;case It:i.mode=16195;case 16195:if(d=i.length,d){if(d>a&&(d=a),d>l&&(d=l),0===d)break e;r.set(s.subarray(o,o+d),n),a-=d,o+=d,l-=d,n+=d,i.length-=d;break}i.mode=Et;break;case 16196:for(;h<14;){if(0===a)break e;a--,A+=s[o++]<>>=5,h-=5,i.ndist=1+(31&A),A>>>=5,h-=5,i.ncode=4+(15&A),A>>>=4,h-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=Rt;break}i.have=0,i.mode=16197;case 16197:for(;i.have>>=3,h-=3}for(;i.have<19;)i.lens[E[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,C={bits:i.lenbits},B=pt(0,i.lens,0,19,i.lencode,0,i.work,C),i.lenbits=C.bits,B){e.msg="invalid code lengths set",i.mode=Rt;break}i.have=0,i.mode=16198;case 16198:for(;i.have>>24,m=w>>>16&255,_=65535&w,!(g<=h);){if(0===a)break e;a--,A+=s[o++]<>>=g,h-=g,i.lens[i.have++]=_;else{if(16===_){for(M=g+2;h>>=g,h-=g,0===i.have){e.msg="invalid bit length repeat",i.mode=Rt;break}x=i.lens[i.have-1],d=3+(3&A),A>>>=2,h-=2}else if(17===_){for(M=g+3;h>>=g,h-=g,x=0,d=3+(7&A),A>>>=3,h-=3}else{for(M=g+7;h>>=g,h-=g,x=0,d=11+(127&A),A>>>=7,h-=7}if(i.have+d>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=Rt;break}for(;d--;)i.lens[i.have++]=x}}if(i.mode===Rt)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=Rt;break}if(i.lenbits=9,C={bits:i.lenbits},B=pt(1,i.lens,0,i.nlen,i.lencode,0,i.work,C),i.lenbits=C.bits,B){e.msg="invalid literal/lengths set",i.mode=Rt;break}if(i.distbits=6,i.distcode=i.distdyn,C={bits:i.distbits},B=pt(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,C),i.distbits=C.bits,B){e.msg="invalid distances set",i.mode=Rt;break}if(i.mode=Dt,t===mt)break e;case Dt:i.mode=St;case St:if(a>=6&&l>=258){e.next_out=n,e.avail_out=l,e.next_in=o,e.avail_in=a,i.hold=A,i.bits=h,At(e,u),n=e.next_out,r=e.output,l=e.avail_out,o=e.next_in,s=e.input,a=e.avail_in,A=i.hold,h=i.bits,i.mode===Et&&(i.back=-1);break}for(i.back=0;w=i.lencode[A&(1<>>24,m=w>>>16&255,_=65535&w,!(g<=h);){if(0===a)break e;a--,A+=s[o++]<>v)],g=w>>>24,m=w>>>16&255,_=65535&w,!(v+g<=h);){if(0===a)break e;a--,A+=s[o++]<>>=v,h-=v,i.back+=v}if(A>>>=g,h-=g,i.back+=g,i.length=_,0===m){i.mode=16205;break}if(32&m){i.back=-1,i.mode=Et;break}if(64&m){e.msg="invalid literal/length code",i.mode=Rt;break}i.extra=15&m,i.mode=16201;case 16201:if(i.extra){for(M=i.extra;h>>=i.extra,h-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=16202;case 16202:for(;w=i.distcode[A&(1<>>24,m=w>>>16&255,_=65535&w,!(g<=h);){if(0===a)break e;a--,A+=s[o++]<>v)],g=w>>>24,m=w>>>16&255,_=65535&w,!(v+g<=h);){if(0===a)break e;a--,A+=s[o++]<>>=v,h-=v,i.back+=v}if(A>>>=g,h-=g,i.back+=g,64&m){e.msg="invalid distance code",i.mode=Rt;break}i.offset=_,i.extra=15&m,i.mode=16203;case 16203:if(i.extra){for(M=i.extra;h>>=i.extra,h-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=Rt;break}i.mode=16204;case 16204:if(0===l)break e;if(d=u-l,i.offset>d){if(d=i.offset-d,d>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=Rt;break}d>i.wnext?(d-=i.wnext,p=i.wsize-d):p=i.wnext-d,d>i.length&&(d=i.length),f=i.window}else f=r,p=n-i.offset,d=i.length;d>l&&(d=l),l-=d,i.length-=d;do{r[n++]=f[p++]}while(--d);0===i.length&&(i.mode=St);break;case 16205:if(0===l)break e;r[n++]=i.length,l--,i.mode=St;break;case Tt:if(i.wrap){for(;h<32;){if(0===a)break e;a--,A|=s[o++]<{if(kt(e))return yt;let t=e.state;return t.window&&(t.window=null),e.state=null,_t},Zt=(e,t)=>{if(kt(e))return yt;const i=e.state;return 0==(2&i.wrap)?yt:(i.head=t,t.done=!1,_t)},qt=(e,t)=>{const i=t.length;let s,r,o;return kt(e)?yt:(s=e.state,0!==s.wrap&&s.mode!==Mt?yt:s.mode===Mt&&(r=1,r=R(r,t,i,0),r!==s.check)?xt:(o=Wt(e,t,i,i),o?(s.mode=16210,Bt):(s.havedict=1,_t)))},$t=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};const ei=Object.prototype.toString,{Z_NO_FLUSH:ti,Z_FINISH:ii,Z_OK:si,Z_STREAM_END:ri,Z_NEED_DICT:oi,Z_STREAM_ERROR:ni,Z_DATA_ERROR:ai,Z_MEM_ERROR:li}=O;function Ai(e){this.options=Ve({chunkSize:65536,windowBits:15,to:""},e||{});const 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 Xe,this.strm.avail_out=0;let i=Xt(this.strm,t.windowBits);if(i!==si)throw new Error(k[i]);if(this.header=new $t,Zt(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=ze(t.dictionary):"[object ArrayBuffer]"===ei.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=qt(this.strm,t.dictionary),i!==si)))throw new Error(k[i])}function hi(e,t){const i=new Ai(t);if(i.push(e),i.err)throw i.msg||k[i.err];return i.result}Ai.prototype.push=function(e,t){const i=this.strm,s=this.options.chunkSize,r=this.options.dictionary;let o,n,a;if(this.ended)return!1;for(n=t===~~t?t:!0===t?ii:ti,"[object ArrayBuffer]"===ei.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(s),i.next_out=0,i.avail_out=s),o=Jt(i,n),o===oi&&r&&(o=qt(i,r),o===si?o=Jt(i,n):o===ai&&(o=oi));i.avail_in>0&&o===ri&&i.state.wrap>0&&0!==e[i.next_in];)Kt(i),o=Jt(i,n);switch(o){case ni:case ai:case oi:case li:return this.onEnd(o),this.ended=!0,!1}if(a=i.avail_out,i.next_out&&(0===i.avail_out||o===ri))if("string"===this.options.to){let e=Ke(i.output,i.next_out),t=i.next_out-e,r=We(i.output,e);i.next_out=t,i.avail_out=s-t,t&&i.output.set(i.output.subarray(e,e+t),0),this.onData(r)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(o!==si||0!==a){if(o===ri)return o=Yt(this.strm),this.onEnd(o),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},Ai.prototype.onData=function(e){this.chunks.push(e)},Ai.prototype.onEnd=function(e){e===si&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=He(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var ci={Inflate:Ai,inflate:hi,inflateRaw:function(e,t){return(t=t||{}).raw=!0,hi(e,t)},ungzip:hi,constants:O};const{Deflate:ui,deflate:di,deflateRaw:pi,gzip:fi}=at,{Inflate:gi,inflate:mi,inflateRaw:_i,ungzip:vi}=ci;var bi=ui,yi=di,xi=pi,Bi=fi,wi=gi,Pi=mi,Ci=_i,Mi=vi,Ei=O,Fi={Deflate:bi,deflate:yi,deflateRaw:xi,gzip:Bi,Inflate:wi,inflate:Pi,inflateRaw:Ci,ungzip:Mi,constants:Ei};e.Deflate=bi,e.Inflate=wi,e.constants=Ei,e.default=Fi,e.deflate=yi,e.deflateRaw=xi,e.gzip=Bi,e.inflate=Pi,e.inflateRaw=Ci,e.ungzip=Mi,Object.defineProperty(e,"__esModule",{value:!0})}));var jC=Object.freeze({__proto__:null});let GC=window.pako||jC;GC.inflate||(GC=GC.default);const zC=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}}();const WC={version:1,parse:function(e,t,i,s,r,o){const n=function(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]}}(i),a=function(e){return{positions:new Uint16Array(GC.inflate(e.positions).buffer),normals:new Int8Array(GC.inflate(e.normals).buffer),indices:new Uint32Array(GC.inflate(e.indices).buffer),edgeIndices:new Uint32Array(GC.inflate(e.edgeIndices).buffer),meshPositions:new Uint32Array(GC.inflate(e.meshPositions).buffer),meshIndices:new Uint32Array(GC.inflate(e.meshIndices).buffer),meshEdgesIndices:new Uint32Array(GC.inflate(e.meshEdgesIndices).buffer),meshColors:new Uint8Array(GC.inflate(e.meshColors).buffer),entityIDs:GC.inflate(e.entityIDs,{to:"string"}),entityMeshes:new Uint32Array(GC.inflate(e.entityMeshes).buffer),entityIsObjects:new Uint8Array(GC.inflate(e.entityIsObjects).buffer),positionsDecodeMatrix:new Float32Array(GC.inflate(e.positionsDecodeMatrix).buffer)}}(n);!function(e,t,i,s,r,o){o.getNextId(),s.positionsCompression="precompressed",s.normalsCompression="precompressed";const n=i.positions,a=i.normals,l=i.indices,A=i.edgeIndices,h=i.meshPositions,c=i.meshIndices,u=i.meshEdgesIndices,p=i.meshColors,f=JSON.parse(i.entityIDs),g=i.entityMeshes,m=i.entityIsObjects,_=h.length,v=g.length;for(let r=0;rg[e]g[t]?1:0));for(let e=0;e1||(E[i]=e)}}for(let e=0;e1,o=eM(m.subarray(4*t,4*t+3)),u=m[4*t+3]/255,_=a.subarray(d[t],i?a.length:d[t+1]),b=l.subarray(d[t],i?l.length:d[t+1]),x=A.subarray(p[t],i?A.length:p[t+1]),w=h.subarray(f[t],i?h.length:f[t+1]),M=c.subarray(g[t],g[t]+16);if(r){const e=`${n}-geometry.${t}`;s.createGeometry({id:e,primitive:"triangles",positionsCompressed:_,normalsCompressed:b,indices:x,edgeIndices:w,positionsDecodeMatrix:M})}else{const e=`${n}-${t}`;v[E[t]];const i={};s.createMesh(y.apply(i,{id:e,primitive:"triangles",positionsCompressed:_,normalsCompressed:b,indices:x,edgeIndices:w,positionsDecodeMatrix:M,color:o,opacity:u}))}}let F=0;for(let e=0;e1){const t={},r=`${n}-instance.${F++}`,o=`${n}-geometry.${i}`,a=16*x[e],A=u.subarray(a,a+16);s.createMesh(y.apply(t,{id:r,geometryId:o,matrix:A})),l.push(r)}else l.push(i)}if(l.length>0){const e={};s.createEntity(y.apply(e,{id:r,isObject:!0,meshIds:l}))}}}(0,0,a,s,0,o)}};let iM=window.pako||jC;iM.inflate||(iM=iM.default);const sM=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}}();const rM={version:5,parse:function(e,t,i,s,r,o){const n=function(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]}}(i),a=function(e){return{positions:new Float32Array(iM.inflate(e.positions).buffer),normals:new Int8Array(iM.inflate(e.normals).buffer),indices:new Uint32Array(iM.inflate(e.indices).buffer),edgeIndices:new Uint32Array(iM.inflate(e.edgeIndices).buffer),matrices:new Float32Array(iM.inflate(e.matrices).buffer),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(iM.inflate(e.eachPrimitivePositionsAndNormalsPortion).buffer),eachPrimitiveIndicesPortion:new Uint32Array(iM.inflate(e.eachPrimitiveIndicesPortion).buffer),eachPrimitiveEdgeIndicesPortion:new Uint32Array(iM.inflate(e.eachPrimitiveEdgeIndicesPortion).buffer),eachPrimitiveColor:new Uint8Array(iM.inflate(e.eachPrimitiveColor).buffer),primitiveInstances:new Uint32Array(iM.inflate(e.primitiveInstances).buffer),eachEntityId:iM.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(iM.inflate(e.eachEntityPrimitiveInstancesPortion).buffer),eachEntityMatricesPortion:new Uint32Array(iM.inflate(e.eachEntityMatricesPortion).buffer)}}(n);!function(e,t,i,s,r,o){const n=o.getNextId();s.positionsCompression="disabled",s.normalsCompression="precompressed";const a=i.positions,l=i.normals,A=i.indices,h=i.edgeIndices,c=i.matrices,u=i.eachPrimitivePositionsAndNormalsPortion,d=i.eachPrimitiveIndicesPortion,p=i.eachPrimitiveEdgeIndicesPortion,f=i.eachPrimitiveColor,g=i.primitiveInstances,m=JSON.parse(i.eachEntityId),_=i.eachEntityPrimitiveInstancesPortion,v=i.eachEntityMatricesPortion,b=u.length,x=g.length,B=new Uint8Array(b),w=m.length;for(let e=0;e1||(P[i]=e)}}for(let e=0;e1,r=sM(f.subarray(4*e,4*e+3)),o=f[4*e+3]/255,c=a.subarray(u[e],t?a.length:u[e+1]),g=l.subarray(u[e],t?l.length:u[e+1]),_=A.subarray(d[e],t?A.length:d[e+1]),v=h.subarray(p[e],t?h.length:p[e+1]);if(i){const t=`${n}-geometry.${e}`;s.createGeometry({id:t,primitive:"triangles",positionsCompressed:c,normalsCompressed:g,indices:_,edgeIndices:v})}else{const t=e;m[P[e]];const i={};s.createMesh(y.apply(i,{id:t,primitive:"triangles",positionsCompressed:c,normalsCompressed:g,indices:_,edgeIndices:v,color:r,opacity:o}))}}let C=0;for(let e=0;e1){const t={},r="instance."+C++,o="geometry"+i,n=16*v[e],l=c.subarray(n,n+16);s.createMesh(y.apply(t,{id:r,geometryId:o,matrix:l})),a.push(r)}else a.push(i)}if(a.length>0){const e={};s.createEntity(y.apply(e,{id:r,isObject:!0,meshIds:a}))}}}(0,0,a,s,0,o)}};let oM=window.pako||jC;oM.inflate||(oM=oM.default);const nM=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}}();const aM={version:6,parse:function(e,t,i,s,r,o){const n=function(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],matrices:e[4],reusedPrimitivesDecodeMatrix:e[5],eachPrimitivePositionsAndNormalsPortion:e[6],eachPrimitiveIndicesPortion:e[7],eachPrimitiveEdgeIndicesPortion:e[8],eachPrimitiveColorAndOpacity:e[9],primitiveInstances:e[10],eachEntityId:e[11],eachEntityPrimitiveInstancesPortion:e[12],eachEntityMatricesPortion:e[13],eachTileAABB:e[14],eachTileEntitiesPortion:e[15]}}(i),a=function(e){function t(e,t){return 0===e.length?[]:oM.inflate(e,t).buffer}return{positions:new Uint16Array(t(e.positions)),normals:new Int8Array(t(e.normals)),indices:new Uint32Array(t(e.indices)),edgeIndices:new Uint32Array(t(e.edgeIndices)),matrices:new Float32Array(t(e.matrices)),reusedPrimitivesDecodeMatrix:new Float32Array(t(e.reusedPrimitivesDecodeMatrix)),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(t(e.eachPrimitivePositionsAndNormalsPortion)),eachPrimitiveIndicesPortion:new Uint32Array(t(e.eachPrimitiveIndicesPortion)),eachPrimitiveEdgeIndicesPortion:new Uint32Array(t(e.eachPrimitiveEdgeIndicesPortion)),eachPrimitiveColorAndOpacity:new Uint8Array(t(e.eachPrimitiveColorAndOpacity)),primitiveInstances:new Uint32Array(t(e.primitiveInstances)),eachEntityId:oM.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(t(e.eachEntityPrimitiveInstancesPortion)),eachEntityMatricesPortion:new Uint32Array(t(e.eachEntityMatricesPortion)),eachTileAABB:new Float64Array(t(e.eachTileAABB)),eachTileEntitiesPortion:new Uint32Array(t(e.eachTileEntitiesPortion))}}(n);!function(e,t,i,s,r,o){const n=o.getNextId(),a=i.positions,l=i.normals,A=i.indices,h=i.edgeIndices,c=i.matrices,u=i.reusedPrimitivesDecodeMatrix,p=i.eachPrimitivePositionsAndNormalsPortion,f=i.eachPrimitiveIndicesPortion,g=i.eachPrimitiveEdgeIndicesPortion,m=i.eachPrimitiveColorAndOpacity,_=i.primitiveInstances,v=JSON.parse(i.eachEntityId),b=i.eachEntityPrimitiveInstancesPortion,x=i.eachEntityMatricesPortion,B=i.eachTileAABB,w=i.eachTileEntitiesPortion,P=p.length,C=_.length,M=v.length,E=w.length,F=new Uint32Array(P);for(let e=0;e1,c=t===P-1,d=a.subarray(p[t],c?a.length:p[t+1]),v=l.subarray(p[t],c?l.length:p[t+1]),b=A.subarray(f[t],c?A.length:f[t+1]),x=h.subarray(g[t],c?h.length:g[t+1]),B=nM(m.subarray(4*t,4*t+3)),w=m[4*t+3]/255,C=o.getNextId();if(r){const e=`${n}-geometry.${i}.${t}`;U[e]||(s.createGeometry({id:e,primitive:"triangles",positionsCompressed:d,indices:b,edgeIndices:x,positionsDecodeMatrix:u}),U[e]=!0),s.createMesh(y.apply(N,{id:C,geometryId:e,origin:I,matrix:E,color:B,opacity:w})),R.push(C)}else s.createMesh(y.apply(N,{id:C,origin:I,primitive:"triangles",positionsCompressed:d,normalsCompressed:v,indices:b,edgeIndices:x,positionsDecodeMatrix:L,color:B,opacity:w})),R.push(C)}R.length>0&&s.createEntity(y.apply(O,{id:w,isObject:!0,meshIds:R}))}}}(e,t,a,s,0,o)}};let lM=window.pako||jC;lM.inflate||(lM=lM.default);const AM=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 hM(e){const t=[];for(let i=0,s=e.length;i1,d=t===F-1,P=AM(w.subarray(6*e,6*e+3)),C=w[6*e+3]/255,M=w[6*e+4]/255,E=w[6*e+5]/255,I=o.getNextId();if(r){const r=B[e],o=u.slice(r,r+16),x=`${n}-geometry.${i}.${t}`;if(!Q[x]){let e,i,r,o,n,u;switch(f[t]){case 0:e="solid",i=a.subarray(g[t],d?a.length:g[t+1]),r=l.subarray(m[t],d?l.length:m[t+1]),n=h.subarray(v[t],d?h.length:v[t+1]),u=c.subarray(b[t],d?c.length:b[t+1]);break;case 1:e="surface",i=a.subarray(g[t],d?a.length:g[t+1]),r=l.subarray(m[t],d?l.length:m[t+1]),n=h.subarray(v[t],d?h.length:v[t+1]),u=c.subarray(b[t],d?c.length:b[t+1]);break;case 2:e="points",i=a.subarray(g[t],d?a.length:g[t+1]),o=hM(A.subarray(_[t],d?A.length:_[t+1]));break;case 3:e="lines",i=a.subarray(g[t],d?a.length:g[t+1]),n=h.subarray(v[t],d?h.length:v[t+1]);break;default:continue}s.createGeometry({id:x,primitive:e,positionsCompressed:i,normalsCompressed:r,colors:o,indices:n,edgeIndices:u,positionsDecodeMatrix:p}),Q[x]=!0}s.createMesh(y.apply(V,{id:I,geometryId:x,origin:R,matrix:o,color:P,metallic:M,roughness:E,opacity:C})),U.push(I)}else{let e,i,r,o,n,u;switch(f[t]){case 0:e="solid",i=a.subarray(g[t],d?a.length:g[t+1]),r=l.subarray(m[t],d?l.length:m[t+1]),n=h.subarray(v[t],d?h.length:v[t+1]),u=c.subarray(b[t],d?c.length:b[t+1]);break;case 1:e="surface",i=a.subarray(g[t],d?a.length:g[t+1]),r=l.subarray(m[t],d?l.length:m[t+1]),n=h.subarray(v[t],d?h.length:v[t+1]),u=c.subarray(b[t],d?c.length:b[t+1]);break;case 2:e="points",i=a.subarray(g[t],d?a.length:g[t+1]),o=hM(A.subarray(_[t],d?A.length:_[t+1]));break;case 3:e="lines",i=a.subarray(g[t],d?a.length:g[t+1]),n=h.subarray(v[t],d?h.length:v[t+1]);break;default:continue}s.createMesh(y.apply(V,{id:I,origin:R,primitive:e,positionsCompressed:i,normalsCompressed:r,colors:o,indices:n,edgeIndices:u,positionsDecodeMatrix:N,color:P,metallic:M,roughness:E,opacity:C})),U.push(I)}}U.length>0&&s.createEntity(y.apply(O,{id:E,isObject:!0,meshIds:U}))}}}(e,t,a,s,0,o)}};let uM=window.pako||jC;uM.inflate||(uM=uM.default);const dM=d.vec4(),pM=d.vec4();const fM=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 gM(e){const t=[];for(let i=0,s=e.length;i1,l=r===L-1,A=fM(F.subarray(6*e,6*e+3)),h=F[6*e+3]/255,c=F[6*e+4]/255,I=F[6*e+5]/255,D=o.getNextId();if(a){const o=E[e],a=_.slice(o,o+16),M=`${n}-geometry.${i}.${r}`;let F=H[M];if(!F){F={batchThisMesh:!t.reuseGeometries};let e=!1;switch(b[r]){case 0:F.primitiveName="solid",F.geometryPositions=u.subarray(x[r],l?u.length:x[r+1]),F.geometryNormals=p.subarray(B[r],l?p.length:B[r+1]),F.geometryIndices=g.subarray(P[r],l?g.length:P[r+1]),F.geometryEdgeIndices=m.subarray(C[r],l?m.length:C[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 1:F.primitiveName="surface",F.geometryPositions=u.subarray(x[r],l?u.length:x[r+1]),F.geometryNormals=p.subarray(B[r],l?p.length:B[r+1]),F.geometryIndices=g.subarray(P[r],l?g.length:P[r+1]),F.geometryEdgeIndices=m.subarray(C[r],l?m.length:C[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 2:F.primitiveName="points",F.geometryPositions=u.subarray(x[r],l?u.length:x[r+1]),F.geometryColors=gM(f.subarray(w[r],l?f.length:w[r+1])),e=F.geometryPositions.length>0;break;case 3:F.primitiveName="lines",F.geometryPositions=u.subarray(x[r],l?u.length:x[r+1]),F.geometryIndices=g.subarray(P[r],l?g.length:P[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;default:continue}if(e||(F=null),F&&(F.geometryPositions.length,F.batchThisMesh)){F.decompressedPositions=new Float32Array(F.geometryPositions.length);const e=F.geometryPositions,t=F.decompressedPositions;for(let i=0,s=e.length;i0&&n.length>0;break;case 1:e="surface",t=u.subarray(x[r],l?u.length:x[r+1]),i=p.subarray(B[r],l?p.length:B[r+1]),n=g.subarray(P[r],l?g.length:P[r+1]),a=m.subarray(C[r],l?m.length:C[r+1]),d=t.length>0&&n.length>0;break;case 2:e="points",t=u.subarray(x[r],l?u.length:x[r+1]),o=gM(f.subarray(w[r],l?f.length:w[r+1])),d=t.length>0;break;case 3:e="lines",t=u.subarray(x[r],l?u.length:x[r+1]),n=g.subarray(P[r],l?g.length:P[r+1]),d=t.length>0&&n.length>0;break;default:continue}d&&(s.createMesh(y.apply(G,{id:D,origin:Q,primitive:e,positionsCompressed:t,normalsCompressed:i,colorsCompressed:o,indices:n,edgeIndices:a,positionsDecodeMatrix:R,color:A,metallic:c,roughness:I,opacity:h})),T.push(D))}}T.length>0&&s.createEntity(y.apply(j,{id:A,isObject:!0,meshIds:T}))}}}(e,t,a,s,r,o)}};let _M=window.pako||jC;_M.inflate||(_M=_M.default);const vM=d.vec4(),bM=d.vec4();const yM=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}}();const xM={version:9,parse:function(e,t,i,s,r,o){const n=function(e){return{metadata:e[0],positions:e[1],normals:e[2],colors:e[3],indices:e[4],edgeIndices:e[5],matrices:e[6],reusedGeometriesDecodeMatrix:e[7],eachGeometryPrimitiveType:e[8],eachGeometryPositionsPortion:e[9],eachGeometryNormalsPortion:e[10],eachGeometryColorsPortion:e[11],eachGeometryIndicesPortion:e[12],eachGeometryEdgeIndicesPortion:e[13],eachMeshGeometriesPortion:e[14],eachMeshMatricesPortion:e[15],eachMeshMaterial:e[16],eachEntityId:e[17],eachEntityMeshesPortion:e[18],eachTileAABB:e[19],eachTileEntitiesPortion:e[20]}}(i),a=function(e){function t(e,t){return 0===e.length?[]:_M.inflate(e,t).buffer}return{metadata:JSON.parse(_M.inflate(e.metadata,{to:"string"})),positions:new Uint16Array(t(e.positions)),normals:new Int8Array(t(e.normals)),colors:new Uint8Array(t(e.colors)),indices:new Uint32Array(t(e.indices)),edgeIndices:new Uint32Array(t(e.edgeIndices)),matrices:new Float32Array(t(e.matrices)),reusedGeometriesDecodeMatrix:new Float32Array(t(e.reusedGeometriesDecodeMatrix)),eachGeometryPrimitiveType:new Uint8Array(t(e.eachGeometryPrimitiveType)),eachGeometryPositionsPortion:new Uint32Array(t(e.eachGeometryPositionsPortion)),eachGeometryNormalsPortion:new Uint32Array(t(e.eachGeometryNormalsPortion)),eachGeometryColorsPortion:new Uint32Array(t(e.eachGeometryColorsPortion)),eachGeometryIndicesPortion:new Uint32Array(t(e.eachGeometryIndicesPortion)),eachGeometryEdgeIndicesPortion:new Uint32Array(t(e.eachGeometryEdgeIndicesPortion)),eachMeshGeometriesPortion:new Uint32Array(t(e.eachMeshGeometriesPortion)),eachMeshMatricesPortion:new Uint32Array(t(e.eachMeshMatricesPortion)),eachMeshMaterial:new Uint8Array(t(e.eachMeshMaterial)),eachEntityId:JSON.parse(_M.inflate(e.eachEntityId,{to:"string"})),eachEntityMeshesPortion:new Uint32Array(t(e.eachEntityMeshesPortion)),eachTileAABB:new Float64Array(t(e.eachTileAABB)),eachTileEntitiesPortion:new Uint32Array(t(e.eachTileEntitiesPortion))}}(n);!function(e,t,i,s,r,o){const n=o.getNextId(),a=i.metadata,l=i.positions,A=i.normals,h=i.colors,c=i.indices,u=i.edgeIndices,p=i.matrices,f=i.reusedGeometriesDecodeMatrix,g=i.eachGeometryPrimitiveType,m=i.eachGeometryPositionsPortion,_=i.eachGeometryNormalsPortion,v=i.eachGeometryColorsPortion,b=i.eachGeometryIndicesPortion,x=i.eachGeometryEdgeIndicesPortion,B=i.eachMeshGeometriesPortion,w=i.eachMeshMatricesPortion,P=i.eachMeshMaterial,C=i.eachEntityId,M=i.eachEntityMeshesPortion,E=i.eachTileAABB,F=i.eachTileEntitiesPortion,I=m.length,D=B.length,S=M.length,T=F.length;r&&r.loadData(a,{includeTypes:t.includeTypes,excludeTypes:t.excludeTypes,globalizeObjectIds:t.globalizeObjectIds});const R=new Uint32Array(I);for(let e=0;e1,C=r===I-1,M=yM(P.subarray(6*e,6*e+3)),E=P[6*e+3]/255,F=P[6*e+4]/255,D=P[6*e+5]/255,S=o.getNextId();if(a){const o=w[e],a=p.slice(o,o+16),B=`${n}-geometry.${i}.${r}`;let P=k[B];if(!P){P={batchThisMesh:!t.reuseGeometries};let e=!1;switch(g[r]){case 0:P.primitiveName="solid",P.geometryPositions=l.subarray(m[r],C?l.length:m[r+1]),P.geometryNormals=A.subarray(_[r],C?A.length:_[r+1]),P.geometryIndices=c.subarray(b[r],C?c.length:b[r+1]),P.geometryEdgeIndices=u.subarray(x[r],C?u.length:x[r+1]),e=P.geometryPositions.length>0&&P.geometryIndices.length>0;break;case 1:P.primitiveName="surface",P.geometryPositions=l.subarray(m[r],C?l.length:m[r+1]),P.geometryNormals=A.subarray(_[r],C?A.length:_[r+1]),P.geometryIndices=c.subarray(b[r],C?c.length:b[r+1]),P.geometryEdgeIndices=u.subarray(x[r],C?u.length:x[r+1]),e=P.geometryPositions.length>0&&P.geometryIndices.length>0;break;case 2:P.primitiveName="points",P.geometryPositions=l.subarray(m[r],C?l.length:m[r+1]),P.geometryColors=h.subarray(v[r],C?h.length:v[r+1]),e=P.geometryPositions.length>0;break;case 3:P.primitiveName="lines",P.geometryPositions=l.subarray(m[r],C?l.length:m[r+1]),P.geometryIndices=c.subarray(b[r],C?c.length:b[r+1]),e=P.geometryPositions.length>0&&P.geometryIndices.length>0;break;default:continue}if(e||(P=null),P&&(P.geometryPositions.length,P.batchThisMesh)){P.decompressedPositions=new Float32Array(P.geometryPositions.length),P.transformedAndRecompressedPositions=new Uint16Array(P.geometryPositions.length);const e=P.geometryPositions,t=P.decompressedPositions;for(let i=0,s=e.length;i0&&n.length>0;break;case 1:e="surface",t=l.subarray(m[r],C?l.length:m[r+1]),i=A.subarray(_[r],C?A.length:_[r+1]),n=c.subarray(b[r],C?c.length:b[r+1]),a=u.subarray(x[r],C?u.length:x[r+1]),d=t.length>0&&n.length>0;break;case 2:e="points",t=l.subarray(m[r],C?l.length:m[r+1]),o=h.subarray(v[r],C?h.length:v[r+1]),d=t.length>0;break;case 3:e="lines",t=l.subarray(m[r],C?l.length:m[r+1]),n=c.subarray(b[r],C?c.length:b[r+1]),d=t.length>0&&n.length>0;break;default:continue}d&&(s.createMesh(y.apply(j,{id:S,origin:L,primitive:e,positionsCompressed:t,normalsCompressed:i,colorsCompressed:o,indices:n,edgeIndices:a,positionsDecodeMatrix:Q,color:M,metallic:F,roughness:D,opacity:E})),O.push(S))}}O.length>0&&s.createEntity(y.apply(H,{id:E,isObject:!0,meshIds:O}))}}}(e,t,a,s,r,o)}};let BM=window.pako||jC;BM.inflate||(BM=BM.default);const wM=d.vec4(),PM=d.vec4();const CM=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 MM(e,t){const i=[];if(t.length>1)for(let e=0,s=t.length-1;e1)for(let t=0,s=e.length/3-1;t0,a=9*e,c=1===h[a+0],u=h[a+1];h[a+2],h[a+3];const d=h[a+4],p=h[a+5],f=h[a+6],g=h[a+7],m=h[a+8];if(o){const t=new Uint8Array(l.subarray(i,r)).buffer,o=`${n}-texture-${e}`;if(c)s.createTexture({id:o,buffers:[t],minFilter:d,magFilter:p,wrapS:f,wrapT:g,wrapR:m});else{const e=new Blob([t],{type:10001===u?"image/jpeg":10002===u?"image/png":"image/gif"}),i=(window.URL||window.webkitURL).createObjectURL(e),r=document.createElement("img");r.src=i,s.createTexture({id:o,image:r,minFilter:d,magFilter:p,wrapS:f,wrapT:g,wrapR:m})}}}for(let e=0;e=0?`${n}-texture-${r}`:null,normalsTextureId:a>=0?`${n}-texture-${a}`:null,metallicRoughnessTextureId:o>=0?`${n}-texture-${o}`:null,emissiveTextureId:l>=0?`${n}-texture-${l}`:null,occlusionTextureId:A>=0?`${n}-texture-${A}`:null})}const j=new Uint32Array(N);for(let e=0;e1,l=r===N-1,A=D[e],h=A>=0?`${n}-textureSet-${A}`:null,T=CM(S.subarray(6*e,6*e+3)),R=S[6*e+3]/255,L=S[6*e+4]/255,O=S[6*e+5]/255,Q=o.getNextId();if(a){const o=I[e],a=v.slice(o,o+16),A=`${n}-geometry.${i}.${r}`;let F=W[A];if(!F){F={batchThisMesh:!t.reuseGeometries};let e=!1;switch(x[r]){case 0:F.primitiveName="solid",F.geometryPositions=c.subarray(B[r],l?c.length:B[r+1]),F.geometryNormals=u.subarray(w[r],l?u.length:w[r+1]),F.geometryUVs=f.subarray(C[r],l?f.length:C[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),F.geometryEdgeIndices=m.subarray(E[r],l?m.length:E[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 1:F.primitiveName="surface",F.geometryPositions=c.subarray(B[r],l?c.length:B[r+1]),F.geometryNormals=u.subarray(w[r],l?u.length:w[r+1]),F.geometryUVs=f.subarray(C[r],l?f.length:C[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),F.geometryEdgeIndices=m.subarray(E[r],l?m.length:E[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 2:F.primitiveName="points",F.geometryPositions=c.subarray(B[r],l?c.length:B[r+1]),F.geometryColors=p.subarray(P[r],l?p.length:P[r+1]),e=F.geometryPositions.length>0;break;case 3:F.primitiveName="lines",F.geometryPositions=c.subarray(B[r],l?c.length:B[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 4:F.primitiveName="lines",F.geometryPositions=c.subarray(B[r],l?c.length:B[r+1]),F.geometryIndices=MM(F.geometryPositions,g.subarray(M[r],l?g.length:M[r+1])),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;default:continue}if(e||(F=null),F&&(F.geometryPositions.length,F.batchThisMesh)){F.decompressedPositions=new Float32Array(F.geometryPositions.length),F.transformedAndRecompressedPositions=new Uint16Array(F.geometryPositions.length);const e=F.geometryPositions,t=F.decompressedPositions;for(let i=0,s=e.length;i0&&a.length>0;break;case 1:e="surface",t=c.subarray(B[r],l?c.length:B[r+1]),i=u.subarray(w[r],l?u.length:w[r+1]),o=f.subarray(C[r],l?f.length:C[r+1]),a=g.subarray(M[r],l?g.length:M[r+1]),A=m.subarray(E[r],l?m.length:E[r+1]),d=t.length>0&&a.length>0;break;case 2:e="points",t=c.subarray(B[r],l?c.length:B[r+1]),n=p.subarray(P[r],l?p.length:P[r+1]),d=t.length>0;break;case 3:e="lines",t=c.subarray(B[r],l?c.length:B[r+1]),a=g.subarray(M[r],l?g.length:M[r+1]),d=t.length>0&&a.length>0;break;case 4:e="lines",t=c.subarray(B[r],l?c.length:B[r+1]),a=MM(t,g.subarray(M[r],l?g.length:M[r+1])),d=t.length>0&&a.length>0;break;default:continue}d&&(s.createMesh(y.apply(H,{id:Q,textureSetId:h,origin:G,primitive:e,positionsCompressed:t,normalsCompressed:i,uv:o&&o.length>0?o:null,colorsCompressed:n,indices:a,edgeIndices:A,positionsDecodeMatrix:_,color:T,metallic:L,roughness:O,opacity:R})),U.push(Q))}}U.length>0&&s.createEntity(y.apply(Q,{id:l,isObject:!0,meshIds:U}))}}}(e,t,a,s,r,o)}},FM=d.vec4(),IM=d.vec4();const DM=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 SM(e,t){const i=[];if(t.length>1)for(let e=0,s=t.length-1;e1)for(let t=0,s=e.length/3-1;t1){const t=new Uint8Array(e,n,a),i=l/2,s=t.length/l;for(let e=0;eJSON.parse(e.decode(i(Uint8Array)))}();return{metadata:s(),textureData:i(Uint8Array),eachTextureDataPortion:i(Uint32Array),eachTextureAttributes:i(Uint16Array),positions:i(Uint16Array),normals:i(Int8Array),colors:i(Uint8Array),uvs:i(Float32Array),indices:i(Uint32Array),edgeIndices:i(Uint32Array),eachTextureSetTextures:i(Int32Array),matrices:i(Float32Array),reusedGeometriesDecodeMatrix:i(Float32Array),eachGeometryPrimitiveType:i(Uint8Array),eachGeometryPositionsPortion:i(Uint32Array),eachGeometryNormalsPortion:i(Uint32Array),eachGeometryColorsPortion:i(Uint32Array),eachGeometryUVsPortion:i(Uint32Array),eachGeometryIndicesPortion:i(Uint32Array),eachGeometryEdgeIndicesPortion:i(Uint32Array),eachMeshGeometriesPortion:i(Uint32Array),eachMeshMatricesPortion:i(Uint32Array),eachMeshTextureSet:i(Int32Array),eachMeshMaterialAttributes:i(Uint8Array),eachEntityId:s(),eachEntityMeshesPortion:i(Uint32Array),eachTileAABB:i(Float64Array),eachTileEntitiesPortion:i(Uint32Array)}}(i);!function(e,t,i,s,r,o){const n=o.getNextId(),a=i.metadata,l=i.textureData,A=i.eachTextureDataPortion,h=i.eachTextureAttributes,c=i.positions,u=i.normals,p=i.colors,f=i.uvs,g=i.indices,m=i.edgeIndices,_=i.eachTextureSetTextures,v=i.matrices,b=i.reusedGeometriesDecodeMatrix,x=i.eachGeometryPrimitiveType,B=i.eachGeometryPositionsPortion,w=i.eachGeometryNormalsPortion,P=i.eachGeometryColorsPortion,C=i.eachGeometryUVsPortion,M=i.eachGeometryIndicesPortion,E=i.eachGeometryEdgeIndicesPortion,F=i.eachMeshGeometriesPortion,I=i.eachMeshMatricesPortion,D=i.eachMeshTextureSet,S=i.eachMeshMaterialAttributes,T=i.eachEntityId,R=i.eachEntityMeshesPortion,L=i.eachTileAABB,U=i.eachTileEntitiesPortion,k=A.length,O=_.length/5,N=B.length,Q=F.length,V=R.length,H=U.length;r&&r.loadData(a,{includeTypes:t.includeTypes,excludeTypes:t.excludeTypes,globalizeObjectIds:t.globalizeObjectIds});for(let e=0;e0,a=9*e,c=1===h[a+0],u=h[a+1];h[a+2],h[a+3];const d=h[a+4],p=h[a+5],f=h[a+6],g=h[a+7],m=h[a+8];if(o){const t=new Uint8Array(l.subarray(i,r)).buffer,o=`${n}-texture-${e}`;if(c)s.createTexture({id:o,buffers:[t],minFilter:d,magFilter:p,wrapS:f,wrapT:g,wrapR:m});else{const e=new Blob([t],{type:10001===u?"image/jpeg":10002===u?"image/png":"image/gif"}),i=(window.URL||window.webkitURL).createObjectURL(e),r=document.createElement("img");r.src=i,s.createTexture({id:o,image:r,minFilter:d,magFilter:p,wrapS:f,wrapT:g,wrapR:m})}}}for(let e=0;e=0?`${n}-texture-${r}`:null,normalsTextureId:a>=0?`${n}-texture-${a}`:null,metallicRoughnessTextureId:o>=0?`${n}-texture-${o}`:null,emissiveTextureId:l>=0?`${n}-texture-${l}`:null,occlusionTextureId:A>=0?`${n}-texture-${A}`:null})}const j=new Uint32Array(N);for(let e=0;e1,l=r===N-1,A=D[e],h=A>=0?`${n}-textureSet-${A}`:null,T=DM(S.subarray(6*e,6*e+3)),R=S[6*e+3]/255,L=S[6*e+4]/255,O=S[6*e+5]/255,Q=o.getNextId();if(a){const o=I[e],a=v.slice(o,o+16),A=`${n}-geometry.${i}.${r}`;let F=W[A];if(!F){F={batchThisMesh:!t.reuseGeometries};let e=!1;switch(x[r]){case 0:F.primitiveName="solid",F.geometryPositions=c.subarray(B[r],l?c.length:B[r+1]),F.geometryNormals=u.subarray(w[r],l?u.length:w[r+1]),F.geometryUVs=f.subarray(C[r],l?f.length:C[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),F.geometryEdgeIndices=m.subarray(E[r],l?m.length:E[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 1:F.primitiveName="surface",F.geometryPositions=c.subarray(B[r],l?c.length:B[r+1]),F.geometryNormals=u.subarray(w[r],l?u.length:w[r+1]),F.geometryUVs=f.subarray(C[r],l?f.length:C[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),F.geometryEdgeIndices=m.subarray(E[r],l?m.length:E[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 2:F.primitiveName="points",F.geometryPositions=c.subarray(B[r],l?c.length:B[r+1]),F.geometryColors=p.subarray(P[r],l?p.length:P[r+1]),e=F.geometryPositions.length>0;break;case 3:F.primitiveName="lines",F.geometryPositions=c.subarray(B[r],l?c.length:B[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 4:F.primitiveName="lines",F.geometryPositions=c.subarray(B[r],l?c.length:B[r+1]),F.geometryIndices=SM(F.geometryPositions,g.subarray(M[r],l?g.length:M[r+1])),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;default:continue}if(e||(F=null),F&&(F.geometryPositions.length,F.batchThisMesh)){F.decompressedPositions=new Float32Array(F.geometryPositions.length),F.transformedAndRecompressedPositions=new Uint16Array(F.geometryPositions.length);const e=F.geometryPositions,t=F.decompressedPositions;for(let i=0,s=e.length;i0&&a.length>0;break;case 1:e="surface",t=c.subarray(B[r],l?c.length:B[r+1]),i=u.subarray(w[r],l?u.length:w[r+1]),o=f.subarray(C[r],l?f.length:C[r+1]),a=g.subarray(M[r],l?g.length:M[r+1]),A=m.subarray(E[r],l?m.length:E[r+1]),d=t.length>0&&a.length>0;break;case 2:e="points",t=c.subarray(B[r],l?c.length:B[r+1]),n=p.subarray(P[r],l?p.length:P[r+1]),d=t.length>0;break;case 3:e="lines",t=c.subarray(B[r],l?c.length:B[r+1]),a=g.subarray(M[r],l?g.length:M[r+1]),d=t.length>0&&a.length>0;break;case 4:e="lines",t=c.subarray(B[r],l?c.length:B[r+1]),a=SM(t,g.subarray(M[r],l?g.length:M[r+1])),d=t.length>0&&a.length>0;break;default:continue}d&&(s.createMesh(y.apply(H,{id:Q,textureSetId:h,origin:G,primitive:e,positionsCompressed:t,normalsCompressed:i,uv:o&&o.length>0?o:null,colorsCompressed:n,indices:a,edgeIndices:A,positionsDecodeMatrix:_,color:T,metallic:L,roughness:O,opacity:R})),U.push(Q))}}U.length>0&&s.createEntity(y.apply(Q,{id:l,isObject:!0,meshIds:U}))}}}(e,t,n,s,r,o)}},RM={};RM[WC.version]=WC,RM[JC.version]=JC,RM[qC.version]=qC,RM[tM.version]=tM,RM[rM.version]=rM,RM[aM.version]=aM,RM[cM.version]=cM,RM[mM.version]=mM,RM[xM.version]=xM,RM[EM.version]=EM,RM[TM.version]=TM;class LM extends z{constructor(e,t={}){super("XKTLoader",e,t),this._maxGeometryBatchSize=t.maxGeometryBatchSize,this.textureTranscoder=t.textureTranscoder,this.dataSource=t.dataSource,this.objectDefaults=t.objectDefaults,this.includeTypes=t.includeTypes,this.excludeTypes=t.excludeTypes,this.excludeUnclassifiedObjects=t.excludeUnclassifiedObjects,this.reuseGeometries=t.reuseGeometries}get supportedVersions(){return Object.keys(RM)}get textureTranscoder(){return this._textureTranscoder}set textureTranscoder(e){this._textureTranscoder=e}get dataSource(){return this._dataSource}set dataSource(e){this._dataSource=e||new HC}get objectDefaults(){return this._objectDefaults}set objectDefaults(e){this._objectDefaults=e||HP}get includeTypes(){return this._includeTypes}set includeTypes(e){this._includeTypes=e}get excludeTypes(){return this._excludeTypes}set excludeTypes(e){this._excludeTypes=e}get excludeUnclassifiedObjects(){return this._excludeUnclassifiedObjects}set excludeUnclassifiedObjects(e){this._excludeUnclassifiedObjects=!!e}get globalizeObjectIds(){return this._globalizeObjectIds}set globalizeObjectIds(e){this._globalizeObjectIds=!!e}get reuseGeometries(){return this._reuseGeometries}set reuseGeometries(e){this._reuseGeometries=!1!==e}load(e={}){if(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),!(e.src||e.xkt||e.manifestSrc||e.manifest))return this.error("load() param expected: src, xkt, manifestSrc or manifestData"),o;const t={},i=e.includeTypes||this._includeTypes,s=e.excludeTypes||this._excludeTypes,r=e.objectDefaults||this._objectDefaults;if(t.reuseGeometries=null!==e.reuseGeometries&&void 0!==e.reuseGeometries?e.reuseGeometries:!1!==this._reuseGeometries,i){t.includeTypesMap={};for(let e=0,s=i.length;e{o.destroyed||(o.finalize(),a.finalize(),this.viewer.scene.canvas.spinner.processes--,o.once("destroyed",(()=>{this.viewer.metaScene.destroyMetaModel(a.id)})),this.scheduleTask((()=>{o.destroyed||(o.scene.fire("modelLoaded",o.id),o.fire("loaded",!0,!1))})))},A=e=>{this.viewer.scene.canvas.spinner.processes--,this.error(e),o.fire("error",e)};let h=0;const c={getNextId:()=>`${n}.${h++}`};if(e.metaModelSrc||e.metaModelData)if(e.metaModelSrc){const r=e.metaModelSrc;this._dataSource.getMetaModel(r,(r=>{o.destroyed||(a.loadData(r,{includeTypes:i,excludeTypes:s,globalizeObjectIds:t.globalizeObjectIds}),e.src?this._loadModel(e.src,e,t,o,null,c,l,A):(this._parseModel(e.xkt,e,t,o,null,c),l()))}),(e=>{A(`load(): Failed to load model metadata for model '${n} from '${r}' - ${e}`)}))}else e.metaModelData&&(a.loadData(e.metaModelData,{includeTypes:i,excludeTypes:s,globalizeObjectIds:t.globalizeObjectIds}),e.src?this._loadModel(e.src,e,t,o,null,c,l,A):(this._parseModel(e.xkt,e,t,o,null,c),l()));else if(e.src)this._loadModel(e.src,e,t,o,a,c,l,A);else if(e.xkt)this._parseModel(e.xkt,e,t,o,a,c),l();else if(e.manifestSrc||e.manifest){const r=e.manifestSrc?function(e){const t=e.split("/");return t.pop(),t.join("/")+"/"}(e.manifestSrc):"",n=(e,n,l)=>{let A=0;const h=()=>{o.destroyed||A>=e.length?n():this._dataSource.getMetaModel(`${r}${e[A]}`,(e=>{a.loadData(e,{includeTypes:i,excludeTypes:s,globalizeObjectIds:t.globalizeObjectIds}),A++,this.scheduleTask(h,200)}),l)};h()},h=(i,s,n)=>{let a=0;const l=()=>{o.destroyed||a>=i.length?s():this._dataSource.getXKT(`${r}${i[a]}`,(i=>{this._parseModel(i,e,t,o,null,c),o.preFinalize(),a++,this.scheduleTask(l,200)}),n)};l()},u=(i,s,n)=>{let l=0;const A=()=>{o.destroyed||l>=i.length?s():this._dataSource.getXKT(`${r}${i[l]}`,(i=>{this._parseModel(i,e,t,o,a,c),o.preFinalize(),l++,this.scheduleTask(A,200)}),n)};A()};if(e.manifest){const t=e.manifest,i=t.xktFiles;if(!i||0===i.length)return void A("load(): Failed to load model manifest - manifest not valid");const s=t.metaModelFiles;s?n(s,(()=>{h(i,l,A)}),A):u(i,l,A)}else this._dataSource.getManifest(e.manifestSrc,(e=>{if(o.destroyed)return;const t=e.xktFiles;if(!t||0===t.length)return void A("load(): Failed to load model manifest - manifest not valid");const i=e.metaModelFiles;i?n(i,(()=>{h(t,l,A)}),A):u(t,l,A)}),A)}return o}_loadModel(e,t,i,s,r,o,n,a){this._dataSource.getXKT(t.src,(e=>{this._parseModel(e,t,i,s,r,o),s.preFinalize(),n()}),a)}async _parseModel(e,t,i,s,r,o){if(s.destroyed)return;const n=new DataView(e),a=new Uint8Array(e),l=n.getUint32(0,!0),A=RM[l];if(!A)return void this.error("Unsupported .XKT file version: "+l+" - this XKTLoaderPlugin supports versions "+Object.keys(RM));if(A.parseArrayBuffer)return void A.parseArrayBuffer(this.viewer,i,e,s,r,o);const h=n.getUint32(4,!0),c=[];let u=4*(h+2);for(let e=0;ee.size)throw new RangeError("offset:"+t+", length:"+i+", size:"+e.size);return e.slice?e.slice(t,t+i):e.webkitSlice?e.webkitSlice(t,t+i):e.mozSlice?e.mozSlice(t,t+i):e.msSlice?e.msSlice(t,t+i):void 0}(e,t,i))}catch(e){r(e)}}}function p(){}function f(e){var i,s=this;s.init=function(e){i=new Blob([],{type:n}),e()},s.writeUint8Array=function(e,s){i=new Blob([i,t?e:e.buffer],{type:n}),s()},s.getData=function(t,s){var r=new FileReader;r.onload=function(e){t(e.target.result)},r.onerror=s,r.readAsText(i,e)}}function g(t){var i=this,s="",r="";i.init=function(e){s+="data:"+(t||"")+";base64,",e()},i.writeUint8Array=function(t,i){var o,n=r.length,a=r;for(r="",o=0;o<3*Math.floor((n+t.length)/3)-n;o++)a+=String.fromCharCode(t[o]);for(;o2?s+=e.btoa(a):r=a,i()},i.getData=function(t){t(s+e.btoa(r))}}function m(e){var i,s=this;s.init=function(t){i=new Blob([],{type:e}),t()},s.writeUint8Array=function(s,r){i=new Blob([i,t?s:s.buffer],{type:e}),r()},s.getData=function(e){e(i)}}function _(e,t,i,s,r,n,a,l,A,h){var c,u,d,p=0,f=t.sn;function g(){e.removeEventListener("message",m,!1),l(u,d)}function m(t){var i=t.data,r=i.data,o=i.error;if(o)return o.toString=function(){return"Error: "+this.message},void A(o);if(i.sn===f)switch("number"==typeof i.codecTime&&(e.codecTime+=i.codecTime),"number"==typeof i.crcTime&&(e.crcTime+=i.crcTime),i.type){case"append":r?(u+=r.length,s.writeUint8Array(r,(function(){_()}),h)):_();break;case"flush":d=i.crc,r?(u+=r.length,s.writeUint8Array(r,(function(){g()}),h)):g();break;case"progress":a&&a(c+i.loaded,n);break;case"importScripts":case"newTask":case"echo":break;default:console.warn("zip.js:launchWorkerProcess: unknown message: ",i)}}function _(){(c=p*o)<=n?i.readUint8Array(r+c,Math.min(o,n-c),(function(i){a&&a(c,n);var s=0===c?t:{sn:f};s.type="append",s.data=i;try{e.postMessage(s,[i.buffer])}catch(t){e.postMessage(s)}p++}),A):e.postMessage({sn:f,type:"flush"})}u=0,e.addEventListener("message",m,!1),_()}function v(e,t,i,s,r,n,l,A,h,c){var u,d=0,p=0,f="input"===n,g="output"===n,m=new a;!function n(){var a;if((u=d*o)127?r[i-128]:String.fromCharCode(i);return s}function x(e){return decodeURIComponent(escape(e))}function B(e){var t,i="";for(t=0;t>16,i=65535&e;try{return new Date(1980+((65024&t)>>9),((480&t)>>5)-1,31&t,(63488&i)>>11,(2016&i)>>5,2*(31&i),0)}catch(e){}}(e.lastModDateRaw),1!=(1&e.bitFlag)?((s||8!=(8&e.bitFlag))&&(e.crc32=t.view.getUint32(i+10,!0),e.compressedSize=t.view.getUint32(i+14,!0),e.uncompressedSize=t.view.getUint32(i+18,!0)),4294967295!==e.compressedSize&&4294967295!==e.uncompressedSize?(e.filenameLength=t.view.getUint16(i+22,!0),e.extraFieldLength=t.view.getUint16(i+24,!0)):r("File is using Zip64 (4gb+ file size).")):r("File contains encrypted entry.")}function P(t,o,n){var a=0;function l(){}l.prototype.getData=function(s,o,l,h){var c=this;function u(e,t){h&&!function(e){var t=A(4);return t.view.setUint32(0,e),c.crc32==t.view.getUint32(0)}(t)?n("CRC failed."):s.getData((function(e){o(e)}))}function d(e){n(e||r)}function p(e){n(e||"Error while writing file data.")}t.readUint8Array(c.offset,30,(function(r){var o,f=A(r.length,r);1347093252==f.view.getUint32(0)?(w(c,f,4,!1,n),o=c.offset+30+c.filenameLength+c.extraFieldLength,s.init((function(){0===c.compressionMethod?b(c._worker,a++,t,s,o,c.compressedSize,h,u,l,d,p):function(t,i,s,r,o,n,a,l,A,h,c){var u=a?"output":"none";e.zip.useWebWorkers?_(t,{sn:i,codecClass:"Inflater",crcType:u},s,r,o,n,A,l,h,c):v(new e.zip.Inflater,s,r,o,n,u,A,l,h,c)}(c._worker,a++,t,s,o,c.compressedSize,h,u,l,d,p)}),p)):n(i)}),d)};var h={getEntries:function(e){var r=this._worker;!function(e){t.size<22?n(i):r(22,(function(){r(Math.min(65558,t.size),(function(){n(i)}))}));function r(i,r){t.readUint8Array(t.size-i,i,(function(t){for(var i=t.length-22;i>=0;i--)if(80===t[i]&&75===t[i+1]&&5===t[i+2]&&6===t[i+3])return void e(new DataView(t.buffer,i,22));r()}),(function(){n(s)}))}}((function(o){var a,h;a=o.getUint32(16,!0),h=o.getUint16(8,!0),a<0||a>=t.size?n(i):t.readUint8Array(a,t.size-a,(function(t){var s,o,a,c,u=0,d=[],p=A(t.length,t);for(s=0;s>>8^i[255&(t^e[s])];this.crc=t},a.prototype.get=function(){return~this.crc},a.prototype.table=function(){var e,t,i,s=[];for(e=0;e<256;e++){for(i=e,t=0;t<8;t++)1&i?i=i>>>1^3988292384:i>>>=1;s[e]=i}return s}(),l.prototype.append=function(e,t){return e},l.prototype.flush=function(){},c.prototype=new h,c.prototype.constructor=c,u.prototype=new h,u.prototype.constructor=u,d.prototype=new h,d.prototype.constructor=d,p.prototype.getData=function(e){e(this.data)},f.prototype=new p,f.prototype.constructor=f,g.prototype=new p,g.prototype.constructor=g,m.prototype=new p,m.prototype.constructor=m;var F={deflater:["z-worker.js","deflate.js"],inflater:["z-worker.js","inflate.js"]};function I(t,i,s){if(null===e.zip.workerScripts||null===e.zip.workerScriptsPath){var r;if(e.zip.workerScripts){if(r=e.zip.workerScripts[t],!Array.isArray(r))return void s(new Error("zip.workerScripts."+t+" is not an array!"));r=function(e){var t=document.createElement("a");return e.map((function(e){return t.href=e,t.href}))}(r)}else(r=F[t].slice(0))[0]=(e.zip.workerScriptsPath||"")+r[0];var o=new Worker(r[0]);o.codecTime=o.crcTime=0,o.postMessage({type:"importScripts",scripts:r.slice(1)}),o.addEventListener("message",(function e(t){var r=t.data;if(r.error)return o.terminate(),void s(r.error);"importScripts"===r.type&&(o.removeEventListener("message",e),o.removeEventListener("error",n),i(o))})),o.addEventListener("error",n)}else s(new Error("Either zip.workerScripts or zip.workerScriptsPath may be set, not both."));function n(e){o.terminate(),s(e)}}function D(e){console.error(e)}e.zip={Reader:h,Writer:p,BlobReader:d,Data64URIReader:u,TextReader:c,BlobWriter:m,Data64URIWriter:g,TextWriter:f,createReader:function(e,t,i){i=i||D,e.init((function(){P(e,t,i)}),i)},createWriter:function(e,t,i,s){i=i||D,s=!!s,e.init((function(){E(e,t,i,s)}),i)},useWebWorkers:!0,workerScriptsPath:null,workerScripts:null}}(UM);const kM=UM.zip;!function(e){var t,i,s=e.Reader,r=e.Writer;try{i=0===new Blob([new DataView(new ArrayBuffer(0))]).size}catch(e){}function o(e){var t=this;function i(i,s){var r;t.data?i():((r=new XMLHttpRequest).addEventListener("load",(function(){t.size||(t.size=Number(r.getResponseHeader("Content-Length"))||Number(r.response.byteLength)),t.data=new Uint8Array(r.response),i()}),!1),r.addEventListener("error",s,!1),r.open("GET",e),r.responseType="arraybuffer",r.send())}t.size=0,t.init=function(s,r){if(function(e){var t=document.createElement("a");return t.href=e,"http:"===t.protocol||"https:"===t.protocol}(e)){var o=new XMLHttpRequest;o.addEventListener("load",(function(){t.size=Number(o.getResponseHeader("Content-Length")),t.size?s():i(s,r)}),!1),o.addEventListener("error",r,!1),o.open("HEAD",e),o.send()}else i(s,r)},t.readUint8Array=function(e,s,r,o){i((function(){r(new Uint8Array(t.data.subarray(e,e+s)))}),o)}}function n(e){var t=this;t.size=0,t.init=function(i,s){var r=new XMLHttpRequest;r.addEventListener("load",(function(){t.size=Number(r.getResponseHeader("Content-Length")),"bytes"==r.getResponseHeader("Accept-Ranges")?i():s("HTTP Range not supported.")}),!1),r.addEventListener("error",s,!1),r.open("HEAD",e),r.send()},t.readUint8Array=function(t,i,s,r){!function(t,i,s,r){var o=new XMLHttpRequest;o.open("GET",e),o.responseType="arraybuffer",o.setRequestHeader("Range","bytes="+t+"-"+(t+i-1)),o.addEventListener("load",(function(){s(o.response)}),!1),o.addEventListener("error",r,!1),o.send()}(t,i,(function(e){s(new Uint8Array(e))}),r)}}function a(e){var t=this;t.size=0,t.init=function(i,s){t.size=e.byteLength,i()},t.readUint8Array=function(t,i,s,r){s(new Uint8Array(e.slice(t,t+i)))}}function l(){var e,t=this;t.init=function(t,i){e=new Uint8Array,t()},t.writeUint8Array=function(t,i,s){var r=new Uint8Array(e.length+t.length);r.set(e),r.set(t,e.length),e=r,i()},t.getData=function(t){t(e.buffer)}}function A(e,t){var s,r=this;r.init=function(t,i){e.createWriter((function(e){s=e,t()}),i)},r.writeUint8Array=function(e,r,o){var n=new Blob([i?e:e.buffer],{type:t});s.onwrite=function(){s.onwrite=null,r()},s.onerror=o,s.write(n)},r.getData=function(t){e.file(t)}}o.prototype=new s,o.prototype.constructor=o,n.prototype=new s,n.prototype.constructor=n,a.prototype=new s,a.prototype.constructor=a,l.prototype=new r,l.prototype.constructor=l,A.prototype=new r,A.prototype.constructor=A,e.FileWriter=A,e.HttpReader=o,e.HttpRangeReader=n,e.ArrayBufferReader=a,e.ArrayBufferWriter=l,e.fs&&((t=e.fs.ZipDirectoryEntry).prototype.addHttpContent=function(i,s,r){return function(i,s,r,o){if(i.directory)return o?new t(i.fs,s,r,i):new e.fs.ZipFileEntry(i.fs,s,r,i);throw"Parent entry is not a directory."}(this,i,{data:s,Reader:r?n:o})},t.prototype.importHttpContent=function(e,t,i,s){this.importZip(t?new n(e):new o(e),i,s)},e.fs.FS.prototype.importHttpContent=function(e,i,s,r){this.entries=[],this.root=new t(this),this.root.importHttpContent(e,i,s,r)})}(kM);const OM=["4.2"];class NM{constructor(e,t={}){this.supportedSchemas=OM,this._xrayOpacity=.7,this._src=null,this._options=t,this.viewpoint=null,t.workerScriptsPath?(kM.workerScriptsPath=t.workerScriptsPath,this.src=t.src,this.xrayOpacity=.7,this.displayEffect=t.displayEffect,this.createMetaModel=t.createMetaModel):e.error("Config expected: workerScriptsPath")}load(e,t,i,s,r,o){switch(s.materialType){case"MetallicMaterial":t._defaultMaterial=new zr(t,{baseColor:[1,1,1],metallic:.6,roughness:.6});break;case"SpecularMaterial":t._defaultMaterial=new Xr(t,{diffuse:[1,1,1],specular:d.vec3([1,1,1]),glossiness:.5});break;default:t._defaultMaterial=new oi(t,{reflectivity:.75,shiness:100,diffuse:[1,1,1]})}t._wireframeMaterial=new Hr(t,{color:[0,0,0],lineWidth:2});var n=t.scene.canvas.spinner;n.processes++,QM(e,t,i,s,(function(){n.processes--,r&&r(),t.fire("loaded",!0,!1)}),(function(e){n.processes--,t.error(e),o&&o(e),t.fire("error",e)}),(function(e){console.log("Error, Will Robinson: "+e)}))}}var QM=function(e,t,i,s,r,o){!function(e,t,i){var s=new XM;s.load(e,(function(){t(s)}),(function(e){i("Error loading ZIP archive: "+e)}))}(i,(function(i){VM(e,i,s,t,r,o)}),o)},VM=function(){return function(t,i,s,r,o){var n={plugin:t,zip:i,edgeThreshold:30,materialType:s.materialType,scene:r.scene,modelNode:r,info:{references:{}},materials:{}};s.createMetaModel&&(n.metaModelData={modelId:r.id,metaObjects:[{name:r.id,type:"Default",id:r.id}]}),r.scene.loading++,function(t,i){t.zip.getFile("Manifest.xml",(function(s,r){for(var o=r.children,n=0,a=o.length;n0){for(var n=o.trim().split(" "),a=new Int16Array(n.length),l=0,A=0,h=n.length;A0){i.primitive="triangles";for(var o=[],n=0,a=r.length;n=t.length)i();else{var a=t[o].id,l=a.lastIndexOf(":");l>0&&(a=a.substring(l+1));var A=a.lastIndexOf("#");A>0&&(a=a.substring(0,A)),s[a]?r(o+1):function(e,t,i){e.zip.getFile(t,(function(t,s){!function(e,t,i){for(var s,r=t.children,o=0,n=r.length;o0)for(var s=0,r=t.length;s-1?e+"&_="+t:e+"?_="+t}getIFC(e,t,i){e=this._cacheBusterURL(e);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),i=new Uint8Array(e);for(var n=0;n{this._parseModel(e,t,i,s),r.processes--}),(e=>{r.processes--,this.error(e),s.fire("error",e)}))}_parseModel(e,t,i,s){if(s.destroyed)return;const r=t.stats||{};if(r.sourceFormat="IFC",r.schemaVersion="",r.title="",r.author="",r.created="",r.numMetaObjects=0,r.numPropertySets=0,r.numObjects=0,r.numGeometries=0,r.numTriangles=0,r.numVertices=0,!this._ifcAPI)throw"WebIFCLoaderPlugin has no WebIFC instance configured - please inject via WebIFCLoaderPlugin constructor";const o=new Uint8Array(e),n=this._ifcAPI.OpenModel(o),a=this._ifcAPI.GetModelSchema(n),l=this._ifcAPI.GetLineIDsWithType(n,this._webIFC.IFCPROJECT).get(0),A=!1!==t.loadMetadata,h={modelID:n,modelSchema:a,sceneModel:s,loadMetadata:A,metadata:A?{id:"",projectId:""+l,author:"",createdAt:"",schema:"",creatingApplication:"",metaObjects:[],propertySets:[]}:null,metaObjects:{},options:i,log:function(e){},nextId:0,stats:r};if(A){if(i.includeTypes){h.includeTypes={};for(let e=0,t=i.includeTypes.length;e{s.destroyed||(s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1))}))}_parseMetaObjects(e){const t=this._ifcAPI.GetLineIDsWithType(e.modelID,this._webIFC.IFCPROJECT).get(0),i=this._ifcAPI.GetLine(e.modelID,t);this._parseSpatialChildren(e,i)}_parseSpatialChildren(e,t,i){const s=this._ifcAPI.GetNameFromTypeCode(t.type);if(e.includeTypes&&!e.includeTypes[s])return;if(e.excludeTypes&&e.excludeTypes[s])return;this._createMetaObject(e,t,i);const r=t.GlobalId.value;this._parseRelatedItemsOfType(e,t.expressID,"RelatingObject","RelatedObjects",this._webIFC.IFCRELAGGREGATES,r),this._parseRelatedItemsOfType(e,t.expressID,"RelatingStructure","RelatedElements",this._webIFC.IFCRELCONTAINEDINSPATIALSTRUCTURE,r)}_createMetaObject(e,t,i){const s=t.GlobalId.value,r=this._ifcAPI.GetNameFromTypeCode(t.type),o={id:s,name:t.Name&&""!==t.Name.value?t.Name.value:r,type:r,parent:i};e.metadata.metaObjects.push(o),e.metaObjects[s]=o,e.stats.numMetaObjects++}_parseRelatedItemsOfType(e,t,i,s,r,o){const n=this._ifcAPI.GetLineIDsWithType(e.modelID,r);for(let r=0;re.value)).includes(t)}else h=A.value===t;if(h){const t=l[s];if(Array.isArray(t))t.forEach((t=>{const i=this._ifcAPI.GetLine(e.modelID,t.value);this._parseSpatialChildren(e,i,o)}));else{const i=this._ifcAPI.GetLine(e.modelID,t.value);this._parseSpatialChildren(e,i,o)}}}}_parsePropertySets(e){const t=this._ifcAPI.GetLineIDsWithType(e.modelID,this._webIFC.IFCRELDEFINESBYPROPERTIES);for(let i=0;i0){const o="Default",n=t.Name.value,a=[];for(let e=0,t=s.length;e{const i=t.expressID,s=t.geometries,r=[],o=this._ifcAPI.GetLine(e.modelID,i).GlobalId.value;if(e.loadMetadata){const t=o,i=e.metaObjects[t];if(e.includeTypes&&(!i||!e.includeTypes[i.type]))return;if(e.excludeTypes&&(!i||e.excludeTypes[i.type]))return}const n=d.mat4(),a=d.vec3();for(let t=0,i=s.size();t-1?e+"&_="+t:e+"?_="+t}getLAS(e,t,i){e=this._cacheBusterURL(e);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),i=new Uint8Array(e);for(var n=0;n{let t=0,i=0,s=0;const r=new DataView(e),o=new Uint8Array(6e3),n=({item:s,format:o,size:n})=>{let a,l;switch(o){case"char":return l=new Uint8Array(e,t,n),t+=n,a=oE(l),[s,a];case"uShort":return a=r.getUint16(t,!0),t+=n,[s,a];case"uLong":return a=r.getUint32(t,!0),"NumberOfVariableLengthRecords"===s&&(i=a),t+=n,[s,a];case"uChar":return a=r.getUint8(t),t+=n,[s,a];case"double":return a=r.getFloat64(t,!0),t+=n,[s,a];default:t+=n}};return(()=>{const e={};tE.forEach((t=>{const i=n({...t});if(void 0!==i){if("FileSignature"===i[0]&&"LASF"!==i[1])throw new Error("Ivalid FileSignature. Is this a LAS/LAZ file");e[i[0]]=i[1]}}));const r=[];let a=i;for(;a--;){const e={};iE.forEach((i=>{const r=n({...i});e[r[0]]=r[1],"UserId"===r[0]&&"LASF_Projection"===r[1]&&(s=t-18+54)})),r.push(e)}const l=(e=>{if(void 0===e)return;const t=s+e.RecordLengthAfterHeader,i=o.slice(s,t),r=rE(i),n=new DataView(r);let a=6,l=Number(n.getUint16(a,!0));const A=[];for(;l--;){const e={};e.key=n.getUint16(a+=2,!0),e.tiffTagLocation=n.getUint16(a+=2,!0),e.count=n.getUint16(a+=2,!0),e.valueOffset=n.getUint16(a+=2,!0),A.push(e)}const h=A.find((e=>3072===e.key));if(h&&h.hasOwnProperty("valueOffset"))return h.valueOffset})(r.find((e=>"LASF_Projection"===e.UserId)));return l&&(e.epsg=l),e})()},rE=e=>{let t=new ArrayBuffer(e.length),i=new Uint8Array(t);for(let t=0;t{let t="";return e.forEach((e=>{let i=String.fromCharCode(e);"\0"!==i&&(t+=i)})),t.trim()};class nE extends z{constructor(e,t={}){super("lasLoader",e,t),this.dataSource=t.dataSource,this.skip=t.skip,this.fp64=t.fp64,this.colorDepth=t.colorDepth}get dataSource(){return this._dataSource}set dataSource(e){this._dataSource=e||new $M}get skip(){return this._skip}set skip(e){this._skip=e||1}get fp64(){return this._fp64}set fp64(e){this._fp64=!!e}get colorDepth(){return this._colorDepth}set colorDepth(e){this._colorDepth=e||"auto"}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 Gc(this.viewer.scene,y.apply(e,{maxGeometryBatchSize:5e5,isModel:!0}));if(!e.src&&!e.las)return this.error("load() param expected: src or las"),t;const i={las:{skip:this._skip,fp64:this._fp64,colorDepth:this._colorDepth}};if(e.src)this._loadModel(e.src,e,i,t);else{const s=this.viewer.scene.canvas.spinner;s.processes++,this._parseModel(e.las,e,i,t).then((()=>{s.processes--}),(e=>{s.processes--,this.error(e),t.fire("error",e)}))}return t}_loadModel(e,t,i,s){const r=this.viewer.scene.canvas.spinner;r.processes++,this._dataSource.getLAS(t.src,(e=>{this._parseModel(e,t,i,s).then((()=>{r.processes--}),(e=>{r.processes--,this.error(e),s.fire("error",e)}))}),(e=>{r.processes--,this.error(e),s.fire("error",e)}))}_parseModel(e,t,i,s){function r(e){const i=e.value;if(t.rotateX&&i)for(let e=0,t=i.length;e{if(s.destroyed)return void l();const A=t.stats||{};A.sourceFormat="LAS",A.schemaVersion="",A.title="",A.author="",A.created="",A.numMetaObjects=0,A.numPropertySets=0,A.numObjects=0,A.numGeometries=0,A.numTriangles=0,A.numVertices=0;try{const A=sE(e);eB(e,eE,i).then((e=>{const h=e.attributes,c=e.loaderData,u=void 0!==c.pointsFormatId?c.pointsFormatId:-1;if(!h.POSITION)return s.finalize(),void l("No positions found in file");let p,f;switch(u){case 0:p=r(h.POSITION),f=n(h.intensity);break;case 1:if(!h.intensity)return s.finalize(),void l("No positions found in file");p=r(h.POSITION),f=n(h.intensity);break;case 2:case 3:if(!h.intensity)return s.finalize(),void l("No positions found in file");p=r(h.POSITION),f=o(h.COLOR_0,h.intensity)}const g=aE(p,15e5),m=aE(f,2e6),_=[];for(let e=0,t=g.length;e{s.destroyed||(s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1))})),a()}))}catch(e){s.finalize(),l(e)}}))}}function aE(e,t){if(t>=e.length)return[e];let i=[];for(let s=0;s-1?e+"&_="+t:e+"?_="+t}getCityJSON(e,t,i){y.loadJSON(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}}function AE(e,t,i){i=i||2;var s,r,o,n,a,l,A,h=t&&t.length,c=h?t[0]*i:e.length,u=hE(e,0,c,i,!0),d=[];if(!u||u.next===u.prev)return d;if(h&&(u=function(e,t,i,s){var r,o,n,a=[];for(r=0,o=t.length;r80*i){s=o=e[0],r=n=e[1];for(var p=i;po&&(o=a),l>n&&(n=l);A=0!==(A=Math.max(o-s,n-r))?1/A:0}return uE(u,d,i,s,r,A),d}function hE(e,t,i,s,r){var o,n;if(r===RE(e,t,i,s)>0)for(o=t;o=t;o-=s)n=DE(o,e[o],e[o+1],n);return n&&PE(n,n.next)&&(SE(n),n=n.next),n}function cE(e,t){if(!e)return e;t||(t=e);var i,s=e;do{if(i=!1,s.steiner||!PE(s,s.next)&&0!==wE(s.prev,s,s.next))s=s.next;else{if(SE(s),(s=t=s.prev)===s.next)break;i=!0}}while(i||s!==t);return t}function uE(e,t,i,s,r,o,n){if(e){!n&&o&&function(e,t,i,s){var r=e;do{null===r.z&&(r.z=bE(r.x,r.y,t,i,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==e);r.prevZ.nextZ=null,r.prevZ=null,function(e){var t,i,s,r,o,n,a,l,A=1;do{for(i=e,e=null,o=null,n=0;i;){for(n++,s=i,a=0,t=0;t0||l>0&&s;)0!==a&&(0===l||!s||i.z<=s.z)?(r=i,i=i.nextZ,a--):(r=s,s=s.nextZ,l--),o?o.nextZ=r:e=r,r.prevZ=o,o=r;i=s}o.nextZ=null,A*=2}while(n>1)}(r)}(e,s,r,o);for(var a,l,A=e;e.prev!==e.next;)if(a=e.prev,l=e.next,o?pE(e,s,r,o):dE(e))t.push(a.i/i),t.push(e.i/i),t.push(l.i/i),SE(e),e=l.next,A=l.next;else if((e=l)===A){n?1===n?uE(e=fE(cE(e),t,i),t,i,s,r,o,2):2===n&&gE(e,t,i,s,r,o):uE(cE(e),t,i,s,r,o,1);break}}}function dE(e){var t=e.prev,i=e,s=e.next;if(wE(t,i,s)>=0)return!1;for(var r=e.next.next;r!==e.prev;){if(xE(t.x,t.y,i.x,i.y,s.x,s.y,r.x,r.y)&&wE(r.prev,r,r.next)>=0)return!1;r=r.next}return!0}function pE(e,t,i,s){var r=e.prev,o=e,n=e.next;if(wE(r,o,n)>=0)return!1;for(var a=r.xo.x?r.x>n.x?r.x:n.x:o.x>n.x?o.x:n.x,h=r.y>o.y?r.y>n.y?r.y:n.y:o.y>n.y?o.y:n.y,c=bE(a,l,t,i,s),u=bE(A,h,t,i,s),d=e.prevZ,p=e.nextZ;d&&d.z>=c&&p&&p.z<=u;){if(d!==e.prev&&d!==e.next&&xE(r.x,r.y,o.x,o.y,n.x,n.y,d.x,d.y)&&wE(d.prev,d,d.next)>=0)return!1;if(d=d.prevZ,p!==e.prev&&p!==e.next&&xE(r.x,r.y,o.x,o.y,n.x,n.y,p.x,p.y)&&wE(p.prev,p,p.next)>=0)return!1;p=p.nextZ}for(;d&&d.z>=c;){if(d!==e.prev&&d!==e.next&&xE(r.x,r.y,o.x,o.y,n.x,n.y,d.x,d.y)&&wE(d.prev,d,d.next)>=0)return!1;d=d.prevZ}for(;p&&p.z<=u;){if(p!==e.prev&&p!==e.next&&xE(r.x,r.y,o.x,o.y,n.x,n.y,p.x,p.y)&&wE(p.prev,p,p.next)>=0)return!1;p=p.nextZ}return!0}function fE(e,t,i){var s=e;do{var r=s.prev,o=s.next.next;!PE(r,o)&&CE(r,s,s.next,o)&&FE(r,o)&&FE(o,r)&&(t.push(r.i/i),t.push(s.i/i),t.push(o.i/i),SE(s),SE(s.next),s=e=o),s=s.next}while(s!==e);return cE(s)}function gE(e,t,i,s,r,o){var n=e;do{for(var a=n.next.next;a!==n.prev;){if(n.i!==a.i&&BE(n,a)){var l=IE(n,a);return n=cE(n,n.next),l=cE(l,l.next),uE(n,t,i,s,r,o),void uE(l,t,i,s,r,o)}a=a.next}n=n.next}while(n!==e)}function mE(e,t){return e.x-t.x}function _E(e,t){if(t=function(e,t){var i,s=t,r=e.x,o=e.y,n=-1/0;do{if(o<=s.y&&o>=s.next.y&&s.next.y!==s.y){var a=s.x+(o-s.y)*(s.next.x-s.x)/(s.next.y-s.y);if(a<=r&&a>n){if(n=a,a===r){if(o===s.y)return s;if(o===s.next.y)return s.next}i=s.x=s.x&&s.x>=h&&r!==s.x&&xE(oi.x||s.x===i.x&&vE(i,s)))&&(i=s,u=l)),s=s.next}while(s!==A);return i}(e,t),t){var i=IE(t,e);cE(t,t.next),cE(i,i.next)}}function vE(e,t){return wE(e.prev,e,t.prev)<0&&wE(t.next,e,e.next)<0}function bE(e,t,i,s,r){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-i)*r)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-s)*r)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function yE(e){var t=e,i=e;do{(t.x=0&&(e-n)*(s-a)-(i-n)*(t-a)>=0&&(i-n)*(o-a)-(r-n)*(s-a)>=0}function BE(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){var i=e;do{if(i.i!==e.i&&i.next.i!==e.i&&i.i!==t.i&&i.next.i!==t.i&&CE(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}(e,t)&&(FE(e,t)&&FE(t,e)&&function(e,t){var i=e,s=!1,r=(e.x+t.x)/2,o=(e.y+t.y)/2;do{i.y>o!=i.next.y>o&&i.next.y!==i.y&&r<(i.next.x-i.x)*(o-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==e);return s}(e,t)&&(wE(e.prev,e,t.prev)||wE(e,t.prev,t))||PE(e,t)&&wE(e.prev,e,e.next)>0&&wE(t.prev,t,t.next)>0)}function wE(e,t,i){return(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y)}function PE(e,t){return e.x===t.x&&e.y===t.y}function CE(e,t,i,s){var r=EE(wE(e,t,i)),o=EE(wE(e,t,s)),n=EE(wE(i,s,e)),a=EE(wE(i,s,t));return r!==o&&n!==a||(!(0!==r||!ME(e,i,t))||(!(0!==o||!ME(e,s,t))||(!(0!==n||!ME(i,e,s))||!(0!==a||!ME(i,t,s)))))}function ME(e,t,i){return t.x<=Math.max(e.x,i.x)&&t.x>=Math.min(e.x,i.x)&&t.y<=Math.max(e.y,i.y)&&t.y>=Math.min(e.y,i.y)}function EE(e){return e>0?1:e<0?-1:0}function FE(e,t){return wE(e.prev,e,e.next)<0?wE(e,t,e.next)>=0&&wE(e,e.prev,t)>=0:wE(e,t,e.prev)<0||wE(e,e.next,t)<0}function IE(e,t){var i=new TE(e.i,e.x,e.y),s=new TE(t.i,t.x,t.y),r=e.next,o=t.prev;return e.next=t,t.prev=e,i.next=r,r.prev=i,s.next=i,i.prev=s,o.next=s,s.prev=o,s}function DE(e,t,i,s){var r=new TE(e,t,i);return s?(r.next=s.next,r.prev=s,s.next.prev=r,s.next=r):(r.prev=r,r.next=r),r}function SE(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function TE(e,t,i){this.i=e,this.x=t,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function RE(e,t,i,s){for(var r=0,o=t,n=i-s;o0&&(s+=e[r-1].length,i.holes.push(s))}return i};const LE=d.vec2(),UE=d.vec3(),kE=d.vec3(),OE=d.vec3();class NE extends z{constructor(e,t={}){super("cityJSONLoader",e,t),this.dataSource=t.dataSource}get dataSource(){return this._dataSource}set dataSource(e){this._dataSource=e||new lE}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 Gc(this.viewer.scene,y.apply(e,{isModel:!0,edges:!0}));if(!e.src&&!e.cityJSON)return this.error("load() param expected: src or cityJSON"),t;const i={};if(e.src)this._loadModel(e.src,e,i,t);else{const s=this.viewer.scene.canvas.spinner;s.processes++,this._parseModel(e.cityJSON,e,i,t),s.processes--}return t}_loadModel(e,t,i,s){const r=this.viewer.scene.canvas.spinner;r.processes++,this._dataSource.getCityJSON(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){if(s.destroyed)return;const r=e.transform?this._transformVertices(e.vertices,e.transform,i.rotateX):e.vertices,o=t.stats||{};o.sourceFormat=e.type||"CityJSON",o.schemaVersion=e.version||"",o.title="",o.author="",o.created="",o.numMetaObjects=0,o.numPropertySets=0,o.numObjects=0,o.numGeometries=0,o.numTriangles=0,o.numVertices=0;const n=!1!==t.loadMetadata,a=n?{id:d.createUUID(),name:"Model",type:"Model"}:null,l=n?{id:"",projectId:"",author:"",createdAt:"",schema:e.version||"",creatingApplication:"",metaObjects:[a],propertySets:[]}:null,A={data:e,vertices:r,sceneModel:s,loadMetadata:n,metadata:l,rootMetaObject:a,nextId:0,stats:o};if(this._parseCityJSON(A),s.finalize(),n){const e=s.id;this.viewer.metaScene.createMetaModel(e,A.metadata,i)}s.scene.once("tick",(()=>{s.destroyed||(s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1))}))}_transformVertices(e,t,i){const s=[],r=t.scale||d.vec3([1,1,1]),o=t.translate||d.vec3([0,0,0]);for(let t=0,n=0;t0))return;const o=[];for(let i=0,s=t.geometry.length;i0){const r=t[s[0]];if(void 0!==r.value)n=e[r.value];else{const t=r.values;if(t){a=[];for(let s=0,r=t.length;s0&&(s.createEntity({id:i,meshIds:o,isObject:!0}),e.stats.numObjects++)}_parseGeometrySurfacesWithOwnMaterials(e,t,i,s){switch(t.type){case"MultiPoint":case"MultiLineString":break;case"MultiSurface":case"CompositeSurface":const r=t.boundaries;this._parseSurfacesWithOwnMaterials(e,i,r,s);break;case"Solid":const o=t.boundaries;for(let t=0;t0&&h.push(A.length);const i=this._extractLocalIndices(e,a[t],c,u);A.push(...i)}if(3===A.length)u.indices.push(A[0]),u.indices.push(A[1]),u.indices.push(A[2]);else if(A.length>3){const e=[];for(let t=0;t0&&n.indices.length>0){const t=""+e.nextId++;r.createMesh({id:t,primitive:"triangles",positions:n.positions,indices:n.indices,color:i&&i.diffuseColor?i.diffuseColor:[.8,.8,.8],opacity:1}),s.push(t),e.stats.numGeometries++,e.stats.numVertices+=n.positions.length/3,e.stats.numTriangles+=n.indices.length/3}}_parseSurfacesWithSharedMaterial(e,t,i,s){const r=e.vertices;for(let o=0;o0&&a.push(n.length);const l=this._extractLocalIndices(e,t[o][r],i,s);n.push(...l)}if(3===n.length)s.indices.push(n[0]),s.indices.push(n[1]),s.indices.push(n[2]);else if(n.length>3){let e=[];for(let t=0;t-1?e+"&_="+t:e+"?_="+t}getDotBIM(e,t,i){y.loadJSON(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}}class VE extends z{constructor(e,t={}){super("DotBIMLoader",e,t),this.dataSource=t.dataSource,this.objectDefaults=t.objectDefaults}set dataSource(e){this._dataSource=e||new QE}get dataSource(){return this._dataSource}set objectDefaults(e){this._objectDefaults=e||HP}get objectDefaults(){return this._objectDefaults}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 Gc(this.viewer.scene,y.apply(e,{isModel:!0,backfaces:e.backfaces,dtxEnabled:e.dtxEnabled,rotation:e.rotation,origin:e.origin})),i=t.id;if(!e.src&&!e.dotBIM)return this.error("load() param expected: src or dotBIM"),t;const s=e.objectDefaults||this._objectDefaults||HP;let r,o;if(e.includeTypes){r={};for(let t=0,i=e.includeTypes.length;t{const t=e.fileData,n=e.sceneModel,a={},l=d.createUUID(),A=d.createUUID(),h=d.createUUID(),c=d.createUUID(),u={metaObjects:[{id:l,name:"Project",type:"Project",parent:null},{id:A,name:"Site",type:"Site",parent:l},{id:h,name:"Building",type:"Building",parent:A},{id:c,name:"BuildingStorey",type:"BuildingStorey",parent:h}],propertySets:[]},p=(e,i)=>{if(a[e])return;const s=t.meshes.find((e=>e.mesh_id===i.mesh_id));n.createGeometry({id:e,primitive:"triangles",positions:s.coordinates,indices:s.indices}),a[e]=!0},f=t.elements;for(let e=0,i=f.length;ee.mesh_id===i.mesh_id));for(let t=0,i=e.length;t{n.destroyed||(n.scene.fire("modelLoaded",n.id),n.fire("loaded",!0,!1))}))};if(e.src){const i=e.src;this.viewer.scene.canvas.spinner.processes++,this._dataSource.getDotBIM(i,(e=>{n({fileData:e,sceneModel:t,nextId:0,error:function(e){}}),this.viewer.scene.canvas.spinner.processes--}),(e=>{this.viewer.scene.canvas.spinner.processes--,this.error(e)}))}else if(e.dotBIM){const i={fileData:e.dotBIM,sceneModel:t,nextId:0,error:function(e){}};n(i)}return t.once("destroyed",(()=>{this.viewer.metaScene.destroyMetaModel(i)})),t}destroy(){super.destroy()}}const HE=function(e){const t=t=>parseInt(e.substr(t+1,2),16)/255;return[t(0),t(2),t(4)]},jE=function(e){const t=[];for(let i=0;i=0?h:2*Math.PI-h}return r(e[0]-i[0])*(t[1]-i[1])-(t[0]-i[0])*(e[1]-i[1]);return(t,i,s,r)=>{const o=e(t,i,s),n=e(t,s,r),a=e(t,r,i);return!((o<0||n<0||a<0)&&(o>0||n>0||a>0))}}(),r=[],o=(i?t:t.slice(0).reverse()).map((e=>({idx:e})));o.forEach(((e,t)=>{e.prev=o[(t-1+o.length)%o.length],e.next=o[(t+1)%o.length]}));const n=d.vec2(),a=d.vec2();for(;o.length>2;){let t=0;for(;;){if(t>=o.length)throw`isCCW = ${i}; earIdx = ${t}; len = ${o.length}`;const r=o[t],l=e[r.prev.idx],A=e[r.idx],h=e[r.next.idx];if(d.subVec2(l,A,n),d.subVec2(h,A,a),n[0]*a[1]-n[1]*a[0]>=0&&o.every((t=>t===r||t===r.prev||t===r.next||!s(e[t.idx],l,A,h))))break;++t}const l=o[t];o.splice(t,1),r.push([l.idx,l.next.idx,l.prev.idx]);l.prev.next=l.next;l.next.prev=l.prev}return[e,r,i]},GE=function(e,t){const i=e.canvas.canvas,s=i.parentNode,r=document.createElement("div");s.insertBefore(r,i);let o=5;r.style.background=t,r.style.border="2px solid white",r.style.margin="0 0",r.style.zIndex="100",r.style.position="absolute",r.style.pointerEvents="none",r.style.display="none";const n=new pe(e,{}),a=e=>e+"px",l=function(){const e=n.canvasPos.slice();ge(i,s,e),r.style.left=a(e[0]-3-o/2),r.style.top=a(e[1]-3-o/2),r.style.borderRadius=a(2*o),r.style.width=a(o),r.style.height=a(o)},A=e.camera.on("viewMatrix",l),h=e.camera.on("projMatrix",l);return{update:function(e){e&&(n.worldPos=e,l()),r.style.display=e?"":"none"},setHighlighted:function(e){o=e?10:5,l()},getCanvasPos:()=>n.canvasPos,getWorldPos:()=>n.worldPos,destroy:function(){r.parentNode.removeChild(r),e.camera.off(A),e.camera.off(h),n.destroy()}}},zE=function(e,t,i){let s=null;const r=r=>{if(r){s&&s.destroy();try{const[o,n]=jE(r.map((e=>[e[0],e[2]]))),a=[].concat(...o.map((e=>[e[0],r[0][1],e[1]]))),l=[].concat(...n);s=new wr(e,{pickable:!1,geometry:new ei(e,{positions:a,indices:l,normals:d.buildNormals(a,l)}),material:new oi(e,{alpha:void 0!==i?i:.5,backfaces:!0,diffuse:HE(t)})})}catch(e){s=null}}s&&(s.visible=!!r)};return r(null),{updateBase:r,destroy:()=>s&&s.destroy()}},WE=function(e,t){return function(i,s,r){const o=e.scene,n=o.canvas.canvas,a=(e,t)=>(t[0]=e.clientX,t[1]=e.clientY,ge(n.ownerDocument.documentElement,n,t),t),l=e=>{const i=d.vec3(),s=d.vec3();return d.canvasPosToWorldRay(n,o.camera.viewMatrix,o.camera.projMatrix,o.camera.projection,e,i,s),t(i,s)};let A=!1;const h=function(){A=!1},c=function(){h(),n.removeEventListener("mousedown",p),n.removeEventListener("mousemove",f),e.cameraControl.off(g),n.removeEventListener("mouseup",m)},u=d.vec2(),p=function(e){1===e.which&&(a(e,u),A=!0)};n.addEventListener("mousedown",p);const f=function(e){const t=a(e,d.vec2());A&&d.distVec2(u,t)>20&&(h(),i())};n.addEventListener("mousemove",f);const g=e.cameraControl.on("rayMove",(e=>{const t=e.canvasPos;s(t,l(t))})),m=function(e){if(1===e.which&&A){c();const t=a(e,d.vec2());r(t,l(t))}};return n.addEventListener("mouseup",m),c}},KE=function(e,t,i,s){const r=-(d.dotVec3(i,t)-e)/d.dotVec3(s,t);{const e=d.vec3();return d.mulVec3Scalar(s,r,e),d.addVec3(i,e,e),e}};class XE extends R{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={},this.plugin.viewer.scene,this._geometry=t.geometry,t.onMouseOver,t.onMouseLeave,t.onContextMenu,this._alpha="alpha"in t&&void 0!==t.alpha?t.alpha:.5,this.color=t.color,this._visible=!0,this._rebuildMesh()}_rebuildMesh(){const e=this.plugin.viewer.scene,t=this._geometry.planeCoordinates.slice(),i=this._geometry.height<0,s=this._geometry.altitude+(i?this._geometry.height:0),r=this._geometry.height*(i?-1:1),[o,n,a]=jE(t),l=[],A=[],h=e=>{const t=l.length;for(let t of o)l.push([t[0],s+(e?r:0),t[1]]);for(let i of n)A.push(...(e?i:i.slice(0).reverse()).map((e=>e+t)))};h(!1),h(!0);for(let e=0;ee+c)))}this._zoneMesh&&this._zoneMesh.destroy();const c=[].concat(...l);this._zoneMesh=new wr(e,{edges:this._edges,geometry:new ei(e,{positions:c,indices:A,normals:d.buildNormals(c,A)}),material:new oi(e,{alpha:this._alpha,backfaces:!0,diffuse:HE(this._color)}),visible:this._visible}),this._zoneMesh.highlighted=this._highlighted,this._zoneMesh.zone=this;{const e=d.vec2(),t=d.vec2();let i=0;for(let s of n){const r=o[s[0]],n=o[s[1]],a=o[s[2]];d.subVec2(n,r,e),d.subVec2(a,r,t),i+=Math.abs(e[0]*t[1]-e[1]*t[0])}this._baseArea=i/2}this._metrics=null;const u=e=>Math.min(...l.map((t=>t[e]))),p=e=>Math.max(...l.map((t=>t[e]))),f=u(0),g=u(1),m=u(2),_=p(0),v=p(1),b=p(2);this._center=d.vec3([(f+_)/2,(g+v)/2,(m+b)/2])}get baseArea(){return this._baseArea}get area(){return this._getMetrics().area}get volume(){return this._getMetrics().volume}_getMetrics(){if(null===this._metrics){let e=0,t=0;const i=this._zoneMesh.geometry,s=[d.vec3(),d.vec3(),d.vec3()],r=d.vec3();for(let o=0;o{const s=t.map((t=>[t[0],e?r:o,t[1]]));i.push(e?s:s.slice(0).reverse())};n(!0),n(!1);const a=(e,i)=>[t[e][0],i,t[e][1]];for(let e=0;ei?a:n;h|=A,c.push(A)}switch(h){case n:case a:o.push(t);break;case l:break;case A:const i=[];for(let o=0;o=3&&o.push(i)}}i=o}if(0===i.length)return null;{const e=d.vec3([0,0,0]),t=new Set;for(const s of i)for(const i of s){const s=i.map((e=>e.toFixed(3))).join(":");t.has(s)||(t.add(s),d.addVec3(e,i,e))}return d.mulVec3Scalar(e,1/t.size,e),e}}get center(){return this._center}get altitude(){return this._geometry.altitude}set altitude(e){this._geometry.altitude=e,this._rebuildMesh()}get height(){return this._geometry.height}set height(e){this._geometry.height=e,this._rebuildMesh()}get highlighted(){return this._highlighted}set highlighted(e){this._highlighted=e,this._zoneMesh&&(this._zoneMesh.highlighted=e)}set color(e){this._color=e,this._zoneMesh&&(this._zoneMesh.material.diffuse=HE(this._color))}get color(){return this._color}set alpha(e){this._alpha=e,this._zoneMesh&&(this._zoneMesh.material.alpha=this._alpha)}get alpha(){return this._alpha}get edges(){return this._edges}set edges(e){this._edges=e,this._zoneMesh&&(this._zoneMesh.edges=this._edges)}set visible(e){this._visible=!!e,this._zoneMesh.visible=this._visible,this._needUpdate()}get visible(){return this._visible}getJSON(){return{id:this.id,geometry:this._geometry,alpha:this._alpha,color:this._color}}duplicate(){return this.plugin.createZone({id:d.createUUID(),geometry:{planeCoordinates:this._geometry.planeCoordinates.map((e=>e.slice())),altitude:this._geometry.altitude,height:this._geometry.height},alpha:this._alpha,color:this._color})}destroy(){this._zoneMesh.destroy(),super.destroy()}}class JE extends R{constructor(e,t,i){super(e.viewer.scene),this.zonesPlugin=e,this.pointerLens=t.pointerLens,this.createSelect3dPoint=i,this._deactivate=null}get active(){return!!this._deactivate}activate(e,t,i,s){if(this._deactivate)return;if("object"==typeof e&&null!==e){const r=e,o=(e,t)=>{if(e in r)return r[e];if(void 0!==t)return t;throw"config missing: "+e};e=o("altitude"),t=o("height"),i=o("color","#008000"),s=o("alpha",.5)}const r=this.zonesPlugin,o=r.viewer,n=o.scene,a=this,l=this.createSelect3dPoint(o,((t,i)=>KE(e,d.vec3([0,1,0]),t,i)));!function o(){const A=zE(n,i,s),h=function(e,t,i,s,r,o){const n=GE(e,t),a=GE(e,t),l=i?function(e){i.visible=!!e,e&&(i.canvasPos=e)}:()=>{};let A=s((()=>{l(null),n.update(null)}),((e,t)=>{l(e),n.update(t)}),(function(e,t){n.update(t),A=s((function(){l(null),a.update(null),r(null)}),(function(e,i){l(e),a.update(i),r(d.distVec3(t,i)>.01&&[t,i])}),(function(e,i){a.update(i),n.destroy(),a.destroy(),l(null),o([t,i])}))}));return{deactivate:function(){A(),n.destroy(),a.destroy(),l(null)}}}(n,i,a.pointerLens,l,(e=>{if(e){const t=e[0],i=e[1],s=e=>Math.min(t[e],i[e]),r=e=>Math.max(t[e],i[e]),o=s(0),n=s(1),a=s(2),l=r(0);r(1);const h=r(2);A.updateBase([[o,n,h],[l,n,h],[l,n,a],[o,n,a]])}else A.updateBase(null)}),(n=>{A.destroy();const l=function(e,t,i,s,r,o,n){const a=i=>Math.min(e[i],t[i]),l=i=>Math.max(e[i],t[i]),A=a(0),h=a(2),c=l(0),u=l(2);return n.createZone({id:d.createUUID(),geometry:{planeCoordinates:[[A,u],[c,u],[c,h],[A,h]],altitude:i,height:s},alpha:o,color:r})}(n[0],n[1],e,t,i,s,r);let h=!0;a._deactivate=()=>{h=!1},a.fire("zoneEnd",l),h&&o()})).deactivate;a._deactivate=()=>{h(),A.destroy()}}()}deactivate(){this._deactivate&&(this._deactivate(),this._deactivate=null)}destroy(){this.deactivate(),super.destroy()}}class YE extends JE{constructor(e,t={}){super(e,t,((e,t)=>WE(e,t)))}}class ZE extends JE{constructor(e,t={}){const i=new G(e.viewer);super(e,t,((e,t)=>be(e,i,t))),this.pointerCircle=i}destroy(){this.pointerCircle.destroy(),super.destroy()}}class qE extends z{constructor(e,t={}){super("Zones",e),this._pointerLens=t.pointerLens,this._container=t.container||document.body,this._zones=[],this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.zIndex=t.zIndex||1e4,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,zone:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,zone:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,zone:t,event:e})}}createZone(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=new XE(this,{id:e.id,plugin:this,container:this._container,geometry:e.geometry,alpha:e.alpha,color:e.color,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._zones.push(t),t.on("destroyed",(()=>{const e=this._zones.indexOf(t);e>=0&&this._zones.splice(e,1)})),this.fire("zoneCreated",t),t}get zones(){return this._zones}destroy(){super.destroy()}}const $E=function(e,t,i,s,r,o,n,a,l){const A=o?function(e){o.visible=!!e,e&&(o.canvasPos=e)}:()=>{};let h;const c=[()=>A(null)],u=zE(e,s,r);return c.push((()=>u.destroy())),function o(p){const f=GE(e,s),g=p.length>0&&function(e,t,i){const s=e.canvas.canvas,r=new pe(e,{});r.worldPos=i;const o=new pe(e,{}),n=s.ownerDocument.body,a=new ye(n,{color:t,thickness:1,thicknessClickable:6});a.setVisible(!1);const l=function(){const e=r.canvasPos.slice(),t=o.canvasPos.slice();ge(s,n,e),ge(s,n,t),a.setStartAndEnd(e[0],e[1],t[0],t[1])},A=e.camera.on("viewMatrix",l),h=e.camera.on("projMatrix",l);return{update:function(e){e&&(o.worldPos=e,l()),a.setVisible(!!e)},destroy:function(){e.camera.off(A),e.camera.off(h),r.destroy(),o.destroy(),a.destroy()}}}(e,s,p[p.length-1].getWorldPos());c.push((()=>{f.destroy(),g&&g.destroy()}));const m=p.length>0&&p[0],_=function(e){const t=m&&m.getCanvasPos();return t&&d.distVec2(t,e)<10&&{canvasPos:t,worldPos:m.getWorldPos()}},v=function(){const e=(e,t,i)=>t[0]<=Math.max(e[0],i[0])&&t[0]>=Math.min(e[0],i[0])&&t[1]<=Math.max(e[1],i[1])&&t[1]>=Math.min(e[1],i[1]),t=(e,t,i)=>{const s=(t[1]-e[1])*(i[0]-t[0])-(t[0]-e[0])*(i[1]-t[1]);return 0===s?0:s>0?1:2};return function(i,s){const r=i[i.length-2],o=i[i.length-1];for(let n=s?1:0;n{A(null),f.update(null),g&&g.update(null),u.updateBase(p.length>2?p.map((e=>e.getWorldPos())):null)}),((e,t)=>{const i=p.length>2&&_(e);if(m&&m.setHighlighted(!!i),A(i?i.canvasPos:e),f.update(!i&&t),g&&g.update(i?i.worldPos:t),p.length>=2){const e=p.map((e=>e.getWorldPos())).concat(i?[]:[t]),s=v(e.map((e=>[e[0],e[2]])),i);u.updateBase(s?null:e)}else u.updateBase(null)}),(function(e,a){const A=p.length>2&&_(e),h=p.map((e=>e.getWorldPos())).concat(A?[]:[a]);u.updateBase(h);const m=h.map((e=>[e[0],e[2]]));p.length>2&&v(m,A)?(c.pop()(),o(p)):A?(f.update(a),c.forEach((e=>e())),l(n.createZone({id:d.createUUID(),geometry:{planeCoordinates:m,altitude:t,height:i},alpha:r,color:s}))):(f.update(a),g&&g.update(a),o(p.concat(f)))}))}([]),{closeSurface:function(){throw"TODO"},deactivate:function(){h(),c.forEach((e=>e()))}}};class eF extends R{constructor(e,t={}){super(e.viewer.scene),this.zonesPlugin=e,this.pointerLens=t.pointerLens,this._action=null}get active(){return!!this._action}activate(e,t,i,s){if("object"==typeof e&&null!==e){const r=e,o=(e,t)=>{if(e in r)return r[e];if(void 0!==t)return t;throw"config missing: "+e};e=o("altitude"),t=o("height"),i=o("color","#008000"),s=o("alpha",.5)}if(this._action)return;const r=this.zonesPlugin,o=r.viewer,n=o.scene,a=this,l=WE(o,(function(t,i){return KE(e,d.vec3([0,1,0]),t,i)}));!function o(){a._action=$E(n,e,t,i,s,a.pointerLens,r,l,(e=>{let t=!0;a._action={deactivate:()=>{t=!1}},a.fire("zoneEnd",e),t&&o()}))}()}deactivate(){this._action&&(this._action.deactivate(),this._action=null)}destroy(){this.deactivate(),super.destroy()}}class tF extends R{constructor(e,t={}){super(e.viewer.scene),this.zonesPlugin=e,this.pointerLens=t.pointerLens,this.pointerCircle=new G(e.viewer),this._action=null}get active(){return!!this._action}activate(e,t,i,s){if("object"==typeof e&&null!==e){const r=e,o=(e,t)=>{if(e in r)return r[e];if(void 0!==t)return t;throw"config missing: "+e};e=o("altitude"),t=o("height"),i=o("color","#008000"),s=o("alpha",.5)}if(this._action)return;const r=this.zonesPlugin,o=r.viewer,n=o.scene,a=this,l=be(o,this.pointerCircle,(function(t,i){return KE(e,d.vec3([0,1,0]),t,i)}));!function o(){a._action=$E(n,e,t,i,s,a.pointerLens,r,l,(e=>{let t=!0;a._action={deactivate:()=>{t=!1}},a.fire("zoneEnd",e),t&&o()}))}()}deactivate(){this._action&&(this._action.deactivate(),this._action=null)}destroy(){this.deactivate(),super.destroy()}}class iF extends R{constructor(e,t,i,s){const r=e.plugin.viewer,o=r.scene;super(o);const n=e._geometry.altitude,a=e._geometry.planeCoordinates.map((t=>{const i=o.canvas.canvas.ownerDocument.body,s=new me(o,{},i,{fillColor:e._color});return s.worldPos=d.vec3([t[0],n,t[1]]),s.on("worldPos",(function(){t[0]=s.worldPos[0],t[1]=s.worldPos[2];try{e._rebuildMesh()}catch(t){e._zoneMesh&&(e._zoneMesh.destroy(),e._zoneMesh=null)}})),s})),l=ve({viewer:r,handleMouseEvents:i,handleTouchEvents:s,pointerLens:t&&t.pointerLens,dots:a,ray2WorldPos:(e,t)=>KE(n,d.vec3([0,1,0]),e,t),onEnd:(t,i)=>(e._zoneMesh&&this.fire("edited"),!!e._zoneMesh)}),A=function(){l(),a.forEach((e=>e.destroy()))},h=e.on("destroyed",A);this._deactivate=function(){e.off("destroyed",h),A()}}deactivate(){this._deactivate(),super.destroy()}}class sF extends iF{constructor(e,t){super(e,t,!0,!1)}}class rF extends iF{constructor(e,t){super(e,t,!1,!0)}}class oF extends R{constructor(e,t,i,s){const r=e.plugin.viewer,o=r.scene,n=o.canvas.canvas;super(o);const a=this,l=e._geometry.altitude,A=t&&t.pointerLens,h=A?function(e){A.visible=!!e,e&&(A.canvasPos=e)}:()=>{},c=e=>{const t=d.vec3(),i=d.vec3();return d.canvasPosToWorldRay(n,o.camera.viewMatrix,o.camera.projMatrix,o.camera.projection,e,t,i),s=t,r=i,KE(l,d.vec3([0,1,0]),s,r);var s,r},u=(e,t)=>(t[0]=e.clientX,t[1]=e.clientY,ge(n.ownerDocument.documentElement,n,t),t),p=function(e,t){const i=e=>{e.preventDefault(),t(e)};return n.addEventListener(e,i),()=>n.removeEventListener(e,i)};let f=()=>{};const g=function(t,i,s,o){const l=o(t),A=u(l,d.vec2()),g=r.scene.pick({canvasPos:A,includeEntities:[e._zoneMesh.id]});if((g&&g.entity&&g.entity.zone)===e){f(),n.style.cursor="move",r.cameraControl.active=!1;const t=function(){const t=e._geometry.planeCoordinates.map((e=>e.slice())),i=c(A),s=d.vec2([i[0],i[2]]),r=d.vec2();return function(i){const o=c(i);r[0]=o[0],r[1]=o[2],d.subVec2(s,r,r),e._geometry.planeCoordinates.forEach(((e,i)=>{d.subVec2(t[i],r,e)}));try{e._rebuildMesh()}catch(t){e._zoneMesh&&(e._zoneMesh.destroy(),e._zoneMesh=null)}}}(),l=p(i,(function(e){const i=o(e);if(i){const e=u(i,d.vec2());t(e),h(e)}})),g=p(s,(function(e){const i=o(e);if(i){const e=u(i,d.vec2());t(e),h(null),f(),a.fire("translated")}}));f=function(){f=()=>{},n.style.cursor="default",r.cameraControl.active=!0,l(),g()}}},m=[];i&&m.push(p("mousedown",(e=>{1===e.which&&g(e,"mousemove","mouseup",(e=>1===e.which&&e))}))),s&&m.push(p("touchstart",(e=>{if(1===e.touches.length){const t=e.touches[0].identifier;g(e,"touchmove","touchend",(e=>[...e.changedTouches].find((e=>e.identifier===t))))}})));const _=function(){f(),m.forEach((e=>e())),h(null)},v=e.on("destroyed",_);this._deactivate=function(){e.off("destroyed",v),_()}}deactivate(){this._deactivate(),super.destroy()}}class nF extends oF{constructor(e,t){super(e,t,!0,!1)}}class aF extends oF{constructor(e,t){super(e,t,!1,!0)}}export{Gi as AlphaFormat,Ht as AmbientLight,De as AngleMeasurementEditMouseControl,Se as AngleMeasurementEditTouchControl,Ce as AngleMeasurementsControl,Me as AngleMeasurementsMouseControl,Ee as AngleMeasurementsPlugin,Fe as AngleMeasurementsTouchControl,ke as AnnotationsPlugin,Ir as AxisGizmoPlugin,Zc as BCFViewpointsPlugin,bo as Bitmap,Ri as ByteType,Hu as CameraMemento,yu as CameraPath,Eu as CameraPathAnimation,NE as CityJSONLoaderPlugin,yi as ClampToEdgeWrapping,R as Component,Ts as CompressedMediaType,Fn as Configs,o as ContextMenu,Ku as CubicBezierCurve,_u as Curve,hc as DefaultLoadingManager,Ji as DepthFormat,Yi as DepthStencilFormat,Vt as DirLight,hu as DistanceMeasurementEditControl,cu as DistanceMeasurementEditMouseControl,uu as DistanceMeasurementEditTouchControl,nu as DistanceMeasurementsControl,au as DistanceMeasurementsMouseControl,lu as DistanceMeasurementsPlugin,Au as DistanceMeasurementsTouchControl,me as Dot3D,QE as DotBIMDefaultDataSource,VE as DotBIMLoaderPlugin,Ai as EdgeMaterial,ai as EmphasisMaterial,BC as FaceAlignedSectionPlanesPlugin,du as FastNavPlugin,Ni as FloatType,ro as Fresnel,N as Frustum,O as FrustumPlane,Is as GIFMediaType,pu as GLTFDefaultDataSource,jP as GLTFLoaderPlugin,Qi as HalfFloatType,Tu as ImagePlane,ki as IntType,Ds as JPEGMediaType,gc as KTX2TextureTranscoder,nE as LASLoaderPlugin,Hr as LambertMaterial,Qu as LightMap,Wc as LineSet,Es as LinearEncoding,Ei as LinearFilter,Si as LinearMipMapLinearFilter,Ii as LinearMipMapNearestFilter,Di as LinearMipmapLinearFilter,Fi as LinearMipmapNearestFilter,cc as Loader,Ac as LoadingManager,fu as LocaleService,Xi as LuminanceAlphaFormat,Ki as LuminanceFormat,e as Map,pe as Marker,H as MarqueePicker,j as MarqueePickerMouseControl,wr as Mesh,To as MeshSurfaceArea,Po as MeshVolume,zr as MetallicMaterial,xi as MirroredRepeatWrapping,Gu as ModelMemento,KP as NavCubePlugin,Bi as NearestFilter,Mi as NearestMipMapLinearFilter,wi as NearestMipMapNearestFilter,Ci as NearestMipmapLinearFilter,Pi as NearestMipmapNearestFilter,Vr as Node,iC as OBJLoaderPlugin,f as ObjectsKdTree3,Wu as ObjectsMemento,Ss as PNGMediaType,Xu as Path,Yu as PerformanceModel,oi as PhongMaterial,Ge as PickResult,z as Plugin,Ru as PointLight,G as PointerCircle,n as PointerLens,Ju as QuadraticBezierCurve,g as Queue,Wi as RGBAFormat,ts as RGBAIntegerFormat,ws as RGBA_ASTC_10x10_Format,ys as RGBA_ASTC_10x5_Format,xs as RGBA_ASTC_10x6_Format,Bs as RGBA_ASTC_10x8_Format,Ps as RGBA_ASTC_12x10_Format,Cs as RGBA_ASTC_12x12_Format,ds as RGBA_ASTC_4x4_Format,ps as RGBA_ASTC_5x4_Format,fs as RGBA_ASTC_5x5_Format,gs as RGBA_ASTC_6x5_Format,ms as RGBA_ASTC_6x6_Format,_s as RGBA_ASTC_8x5_Format,vs as RGBA_ASTC_8x6_Format,bs as RGBA_ASTC_8x8_Format,Ms as RGBA_BPTC_Format,us as RGBA_ETC2_EAC_Format,As as RGBA_PVRTC_2BPPV1_Format,ls as RGBA_PVRTC_4BPPV1_Format,ss as RGBA_S3TC_DXT1_Format,rs as RGBA_S3TC_DXT3_Format,os as RGBA_S3TC_DXT5_Format,zi as RGBFormat,hs as RGB_ETC1_Format,cs as RGB_ETC2_Format,as as RGB_PVRTC_2BPPV1_Format,ns as RGB_PVRTC_4BPPV1_Format,is as RGB_S3TC_DXT1_Format,$i as RGFormat,es as RGIntegerFormat,ei as ReadableGeometry,Zi as RedFormat,qi as RedIntegerFormat,Nu as ReflectionMap,bi as RepeatWrapping,PC as STLDefaultDataSource,RC as STLLoaderPlugin,Gc as SceneModel,Oo as SceneModelMesh,Lc as SceneModelTransform,Dr as SectionPlane,hC as SectionPlanesPlugin,Li as ShortType,Zu as Skybox,wC as SkyboxesPlugin,Xr as SpecularMaterial,vu as SplineCurve,Vu as SpriteMarker,fC as StoreyViewsPlugin,so as Texture,qu as TextureTranscoder,kC as TreeViewPlugin,Ti as UnsignedByteType,ji as UnsignedInt248Type,Oi as UnsignedIntType,Vi as UnsignedShort4444Type,Hi as UnsignedShort5551Type,Ui as UnsignedShortType,ao as VBOGeometry,VC as ViewCullPlugin,Qb as Viewer,qM as WebIFCLoaderPlugin,pc as WorkerPool,HC as XKTDefaultDataSource,LM as XKTLoaderPlugin,YM as XML3DLoaderPlugin,iF as ZoneEditControl,sF as ZoneEditMouseControl,rF as ZoneEditTouchControl,oF as ZoneTranslateControl,nF as ZoneTranslateMouseControl,aF as ZoneTranslateTouchControl,YE as ZonesMouseControl,qE as ZonesPlugin,eF as ZonesPolysurfaceMouseControl,tF as ZonesPolysurfaceTouchControl,ZE as ZonesTouchControl,_e as activateDraggableDot,ve as activateDraggableDots,ti as buildBoxGeometry,co as buildBoxLinesGeometry,uo as buildBoxLinesGeometryFromAABB,Cr as buildCylinderGeometry,po as buildGridGeometry,vo as buildLineGeometry,fo as buildPlaneGeometry,mo as buildPolylineGeometry,_o as buildPolylineGeometryFromCurve,Mr as buildSphereGeometry,go as buildTorusGeometry,Fr as buildVectorTextGeometry,J as createRTCViewMat,V as frustumIntersectsAABB3,_c as getKTX2TextureTranscoder,$ as getPlaneRTCPos,yo as isTriangleMeshSolid,Ao as load3DSGeometry,ho as loadOBJGeometry,d as math,Ro as meshSurfaceArea,Co as meshVolume,q as rtcToWorldPos,Fs as sRGBEncoding,Q as setFrustum,m as stats,be as touchPointSelector,ge as transformToNode,y as utils,Y as worldToRTCPos,Z as worldToRTCPositions}; +***************************************************************************** */var Hd=function(e,t){return Hd=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},Hd(e,t)};function jd(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}Hd(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}var Gd=function(){return Gd=Object.assign||function(e){for(var t,i=1,s=arguments.length;i0&&r[r.length-1])||6!==o[0]&&2!==o[0])){n=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]=55296&&r<=56319&&i>10),n%1024+56320)),(r+1===i||s.length>16384)&&(o+=String.fromCharCode.apply(String,s),s.length=0)}return o},qd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",$d="undefined"==typeof Uint8Array?[]:new Uint8Array(256),ep=0;ep=0){if(e<55296||e>56319&&e<=65535)return t=((t=this.index[e>>5])<<2)+(31&e),this.data[t];if(e<=65535)return t=((t=this.index[2048+(e-55296>>5)])<<2)+(31&e),this.data[t];if(e>11),t=this.index[t],t+=e>>5&63,t=((t=this.index[t])<<2)+(31&e),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},e}(),np="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ap="undefined"==typeof Uint8Array?[]:new Uint8Array(256),lp=0;lp>4,h[l++]=(15&s)<<4|r>>2,h[l++]=(3&r)<<6|63&o;return A}(e),n=Array.isArray(o)?function(e){for(var t=e.length,i=[],s=0;s0;){var n=s[--o];if(Array.isArray(e)?-1!==e.indexOf(n):e===n)for(var a=i;a<=s.length;){var l;if((l=s[++a])===t)return!0;if(l!==Ap)break}if(n!==Ap)break}return!1},jp=function(e,t){for(var i=e;i>=0;){var s=t[i];if(s!==Ap)return s;i--}return 0},Gp=function(e,t,i,s,r){if(0===i[s])return"×";var o=s-1;if(Array.isArray(r)&&!0===r[o])return"×";var n=o-1,a=o+1,l=t[o],A=n>=0?t[n]:0,h=t[a];if(2===l&&3===h)return"×";if(-1!==Up.indexOf(l))return"!";if(-1!==Up.indexOf(h))return"×";if(-1!==Op.indexOf(h))return"×";if(8===jp(o,t))return"÷";if(11===Rp.get(e[o]))return"×";if((l===wp||l===Pp)&&11===Rp.get(e[a]))return"×";if(7===l||7===h)return"×";if(9===l)return"×";if(-1===[Ap,hp,cp].indexOf(l)&&9===h)return"×";if(-1!==[up,dp,pp,_p,xp].indexOf(h))return"×";if(jp(o,t)===mp)return"×";if(Hp(23,mp,o,t))return"×";if(Hp([up,dp],gp,o,t))return"×";if(Hp(12,12,o,t))return"×";if(l===Ap)return"÷";if(23===l||23===h)return"×";if(16===h||16===l)return"÷";if(-1!==[hp,cp,gp].indexOf(h)||14===l)return"×";if(36===A&&-1!==Vp.indexOf(l))return"×";if(l===xp&&36===h)return"×";if(h===fp)return"×";if(-1!==Lp.indexOf(h)&&l===vp||-1!==Lp.indexOf(l)&&h===vp)return"×";if(l===yp&&-1!==[Ep,wp,Pp].indexOf(h)||-1!==[Ep,wp,Pp].indexOf(l)&&h===bp)return"×";if(-1!==Lp.indexOf(l)&&-1!==kp.indexOf(h)||-1!==kp.indexOf(l)&&-1!==Lp.indexOf(h))return"×";if(-1!==[yp,bp].indexOf(l)&&(h===vp||-1!==[mp,cp].indexOf(h)&&t[a+1]===vp)||-1!==[mp,cp].indexOf(l)&&h===vp||l===vp&&-1!==[vp,xp,_p].indexOf(h))return"×";if(-1!==[vp,xp,_p,up,dp].indexOf(h))for(var c=o;c>=0;){if((u=t[c])===vp)return"×";if(-1===[xp,_p].indexOf(u))break;c--}if(-1!==[yp,bp].indexOf(h))for(c=-1!==[up,dp].indexOf(l)?n:o;c>=0;){var u;if((u=t[c])===vp)return"×";if(-1===[xp,_p].indexOf(u))break;c--}if(Fp===l&&-1!==[Fp,Ip,Cp,Mp].indexOf(h)||-1!==[Ip,Cp].indexOf(l)&&-1!==[Ip,Dp].indexOf(h)||-1!==[Dp,Mp].indexOf(l)&&h===Dp)return"×";if(-1!==Qp.indexOf(l)&&-1!==[fp,bp].indexOf(h)||-1!==Qp.indexOf(h)&&l===yp)return"×";if(-1!==Lp.indexOf(l)&&-1!==Lp.indexOf(h))return"×";if(l===_p&&-1!==Lp.indexOf(h))return"×";if(-1!==Lp.concat(vp).indexOf(l)&&h===mp&&-1===Tp.indexOf(e[a])||-1!==Lp.concat(vp).indexOf(h)&&l===dp)return"×";if(41===l&&41===h){for(var d=i[o],p=1;d>0&&41===t[--d];)p++;if(p%2!=0)return"×"}return l===wp&&h===Pp?"×":"÷"},zp=function(e,t){t||(t={lineBreak:"normal",wordBreak:"normal"});var i=function(e,t){void 0===t&&(t="strict");var i=[],s=[],r=[];return e.forEach((function(e,o){var n=Rp.get(e);if(n>50?(r.push(!0),n-=50):r.push(!1),-1!==["normal","auto","loose"].indexOf(t)&&-1!==[8208,8211,12316,12448].indexOf(e))return s.push(o),i.push(16);if(4===n||11===n){if(0===o)return s.push(o),i.push(Bp);var a=i[o-1];return-1===Np.indexOf(a)?(s.push(s[o-1]),i.push(a)):(s.push(o),i.push(Bp))}return s.push(o),31===n?i.push("strict"===t?gp:Ep):n===Sp||29===n?i.push(Bp):43===n?e>=131072&&e<=196605||e>=196608&&e<=262141?i.push(Ep):i.push(Bp):void i.push(n)})),[s,i,r]}(e,t.lineBreak),s=i[0],r=i[1],o=i[2];"break-all"!==t.wordBreak&&"break-word"!==t.wordBreak||(r=r.map((function(e){return-1!==[vp,Bp,Sp].indexOf(e)?Ep:e})));var n="keep-all"===t.wordBreak?o.map((function(t,i){return t&&e[i]>=19968&&e[i]<=40959})):void 0;return[s,r,n]},Wp=function(){function e(e,t,i,s){this.codePoints=e,this.required="!"===t,this.start=i,this.end=s}return e.prototype.slice=function(){return Zd.apply(void 0,this.codePoints.slice(this.start,this.end))},e}(),Kp=function(e){return e>=48&&e<=57},Xp=function(e){return Kp(e)||e>=65&&e<=70||e>=97&&e<=102},Jp=function(e){return 10===e||9===e||32===e},Yp=function(e){return function(e){return function(e){return e>=97&&e<=122}(e)||function(e){return e>=65&&e<=90}(e)}(e)||function(e){return e>=128}(e)||95===e},Zp=function(e){return Yp(e)||Kp(e)||45===e},qp=function(e){return e>=0&&e<=8||11===e||e>=14&&e<=31||127===e},$p=function(e,t){return 92===e&&10!==t},ef=function(e,t,i){return 45===e?Yp(t)||$p(t,i):!!Yp(e)||!(92!==e||!$p(e,t))},tf=function(e,t,i){return 43===e||45===e?!!Kp(t)||46===t&&Kp(i):Kp(46===e?t:e)},sf=function(e){var t=0,i=1;43!==e[t]&&45!==e[t]||(45===e[t]&&(i=-1),t++);for(var s=[];Kp(e[t]);)s.push(e[t++]);var r=s.length?parseInt(Zd.apply(void 0,s),10):0;46===e[t]&&t++;for(var o=[];Kp(e[t]);)o.push(e[t++]);var n=o.length,a=n?parseInt(Zd.apply(void 0,o),10):0;69!==e[t]&&101!==e[t]||t++;var l=1;43!==e[t]&&45!==e[t]||(45===e[t]&&(l=-1),t++);for(var A=[];Kp(e[t]);)A.push(e[t++]);var h=A.length?parseInt(Zd.apply(void 0,A),10):0;return i*(r+a*Math.pow(10,-n))*Math.pow(10,l*h)},rf={type:2},of={type:3},nf={type:4},af={type:13},lf={type:8},Af={type:21},hf={type:9},cf={type:10},uf={type:11},df={type:12},pf={type:14},ff={type:23},gf={type:1},mf={type:25},_f={type:24},vf={type:26},bf={type:27},yf={type:28},xf={type:29},Bf={type:31},wf={type:32},Pf=function(){function e(){this._value=[]}return e.prototype.write=function(e){this._value=this._value.concat(Yd(e))},e.prototype.read=function(){for(var e=[],t=this.consumeToken();t!==wf;)e.push(t),t=this.consumeToken();return e},e.prototype.consumeToken=function(){var e=this.consumeCodePoint();switch(e){case 34:return this.consumeStringToken(34);case 35:var t=this.peekCodePoint(0),i=this.peekCodePoint(1),s=this.peekCodePoint(2);if(Zp(t)||$p(i,s)){var r=ef(t,i,s)?2:1;return{type:5,value:this.consumeName(),flags:r}}break;case 36:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),af;break;case 39:return this.consumeStringToken(39);case 40:return rf;case 41:return of;case 42:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),pf;break;case 43:if(tf(e,this.peekCodePoint(0),this.peekCodePoint(1)))return this.reconsumeCodePoint(e),this.consumeNumericToken();break;case 44:return nf;case 45:var o=e,n=this.peekCodePoint(0),a=this.peekCodePoint(1);if(tf(o,n,a))return this.reconsumeCodePoint(e),this.consumeNumericToken();if(ef(o,n,a))return this.reconsumeCodePoint(e),this.consumeIdentLikeToken();if(45===n&&62===a)return this.consumeCodePoint(),this.consumeCodePoint(),_f;break;case 46:if(tf(e,this.peekCodePoint(0),this.peekCodePoint(1)))return this.reconsumeCodePoint(e),this.consumeNumericToken();break;case 47:if(42===this.peekCodePoint(0))for(this.consumeCodePoint();;){var l=this.consumeCodePoint();if(42===l&&47===(l=this.consumeCodePoint()))return this.consumeToken();if(-1===l)return this.consumeToken()}break;case 58:return vf;case 59:return bf;case 60:if(33===this.peekCodePoint(0)&&45===this.peekCodePoint(1)&&45===this.peekCodePoint(2))return this.consumeCodePoint(),this.consumeCodePoint(),mf;break;case 64:var A=this.peekCodePoint(0),h=this.peekCodePoint(1),c=this.peekCodePoint(2);if(ef(A,h,c))return{type:7,value:this.consumeName()};break;case 91:return yf;case 92:if($p(e,this.peekCodePoint(0)))return this.reconsumeCodePoint(e),this.consumeIdentLikeToken();break;case 93:return xf;case 61:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),lf;break;case 123:return uf;case 125:return df;case 117:case 85:var u=this.peekCodePoint(0),d=this.peekCodePoint(1);return 43!==u||!Xp(d)&&63!==d||(this.consumeCodePoint(),this.consumeUnicodeRangeToken()),this.reconsumeCodePoint(e),this.consumeIdentLikeToken();case 124:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),hf;if(124===this.peekCodePoint(0))return this.consumeCodePoint(),Af;break;case 126:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),cf;break;case-1:return wf}return Jp(e)?(this.consumeWhiteSpace(),Bf):Kp(e)?(this.reconsumeCodePoint(e),this.consumeNumericToken()):Yp(e)?(this.reconsumeCodePoint(e),this.consumeIdentLikeToken()):{type:6,value:Zd(e)}},e.prototype.consumeCodePoint=function(){var e=this._value.shift();return void 0===e?-1:e},e.prototype.reconsumeCodePoint=function(e){this._value.unshift(e)},e.prototype.peekCodePoint=function(e){return e>=this._value.length?-1:this._value[e]},e.prototype.consumeUnicodeRangeToken=function(){for(var e=[],t=this.consumeCodePoint();Xp(t)&&e.length<6;)e.push(t),t=this.consumeCodePoint();for(var i=!1;63===t&&e.length<6;)e.push(t),t=this.consumeCodePoint(),i=!0;if(i)return{type:30,start:parseInt(Zd.apply(void 0,e.map((function(e){return 63===e?48:e}))),16),end:parseInt(Zd.apply(void 0,e.map((function(e){return 63===e?70:e}))),16)};var s=parseInt(Zd.apply(void 0,e),16);if(45===this.peekCodePoint(0)&&Xp(this.peekCodePoint(1))){this.consumeCodePoint(),t=this.consumeCodePoint();for(var r=[];Xp(t)&&r.length<6;)r.push(t),t=this.consumeCodePoint();return{type:30,start:s,end:parseInt(Zd.apply(void 0,r),16)}}return{type:30,start:s,end:s}},e.prototype.consumeIdentLikeToken=function(){var e=this.consumeName();return"url"===e.toLowerCase()&&40===this.peekCodePoint(0)?(this.consumeCodePoint(),this.consumeUrlToken()):40===this.peekCodePoint(0)?(this.consumeCodePoint(),{type:19,value:e}):{type:20,value:e}},e.prototype.consumeUrlToken=function(){var e=[];if(this.consumeWhiteSpace(),-1===this.peekCodePoint(0))return{type:22,value:""};var t=this.peekCodePoint(0);if(39===t||34===t){var i=this.consumeStringToken(this.consumeCodePoint());return 0===i.type&&(this.consumeWhiteSpace(),-1===this.peekCodePoint(0)||41===this.peekCodePoint(0))?(this.consumeCodePoint(),{type:22,value:i.value}):(this.consumeBadUrlRemnants(),ff)}for(;;){var s=this.consumeCodePoint();if(-1===s||41===s)return{type:22,value:Zd.apply(void 0,e)};if(Jp(s))return this.consumeWhiteSpace(),-1===this.peekCodePoint(0)||41===this.peekCodePoint(0)?(this.consumeCodePoint(),{type:22,value:Zd.apply(void 0,e)}):(this.consumeBadUrlRemnants(),ff);if(34===s||39===s||40===s||qp(s))return this.consumeBadUrlRemnants(),ff;if(92===s){if(!$p(s,this.peekCodePoint(0)))return this.consumeBadUrlRemnants(),ff;e.push(this.consumeEscapedCodePoint())}else e.push(s)}},e.prototype.consumeWhiteSpace=function(){for(;Jp(this.peekCodePoint(0));)this.consumeCodePoint()},e.prototype.consumeBadUrlRemnants=function(){for(;;){var e=this.consumeCodePoint();if(41===e||-1===e)return;$p(e,this.peekCodePoint(0))&&this.consumeEscapedCodePoint()}},e.prototype.consumeStringSlice=function(e){for(var t="";e>0;){var i=Math.min(5e4,e);t+=Zd.apply(void 0,this._value.splice(0,i)),e-=i}return this._value.shift(),t},e.prototype.consumeStringToken=function(e){for(var t="",i=0;;){var s=this._value[i];if(-1===s||void 0===s||s===e)return{type:0,value:t+=this.consumeStringSlice(i)};if(10===s)return this._value.splice(0,i),gf;if(92===s){var r=this._value[i+1];-1!==r&&void 0!==r&&(10===r?(t+=this.consumeStringSlice(i),i=-1,this._value.shift()):$p(s,r)&&(t+=this.consumeStringSlice(i),t+=Zd(this.consumeEscapedCodePoint()),i=-1))}i++}},e.prototype.consumeNumber=function(){var e=[],t=4,i=this.peekCodePoint(0);for(43!==i&&45!==i||e.push(this.consumeCodePoint());Kp(this.peekCodePoint(0));)e.push(this.consumeCodePoint());i=this.peekCodePoint(0);var s=this.peekCodePoint(1);if(46===i&&Kp(s))for(e.push(this.consumeCodePoint(),this.consumeCodePoint()),t=8;Kp(this.peekCodePoint(0));)e.push(this.consumeCodePoint());i=this.peekCodePoint(0),s=this.peekCodePoint(1);var r=this.peekCodePoint(2);if((69===i||101===i)&&((43===s||45===s)&&Kp(r)||Kp(s)))for(e.push(this.consumeCodePoint(),this.consumeCodePoint()),t=8;Kp(this.peekCodePoint(0));)e.push(this.consumeCodePoint());return[sf(e),t]},e.prototype.consumeNumericToken=function(){var e=this.consumeNumber(),t=e[0],i=e[1],s=this.peekCodePoint(0),r=this.peekCodePoint(1),o=this.peekCodePoint(2);return ef(s,r,o)?{type:15,number:t,flags:i,unit:this.consumeName()}:37===s?(this.consumeCodePoint(),{type:16,number:t,flags:i}):{type:17,number:t,flags:i}},e.prototype.consumeEscapedCodePoint=function(){var e=this.consumeCodePoint();if(Xp(e)){for(var t=Zd(e);Xp(this.peekCodePoint(0))&&t.length<6;)t+=Zd(this.consumeCodePoint());Jp(this.peekCodePoint(0))&&this.consumeCodePoint();var i=parseInt(t,16);return 0===i||function(e){return e>=55296&&e<=57343}(i)||i>1114111?65533:i}return-1===e?65533:e},e.prototype.consumeName=function(){for(var e="";;){var t=this.consumeCodePoint();if(Zp(t))e+=Zd(t);else{if(!$p(t,this.peekCodePoint(0)))return this.reconsumeCodePoint(t),e;e+=Zd(this.consumeEscapedCodePoint())}}},e}(),Cf=function(){function e(e){this._tokens=e}return e.create=function(t){var i=new Pf;return i.write(t),new e(i.read())},e.parseValue=function(t){return e.create(t).parseComponentValue()},e.parseValues=function(t){return e.create(t).parseComponentValues()},e.prototype.parseComponentValue=function(){for(var e=this.consumeToken();31===e.type;)e=this.consumeToken();if(32===e.type)throw new SyntaxError("Error parsing CSS component value, unexpected EOF");this.reconsumeToken(e);var t=this.consumeComponentValue();do{e=this.consumeToken()}while(31===e.type);if(32===e.type)return t;throw new SyntaxError("Error parsing CSS component value, multiple values found when expecting only one")},e.prototype.parseComponentValues=function(){for(var e=[];;){var t=this.consumeComponentValue();if(32===t.type)return e;e.push(t),e.push()}},e.prototype.consumeComponentValue=function(){var e=this.consumeToken();switch(e.type){case 11:case 28:case 2:return this.consumeSimpleBlock(e.type);case 19:return this.consumeFunction(e)}return e},e.prototype.consumeSimpleBlock=function(e){for(var t={type:e,values:[]},i=this.consumeToken();;){if(32===i.type||Lf(i,e))return t;this.reconsumeToken(i),t.values.push(this.consumeComponentValue()),i=this.consumeToken()}},e.prototype.consumeFunction=function(e){for(var t={name:e.value,values:[],type:18};;){var i=this.consumeToken();if(32===i.type||3===i.type)return t;this.reconsumeToken(i),t.values.push(this.consumeComponentValue())}},e.prototype.consumeToken=function(){var e=this._tokens.shift();return void 0===e?wf:e},e.prototype.reconsumeToken=function(e){this._tokens.unshift(e)},e}(),Mf=function(e){return 15===e.type},Ef=function(e){return 17===e.type},Ff=function(e){return 20===e.type},If=function(e){return 0===e.type},Df=function(e,t){return Ff(e)&&e.value===t},Sf=function(e){return 31!==e.type},Tf=function(e){return 31!==e.type&&4!==e.type},Rf=function(e){var t=[],i=[];return e.forEach((function(e){if(4===e.type){if(0===i.length)throw new Error("Error parsing function args, zero tokens for arg");return t.push(i),void(i=[])}31!==e.type&&i.push(e)})),i.length&&t.push(i),t},Lf=function(e,t){return 11===t&&12===e.type||(28===t&&29===e.type||2===t&&3===e.type)},Uf=function(e){return 17===e.type||15===e.type},Of=function(e){return 16===e.type||Uf(e)},kf=function(e){return e.length>1?[e[0],e[1]]:[e[0]]},Nf={type:17,number:0,flags:4},Qf={type:16,number:50,flags:4},Vf={type:16,number:100,flags:4},Hf=function(e,t,i){var s=e[0],r=e[1];return[jf(s,t),jf(void 0!==r?r:s,i)]},jf=function(e,t){if(16===e.type)return e.number/100*t;if(Mf(e))switch(e.unit){case"rem":case"em":return 16*e.number;default:return e.number}return e.number},Gf=function(e,t){if(15===t.type)switch(t.unit){case"deg":return Math.PI*t.number/180;case"grad":return Math.PI/200*t.number;case"rad":return t.number;case"turn":return 2*Math.PI*t.number}throw new Error("Unsupported angle type")},zf=function(e){return 15===e.type&&("deg"===e.unit||"grad"===e.unit||"rad"===e.unit||"turn"===e.unit)},Wf=function(e){switch(e.filter(Ff).map((function(e){return e.value})).join(" ")){case"to bottom right":case"to right bottom":case"left top":case"top left":return[Nf,Nf];case"to top":case"bottom":return Kf(0);case"to bottom left":case"to left bottom":case"right top":case"top right":return[Nf,Vf];case"to right":case"left":return Kf(90);case"to top left":case"to left top":case"right bottom":case"bottom right":return[Vf,Vf];case"to bottom":case"top":return Kf(180);case"to top right":case"to right top":case"left bottom":case"bottom left":return[Vf,Nf];case"to left":case"right":return Kf(270)}return 0},Kf=function(e){return Math.PI*e/180},Xf=function(e,t){if(18===t.type){var i=ig[t.name];if(void 0===i)throw new Error('Attempting to parse an unsupported color function "'+t.name+'"');return i(e,t.values)}if(5===t.type){if(3===t.value.length){var s=t.value.substring(0,1),r=t.value.substring(1,2),o=t.value.substring(2,3);return Zf(parseInt(s+s,16),parseInt(r+r,16),parseInt(o+o,16),1)}if(4===t.value.length){s=t.value.substring(0,1),r=t.value.substring(1,2),o=t.value.substring(2,3);var n=t.value.substring(3,4);return Zf(parseInt(s+s,16),parseInt(r+r,16),parseInt(o+o,16),parseInt(n+n,16)/255)}if(6===t.value.length){s=t.value.substring(0,2),r=t.value.substring(2,4),o=t.value.substring(4,6);return Zf(parseInt(s,16),parseInt(r,16),parseInt(o,16),1)}if(8===t.value.length){s=t.value.substring(0,2),r=t.value.substring(2,4),o=t.value.substring(4,6),n=t.value.substring(6,8);return Zf(parseInt(s,16),parseInt(r,16),parseInt(o,16),parseInt(n,16)/255)}}if(20===t.type){var a=rg[t.value.toUpperCase()];if(void 0!==a)return a}return rg.TRANSPARENT},Jf=function(e){return 0==(255&e)},Yf=function(e){var t=255&e,i=255&e>>8,s=255&e>>16,r=255&e>>24;return t<255?"rgba("+r+","+s+","+i+","+t/255+")":"rgb("+r+","+s+","+i+")"},Zf=function(e,t,i,s){return(e<<24|t<<16|i<<8|Math.round(255*s)<<0)>>>0},qf=function(e,t){if(17===e.type)return e.number;if(16===e.type){var i=3===t?1:255;return 3===t?e.number/100*i:Math.round(e.number/100*i)}return 0},$f=function(e,t){var i=t.filter(Tf);if(3===i.length){var s=i.map(qf),r=s[0],o=s[1],n=s[2];return Zf(r,o,n,1)}if(4===i.length){var a=i.map(qf),l=(r=a[0],o=a[1],n=a[2],a[3]);return Zf(r,o,n,l)}return 0};function eg(e,t,i){return i<0&&(i+=1),i>=1&&(i-=1),i<1/6?(t-e)*i*6+e:i<.5?t:i<2/3?6*(t-e)*(2/3-i)+e:e}var tg=function(e,t){var i=t.filter(Tf),s=i[0],r=i[1],o=i[2],n=i[3],a=(17===s.type?Kf(s.number):Gf(e,s))/(2*Math.PI),l=Of(r)?r.number/100:0,A=Of(o)?o.number/100:0,h=void 0!==n&&Of(n)?jf(n,1):1;if(0===l)return Zf(255*A,255*A,255*A,1);var c=A<=.5?A*(l+1):A+l-A*l,u=2*A-c,d=eg(u,c,a+1/3),p=eg(u,c,a),f=eg(u,c,a-1/3);return Zf(255*d,255*p,255*f,h)},ig={hsl:tg,hsla:tg,rgb:$f,rgba:$f},sg=function(e,t){return Xf(e,Cf.create(t).parseComponentValue())},rg={ALICEBLUE:4042850303,ANTIQUEWHITE:4209760255,AQUA:16777215,AQUAMARINE:2147472639,AZURE:4043309055,BEIGE:4126530815,BISQUE:4293182719,BLACK:255,BLANCHEDALMOND:4293643775,BLUE:65535,BLUEVIOLET:2318131967,BROWN:2771004159,BURLYWOOD:3736635391,CADETBLUE:1604231423,CHARTREUSE:2147418367,CHOCOLATE:3530104575,CORAL:4286533887,CORNFLOWERBLUE:1687547391,CORNSILK:4294499583,CRIMSON:3692313855,CYAN:16777215,DARKBLUE:35839,DARKCYAN:9145343,DARKGOLDENROD:3095837695,DARKGRAY:2846468607,DARKGREEN:6553855,DARKGREY:2846468607,DARKKHAKI:3182914559,DARKMAGENTA:2332068863,DARKOLIVEGREEN:1433087999,DARKORANGE:4287365375,DARKORCHID:2570243327,DARKRED:2332033279,DARKSALMON:3918953215,DARKSEAGREEN:2411499519,DARKSLATEBLUE:1211993087,DARKSLATEGRAY:793726975,DARKSLATEGREY:793726975,DARKTURQUOISE:13554175,DARKVIOLET:2483082239,DEEPPINK:4279538687,DEEPSKYBLUE:12582911,DIMGRAY:1768516095,DIMGREY:1768516095,DODGERBLUE:512819199,FIREBRICK:2988581631,FLORALWHITE:4294635775,FORESTGREEN:579543807,FUCHSIA:4278255615,GAINSBORO:3705462015,GHOSTWHITE:4177068031,GOLD:4292280575,GOLDENROD:3668254975,GRAY:2155905279,GREEN:8388863,GREENYELLOW:2919182335,GREY:2155905279,HONEYDEW:4043305215,HOTPINK:4285117695,INDIANRED:3445382399,INDIGO:1258324735,IVORY:4294963455,KHAKI:4041641215,LAVENDER:3873897215,LAVENDERBLUSH:4293981695,LAWNGREEN:2096890111,LEMONCHIFFON:4294626815,LIGHTBLUE:2916673279,LIGHTCORAL:4034953471,LIGHTCYAN:3774873599,LIGHTGOLDENRODYELLOW:4210742015,LIGHTGRAY:3553874943,LIGHTGREEN:2431553791,LIGHTGREY:3553874943,LIGHTPINK:4290167295,LIGHTSALMON:4288707327,LIGHTSEAGREEN:548580095,LIGHTSKYBLUE:2278488831,LIGHTSLATEGRAY:2005441023,LIGHTSLATEGREY:2005441023,LIGHTSTEELBLUE:2965692159,LIGHTYELLOW:4294959359,LIME:16711935,LIMEGREEN:852308735,LINEN:4210091775,MAGENTA:4278255615,MAROON:2147483903,MEDIUMAQUAMARINE:1724754687,MEDIUMBLUE:52735,MEDIUMORCHID:3126187007,MEDIUMPURPLE:2473647103,MEDIUMSEAGREEN:1018393087,MEDIUMSLATEBLUE:2070474495,MEDIUMSPRINGGREEN:16423679,MEDIUMTURQUOISE:1221709055,MEDIUMVIOLETRED:3340076543,MIDNIGHTBLUE:421097727,MINTCREAM:4127193855,MISTYROSE:4293190143,MOCCASIN:4293178879,NAVAJOWHITE:4292783615,NAVY:33023,OLDLACE:4260751103,OLIVE:2155872511,OLIVEDRAB:1804477439,ORANGE:4289003775,ORANGERED:4282712319,ORCHID:3664828159,PALEGOLDENROD:4008225535,PALEGREEN:2566625535,PALETURQUOISE:2951671551,PALEVIOLETRED:3681588223,PAPAYAWHIP:4293907967,PEACHPUFF:4292524543,PERU:3448061951,PINK:4290825215,PLUM:3718307327,POWDERBLUE:2967529215,PURPLE:2147516671,REBECCAPURPLE:1714657791,RED:4278190335,ROSYBROWN:3163525119,ROYALBLUE:1097458175,SADDLEBROWN:2336560127,SALMON:4202722047,SANDYBROWN:4104413439,SEAGREEN:780883967,SEASHELL:4294307583,SIENNA:2689740287,SILVER:3233857791,SKYBLUE:2278484991,SLATEBLUE:1784335871,SLATEGRAY:1887473919,SLATEGREY:1887473919,SNOW:4294638335,SPRINGGREEN:16744447,STEELBLUE:1182971135,TAN:3535047935,TEAL:8421631,THISTLE:3636451583,TOMATO:4284696575,TRANSPARENT:0,TURQUOISE:1088475391,VIOLET:4001558271,WHEAT:4125012991,WHITE:4294967295,WHITESMOKE:4126537215,YELLOW:4294902015,YELLOWGREEN:2597139199},og={name:"background-clip",initialValue:"border-box",prefix:!1,type:1,parse:function(e,t){return t.map((function(e){if(Ff(e))switch(e.value){case"padding-box":return 1;case"content-box":return 2}return 0}))}},ng={name:"background-color",initialValue:"transparent",prefix:!1,type:3,format:"color"},ag=function(e,t){var i=Xf(e,t[0]),s=t[1];return s&&Of(s)?{color:i,stop:s}:{color:i,stop:null}},lg=function(e,t){var i=e[0],s=e[e.length-1];null===i.stop&&(i.stop=Nf),null===s.stop&&(s.stop=Vf);for(var r=[],o=0,n=0;no?r.push(l):r.push(o),o=l}else r.push(null)}var A=null;for(n=0;ne.optimumDistance)?{optimumCorner:t,optimumDistance:a}:e}),{optimumDistance:r?1/0:-1/0,optimumCorner:null}).optimumCorner},ug=function(e,t){var i=Kf(180),s=[];return Rf(t).forEach((function(t,r){if(0===r){var o=t[0];if(20===o.type&&-1!==["top","left","right","bottom"].indexOf(o.value))return void(i=Wf(t));if(zf(o))return void(i=(Gf(e,o)+Kf(270))%Kf(360))}var n=ag(e,t);s.push(n)})),{angle:i,stops:s,type:1}},dg=function(e,t){var i=0,s=3,r=[],o=[];return Rf(t).forEach((function(t,n){var a=!0;if(0===n?a=t.reduce((function(e,t){if(Ff(t))switch(t.value){case"center":return o.push(Qf),!1;case"top":case"left":return o.push(Nf),!1;case"right":case"bottom":return o.push(Vf),!1}else if(Of(t)||Uf(t))return o.push(t),!1;return e}),a):1===n&&(a=t.reduce((function(e,t){if(Ff(t))switch(t.value){case"circle":return i=0,!1;case"ellipse":return i=1,!1;case"contain":case"closest-side":return s=0,!1;case"farthest-side":return s=1,!1;case"closest-corner":return s=2,!1;case"cover":case"farthest-corner":return s=3,!1}else if(Uf(t)||Of(t))return Array.isArray(s)||(s=[]),s.push(t),!1;return e}),a)),a){var l=ag(e,t);r.push(l)}})),{size:s,shape:i,stops:r,position:o,type:2}},pg=function(e,t){if(22===t.type){var i={url:t.value,type:0};return e.cache.addImage(t.value),i}if(18===t.type){var s=gg[t.name];if(void 0===s)throw new Error('Attempting to parse an unsupported image function "'+t.name+'"');return s(e,t.values)}throw new Error("Unsupported image type "+t.type)};var fg,gg={"linear-gradient":function(e,t){var i=Kf(180),s=[];return Rf(t).forEach((function(t,r){if(0===r){var o=t[0];if(20===o.type&&"to"===o.value)return void(i=Wf(t));if(zf(o))return void(i=Gf(e,o))}var n=ag(e,t);s.push(n)})),{angle:i,stops:s,type:1}},"-moz-linear-gradient":ug,"-ms-linear-gradient":ug,"-o-linear-gradient":ug,"-webkit-linear-gradient":ug,"radial-gradient":function(e,t){var i=0,s=3,r=[],o=[];return Rf(t).forEach((function(t,n){var a=!0;if(0===n){var l=!1;a=t.reduce((function(e,t){if(l)if(Ff(t))switch(t.value){case"center":return o.push(Qf),e;case"top":case"left":return o.push(Nf),e;case"right":case"bottom":return o.push(Vf),e}else(Of(t)||Uf(t))&&o.push(t);else if(Ff(t))switch(t.value){case"circle":return i=0,!1;case"ellipse":return i=1,!1;case"at":return l=!0,!1;case"closest-side":return s=0,!1;case"cover":case"farthest-side":return s=1,!1;case"contain":case"closest-corner":return s=2,!1;case"farthest-corner":return s=3,!1}else if(Uf(t)||Of(t))return Array.isArray(s)||(s=[]),s.push(t),!1;return e}),a)}if(a){var A=ag(e,t);r.push(A)}})),{size:s,shape:i,stops:r,position:o,type:2}},"-moz-radial-gradient":dg,"-ms-radial-gradient":dg,"-o-radial-gradient":dg,"-webkit-radial-gradient":dg,"-webkit-gradient":function(e,t){var i=Kf(180),s=[],r=1;return Rf(t).forEach((function(t,i){var o=t[0];if(0===i){if(Ff(o)&&"linear"===o.value)return void(r=1);if(Ff(o)&&"radial"===o.value)return void(r=2)}if(18===o.type)if("from"===o.name){var n=Xf(e,o.values[0]);s.push({stop:Nf,color:n})}else if("to"===o.name){n=Xf(e,o.values[0]);s.push({stop:Vf,color:n})}else if("color-stop"===o.name){var a=o.values.filter(Tf);if(2===a.length){n=Xf(e,a[1]);var l=a[0];Ef(l)&&s.push({stop:{type:16,number:100*l.number,flags:l.flags},color:n})}}})),1===r?{angle:(i+Kf(180))%Kf(360),stops:s,type:r}:{size:3,shape:0,stops:s,position:[],type:r}}},mg={name:"background-image",initialValue:"none",type:1,prefix:!1,parse:function(e,t){if(0===t.length)return[];var i=t[0];return 20===i.type&&"none"===i.value?[]:t.filter((function(e){return Tf(e)&&function(e){return!(20===e.type&&"none"===e.value||18===e.type&&!gg[e.name])}(e)})).map((function(t){return pg(e,t)}))}},_g={name:"background-origin",initialValue:"border-box",prefix:!1,type:1,parse:function(e,t){return t.map((function(e){if(Ff(e))switch(e.value){case"padding-box":return 1;case"content-box":return 2}return 0}))}},vg={name:"background-position",initialValue:"0% 0%",type:1,prefix:!1,parse:function(e,t){return Rf(t).map((function(e){return e.filter(Of)})).map(kf)}},bg={name:"background-repeat",initialValue:"repeat",prefix:!1,type:1,parse:function(e,t){return Rf(t).map((function(e){return e.filter(Ff).map((function(e){return e.value})).join(" ")})).map(yg)}},yg=function(e){switch(e){case"no-repeat":return 1;case"repeat-x":case"repeat no-repeat":return 2;case"repeat-y":case"no-repeat repeat":return 3;default:return 0}};!function(e){e.AUTO="auto",e.CONTAIN="contain",e.COVER="cover"}(fg||(fg={}));var xg,Bg={name:"background-size",initialValue:"0",prefix:!1,type:1,parse:function(e,t){return Rf(t).map((function(e){return e.filter(wg)}))}},wg=function(e){return Ff(e)||Of(e)},Pg=function(e){return{name:"border-"+e+"-color",initialValue:"transparent",prefix:!1,type:3,format:"color"}},Cg=Pg("top"),Mg=Pg("right"),Eg=Pg("bottom"),Fg=Pg("left"),Ig=function(e){return{name:"border-radius-"+e,initialValue:"0 0",prefix:!1,type:1,parse:function(e,t){return kf(t.filter(Of))}}},Dg=Ig("top-left"),Sg=Ig("top-right"),Tg=Ig("bottom-right"),Rg=Ig("bottom-left"),Lg=function(e){return{name:"border-"+e+"-style",initialValue:"solid",prefix:!1,type:2,parse:function(e,t){switch(t){case"none":return 0;case"dashed":return 2;case"dotted":return 3;case"double":return 4}return 1}}},Ug=Lg("top"),Og=Lg("right"),kg=Lg("bottom"),Ng=Lg("left"),Qg=function(e){return{name:"border-"+e+"-width",initialValue:"0",type:0,prefix:!1,parse:function(e,t){return Mf(t)?t.number:0}}},Vg=Qg("top"),Hg=Qg("right"),jg=Qg("bottom"),Gg=Qg("left"),zg={name:"color",initialValue:"transparent",prefix:!1,type:3,format:"color"},Wg={name:"direction",initialValue:"ltr",prefix:!1,type:2,parse:function(e,t){return"rtl"===t?1:0}},Kg={name:"display",initialValue:"inline-block",prefix:!1,type:1,parse:function(e,t){return t.filter(Ff).reduce((function(e,t){return e|Xg(t.value)}),0)}},Xg=function(e){switch(e){case"block":case"-webkit-box":return 2;case"inline":return 4;case"run-in":return 8;case"flow":return 16;case"flow-root":return 32;case"table":return 64;case"flex":case"-webkit-flex":return 128;case"grid":case"-ms-grid":return 256;case"ruby":return 512;case"subgrid":return 1024;case"list-item":return 2048;case"table-row-group":return 4096;case"table-header-group":return 8192;case"table-footer-group":return 16384;case"table-row":return 32768;case"table-cell":return 65536;case"table-column-group":return 131072;case"table-column":return 262144;case"table-caption":return 524288;case"ruby-base":return 1048576;case"ruby-text":return 2097152;case"ruby-base-container":return 4194304;case"ruby-text-container":return 8388608;case"contents":return 16777216;case"inline-block":return 33554432;case"inline-list-item":return 67108864;case"inline-table":return 134217728;case"inline-flex":return 268435456;case"inline-grid":return 536870912}return 0},Jg={name:"float",initialValue:"none",prefix:!1,type:2,parse:function(e,t){switch(t){case"left":return 1;case"right":return 2;case"inline-start":return 3;case"inline-end":return 4}return 0}},Yg={name:"letter-spacing",initialValue:"0",prefix:!1,type:0,parse:function(e,t){return 20===t.type&&"normal"===t.value?0:17===t.type||15===t.type?t.number:0}};!function(e){e.NORMAL="normal",e.STRICT="strict"}(xg||(xg={}));var Zg,qg={name:"line-break",initialValue:"normal",prefix:!1,type:2,parse:function(e,t){return"strict"===t?xg.STRICT:xg.NORMAL}},$g={name:"line-height",initialValue:"normal",prefix:!1,type:4},em=function(e,t){return Ff(e)&&"normal"===e.value?1.2*t:17===e.type?t*e.number:Of(e)?jf(e,t):t},tm={name:"list-style-image",initialValue:"none",type:0,prefix:!1,parse:function(e,t){return 20===t.type&&"none"===t.value?null:pg(e,t)}},im={name:"list-style-position",initialValue:"outside",prefix:!1,type:2,parse:function(e,t){return"inside"===t?0:1}},sm={name:"list-style-type",initialValue:"none",prefix:!1,type:2,parse:function(e,t){switch(t){case"disc":return 0;case"circle":return 1;case"square":return 2;case"decimal":return 3;case"cjk-decimal":return 4;case"decimal-leading-zero":return 5;case"lower-roman":return 6;case"upper-roman":return 7;case"lower-greek":return 8;case"lower-alpha":return 9;case"upper-alpha":return 10;case"arabic-indic":return 11;case"armenian":return 12;case"bengali":return 13;case"cambodian":return 14;case"cjk-earthly-branch":return 15;case"cjk-heavenly-stem":return 16;case"cjk-ideographic":return 17;case"devanagari":return 18;case"ethiopic-numeric":return 19;case"georgian":return 20;case"gujarati":return 21;case"gurmukhi":case"hebrew":return 22;case"hiragana":return 23;case"hiragana-iroha":return 24;case"japanese-formal":return 25;case"japanese-informal":return 26;case"kannada":return 27;case"katakana":return 28;case"katakana-iroha":return 29;case"khmer":return 30;case"korean-hangul-formal":return 31;case"korean-hanja-formal":return 32;case"korean-hanja-informal":return 33;case"lao":return 34;case"lower-armenian":return 35;case"malayalam":return 36;case"mongolian":return 37;case"myanmar":return 38;case"oriya":return 39;case"persian":return 40;case"simp-chinese-formal":return 41;case"simp-chinese-informal":return 42;case"tamil":return 43;case"telugu":return 44;case"thai":return 45;case"tibetan":return 46;case"trad-chinese-formal":return 47;case"trad-chinese-informal":return 48;case"upper-armenian":return 49;case"disclosure-open":return 50;case"disclosure-closed":return 51;default:return-1}}},rm=function(e){return{name:"margin-"+e,initialValue:"0",prefix:!1,type:4}},om=rm("top"),nm=rm("right"),am=rm("bottom"),lm=rm("left"),Am={name:"overflow",initialValue:"visible",prefix:!1,type:1,parse:function(e,t){return t.filter(Ff).map((function(e){switch(e.value){case"hidden":return 1;case"scroll":return 2;case"clip":return 3;case"auto":return 4;default:return 0}}))}},hm={name:"overflow-wrap",initialValue:"normal",prefix:!1,type:2,parse:function(e,t){return"break-word"===t?"break-word":"normal"}},cm=function(e){return{name:"padding-"+e,initialValue:"0",prefix:!1,type:3,format:"length-percentage"}},um=cm("top"),dm=cm("right"),pm=cm("bottom"),fm=cm("left"),gm={name:"text-align",initialValue:"left",prefix:!1,type:2,parse:function(e,t){switch(t){case"right":return 2;case"center":case"justify":return 1;default:return 0}}},mm={name:"position",initialValue:"static",prefix:!1,type:2,parse:function(e,t){switch(t){case"relative":return 1;case"absolute":return 2;case"fixed":return 3;case"sticky":return 4}return 0}},_m={name:"text-shadow",initialValue:"none",type:1,prefix:!1,parse:function(e,t){return 1===t.length&&Df(t[0],"none")?[]:Rf(t).map((function(t){for(var i={color:rg.TRANSPARENT,offsetX:Nf,offsetY:Nf,blur:Nf},s=0,r=0;r1?1:0],this.overflowWrap=Zm(e,hm,t.overflowWrap),this.paddingTop=Zm(e,um,t.paddingTop),this.paddingRight=Zm(e,dm,t.paddingRight),this.paddingBottom=Zm(e,pm,t.paddingBottom),this.paddingLeft=Zm(e,fm,t.paddingLeft),this.paintOrder=Zm(e,zm,t.paintOrder),this.position=Zm(e,mm,t.position),this.textAlign=Zm(e,gm,t.textAlign),this.textDecorationColor=Zm(e,Im,null!==(i=t.textDecorationColor)&&void 0!==i?i:t.color),this.textDecorationLine=Zm(e,Dm,null!==(s=t.textDecorationLine)&&void 0!==s?s:t.textDecoration),this.textShadow=Zm(e,_m,t.textShadow),this.textTransform=Zm(e,vm,t.textTransform),this.transform=Zm(e,bm,t.transform),this.transformOrigin=Zm(e,wm,t.transformOrigin),this.visibility=Zm(e,Pm,t.visibility),this.webkitTextStrokeColor=Zm(e,Wm,t.webkitTextStrokeColor),this.webkitTextStrokeWidth=Zm(e,Km,t.webkitTextStrokeWidth),this.wordBreak=Zm(e,Cm,t.wordBreak),this.zIndex=Zm(e,Mm,t.zIndex)}return e.prototype.isVisible=function(){return this.display>0&&this.opacity>0&&0===this.visibility},e.prototype.isTransparent=function(){return Jf(this.backgroundColor)},e.prototype.isTransformed=function(){return null!==this.transform},e.prototype.isPositioned=function(){return 0!==this.position},e.prototype.isPositionedWithZIndex=function(){return this.isPositioned()&&!this.zIndex.auto},e.prototype.isFloating=function(){return 0!==this.float},e.prototype.isInlineLevel=function(){return Om(this.display,4)||Om(this.display,33554432)||Om(this.display,268435456)||Om(this.display,536870912)||Om(this.display,67108864)||Om(this.display,134217728)},e}(),Jm=function(e,t){this.content=Zm(e,km,t.content),this.quotes=Zm(e,Hm,t.quotes)},Ym=function(e,t){this.counterIncrement=Zm(e,Nm,t.counterIncrement),this.counterReset=Zm(e,Qm,t.counterReset)},Zm=function(e,t,i){var s=new Pf,r=null!=i?i.toString():t.initialValue;s.write(r);var o=new Cf(s.read());switch(t.type){case 2:var n=o.parseComponentValue();return t.parse(e,Ff(n)?n.value:t.initialValue);case 0:return t.parse(e,o.parseComponentValue());case 1:return t.parse(e,o.parseComponentValues());case 4:return o.parseComponentValue();case 3:switch(t.format){case"angle":return Gf(e,o.parseComponentValue());case"color":return Xf(e,o.parseComponentValue());case"image":return pg(e,o.parseComponentValue());case"length":var a=o.parseComponentValue();return Uf(a)?a:Nf;case"length-percentage":var l=o.parseComponentValue();return Of(l)?l:Nf;case"time":return Em(e,o.parseComponentValue())}}},qm=function(e,t){var i=function(e){switch(e.getAttribute("data-html2canvas-debug")){case"all":return 1;case"clone":return 2;case"parse":return 3;case"render":return 4;default:return 0}}(e);return 1===i||t===i},$m=function(e,t){this.context=e,this.textNodes=[],this.elements=[],this.flags=0,qm(t,3),this.styles=new Xm(e,window.getComputedStyle(t,null)),$_(t)&&(this.styles.animationDuration.some((function(e){return e>0}))&&(t.style.animationDuration="0s"),null!==this.styles.transform&&(t.style.transform="none")),this.bounds=Jd(this.context,t),qm(t,4)&&(this.flags|=16)},e_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t_="undefined"==typeof Uint8Array?[]:new Uint8Array(256),i_=0;i_=0){if(e<55296||e>56319&&e<=65535)return t=((t=this.index[e>>5])<<2)+(31&e),this.data[t];if(e<=65535)return t=((t=this.index[2048+(e-55296>>5)])<<2)+(31&e),this.data[t];if(e>11),t=this.index[t],t+=e>>5&63,t=((t=this.index[t])<<2)+(31&e),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},e}(),o_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n_="undefined"==typeof Uint8Array?[]:new Uint8Array(256),a_=0;a_>10),n%1024+56320)),(r+1===i||s.length>16384)&&(o+=String.fromCharCode.apply(String,s),s.length=0)}return o},p_=function(e,t){var i,s,r,o=function(e){var t,i,s,r,o,n=.75*e.length,a=e.length,l=0;"="===e[e.length-1]&&(n--,"="===e[e.length-2]&&n--);var A="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&void 0!==Uint8Array.prototype.slice?new ArrayBuffer(n):new Array(n),h=Array.isArray(A)?A:new Uint8Array(A);for(t=0;t>4,h[l++]=(15&s)<<4|r>>2,h[l++]=(3&r)<<6|63&o;return A}(e),n=Array.isArray(o)?function(e){for(var t=e.length,i=[],s=0;s=55296&&r<=56319&&i=i)return{done:!0,value:null};for(var e="×";sn.x||r.y>n.y;return n=r,0===t||a}));return e.body.removeChild(t),a}(document);return Object.defineProperty(y_,"SUPPORT_WORD_BREAKING",{value:e}),e},get SUPPORT_SVG_DRAWING(){var e=function(e){var t=new Image,i=e.createElement("canvas"),s=i.getContext("2d");if(!s)return!1;t.src="data:image/svg+xml,";try{s.drawImage(t,0,0),i.toDataURL()}catch(e){return!1}return!0}(document);return Object.defineProperty(y_,"SUPPORT_SVG_DRAWING",{value:e}),e},get SUPPORT_FOREIGNOBJECT_DRAWING(){var e="function"==typeof Array.from&&"function"==typeof window.fetch?function(e){var t=e.createElement("canvas"),i=100;t.width=i,t.height=i;var s=t.getContext("2d");if(!s)return Promise.reject(!1);s.fillStyle="rgb(0, 255, 0)",s.fillRect(0,0,i,i);var r=new Image,o=t.toDataURL();r.src=o;var n=v_(i,i,0,0,r);return s.fillStyle="red",s.fillRect(0,0,i,i),b_(n).then((function(t){s.drawImage(t,0,0);var r=s.getImageData(0,0,i,i).data;s.fillStyle="red",s.fillRect(0,0,i,i);var n=e.createElement("div");return n.style.backgroundImage="url("+o+")",n.style.height="100px",__(r)?b_(v_(i,i,0,0,n)):Promise.reject(!1)})).then((function(e){return s.drawImage(e,0,0),__(s.getImageData(0,0,i,i).data)})).catch((function(){return!1}))}(document):Promise.resolve(!1);return Object.defineProperty(y_,"SUPPORT_FOREIGNOBJECT_DRAWING",{value:e}),e},get SUPPORT_CORS_IMAGES(){var e=void 0!==(new Image).crossOrigin;return Object.defineProperty(y_,"SUPPORT_CORS_IMAGES",{value:e}),e},get SUPPORT_RESPONSE_TYPE(){var e="string"==typeof(new XMLHttpRequest).responseType;return Object.defineProperty(y_,"SUPPORT_RESPONSE_TYPE",{value:e}),e},get SUPPORT_CORS_XHR(){var e="withCredentials"in new XMLHttpRequest;return Object.defineProperty(y_,"SUPPORT_CORS_XHR",{value:e}),e},get SUPPORT_NATIVE_TEXT_SEGMENTATION(){var e=!("undefined"==typeof Intl||!Intl.Segmenter);return Object.defineProperty(y_,"SUPPORT_NATIVE_TEXT_SEGMENTATION",{value:e}),e}},x_=function(e,t){this.text=e,this.bounds=t},B_=function(e,t){var i=t.ownerDocument;if(i){var s=i.createElement("html2canvaswrapper");s.appendChild(t.cloneNode(!0));var r=t.parentNode;if(r){r.replaceChild(s,t);var o=Jd(e,s);return s.firstChild&&r.replaceChild(s.firstChild,s),o}}return Xd.EMPTY},w_=function(e,t,i){var s=e.ownerDocument;if(!s)throw new Error("Node has no owner document");var r=s.createRange();return r.setStart(e,t),r.setEnd(e,t+i),r},P_=function(e){if(y_.SUPPORT_NATIVE_TEXT_SEGMENTATION){var t=new Intl.Segmenter(void 0,{granularity:"grapheme"});return Array.from(t.segment(e)).map((function(e){return e.segment}))}return function(e){for(var t,i=m_(e),s=[];!(t=i.next()).done;)t.value&&s.push(t.value.slice());return s}(e)},C_=function(e,t){return 0!==t.letterSpacing?P_(e):function(e,t){if(y_.SUPPORT_NATIVE_TEXT_SEGMENTATION){var i=new Intl.Segmenter(void 0,{granularity:"word"});return Array.from(i.segment(e)).map((function(e){return e.segment}))}return E_(e,t)}(e,t)},M_=[32,160,4961,65792,65793,4153,4241],E_=function(e,t){for(var i,s=function(e,t){var i=Yd(e),s=zp(i,t),r=s[0],o=s[1],n=s[2],a=i.length,l=0,A=0;return{next:function(){if(A>=a)return{done:!0,value:null};for(var e="×";A0)if(y_.SUPPORT_RANGE_BOUNDS){var r=w_(s,n,t.length).getClientRects();if(r.length>1){var a=P_(t),l=0;a.forEach((function(t){o.push(new x_(t,Xd.fromDOMRectList(e,w_(s,l+n,t.length).getClientRects()))),l+=t.length}))}else o.push(new x_(t,Xd.fromDOMRectList(e,r)))}else{var A=s.splitText(t.length);o.push(new x_(t,B_(e,s))),s=A}else y_.SUPPORT_RANGE_BOUNDS||(s=s.splitText(t.length));n+=t.length})),o}(e,this.text,i,t)},I_=function(e,t){switch(t){case 1:return e.toLowerCase();case 3:return e.replace(D_,S_);case 2:return e.toUpperCase();default:return e}},D_=/(^|\s|:|-|\(|\))([a-z])/g,S_=function(e,t,i){return e.length>0?t+i.toUpperCase():e},T_=function(e){function t(t,i){var s=e.call(this,t,i)||this;return s.src=i.currentSrc||i.src,s.intrinsicWidth=i.naturalWidth,s.intrinsicHeight=i.naturalHeight,s.context.cache.addImage(s.src),s}return jd(t,e),t}($m),R_=function(e){function t(t,i){var s=e.call(this,t,i)||this;return s.canvas=i,s.intrinsicWidth=i.width,s.intrinsicHeight=i.height,s}return jd(t,e),t}($m),L_=function(e){function t(t,i){var s=e.call(this,t,i)||this,r=new XMLSerializer,o=Jd(t,i);return i.setAttribute("width",o.width+"px"),i.setAttribute("height",o.height+"px"),s.svg="data:image/svg+xml,"+encodeURIComponent(r.serializeToString(i)),s.intrinsicWidth=i.width.baseVal.value,s.intrinsicHeight=i.height.baseVal.value,s.context.cache.addImage(s.svg),s}return jd(t,e),t}($m),U_=function(e){function t(t,i){var s=e.call(this,t,i)||this;return s.value=i.value,s}return jd(t,e),t}($m),O_=function(e){function t(t,i){var s=e.call(this,t,i)||this;return s.start=i.start,s.reversed="boolean"==typeof i.reversed&&!0===i.reversed,s}return jd(t,e),t}($m),k_=[{type:15,flags:0,unit:"px",number:3}],N_=[{type:16,flags:0,number:50}],Q_="password",V_=function(e){function t(t,i){var s,r=e.call(this,t,i)||this;switch(r.type=i.type.toLowerCase(),r.checked=i.checked,r.value=function(e){var t=e.type===Q_?new Array(e.value.length+1).join("•"):e.value;return 0===t.length?e.placeholder||"":t}(i),"checkbox"!==r.type&&"radio"!==r.type||(r.styles.backgroundColor=3739148031,r.styles.borderTopColor=r.styles.borderRightColor=r.styles.borderBottomColor=r.styles.borderLeftColor=2779096575,r.styles.borderTopWidth=r.styles.borderRightWidth=r.styles.borderBottomWidth=r.styles.borderLeftWidth=1,r.styles.borderTopStyle=r.styles.borderRightStyle=r.styles.borderBottomStyle=r.styles.borderLeftStyle=1,r.styles.backgroundClip=[0],r.styles.backgroundOrigin=[0],r.bounds=(s=r.bounds).width>s.height?new Xd(s.left+(s.width-s.height)/2,s.top,s.height,s.height):s.width0)i.textNodes.push(new F_(e,r,i.styles));else if(q_(r))if(dv(r)&&r.assignedNodes)r.assignedNodes().forEach((function(t){return W_(e,t,i,s)}));else{var n=K_(e,r);n.styles.isVisible()&&(J_(r,n,s)?n.flags|=4:Y_(n.styles)&&(n.flags|=2),-1!==z_.indexOf(r.tagName)&&(n.flags|=8),i.elements.push(n),r.slot,r.shadowRoot?W_(e,r.shadowRoot,n,s):cv(r)||rv(r)||uv(r)||W_(e,r,n,s))}},K_=function(e,t){return lv(t)?new T_(e,t):nv(t)?new R_(e,t):rv(t)?new L_(e,t):tv(t)?new U_(e,t):iv(t)?new O_(e,t):sv(t)?new V_(e,t):uv(t)?new H_(e,t):cv(t)?new j_(e,t):Av(t)?new G_(e,t):new $m(e,t)},X_=function(e,t){var i=K_(e,t);return i.flags|=4,W_(e,t,i,i),i},J_=function(e,t,i){return t.styles.isPositionedWithZIndex()||t.styles.opacity<1||t.styles.isTransformed()||ov(e)&&i.styles.isTransparent()},Y_=function(e){return e.isPositioned()||e.isFloating()},Z_=function(e){return e.nodeType===Node.TEXT_NODE},q_=function(e){return e.nodeType===Node.ELEMENT_NODE},$_=function(e){return q_(e)&&void 0!==e.style&&!ev(e)},ev=function(e){return"object"==typeof e.className},tv=function(e){return"LI"===e.tagName},iv=function(e){return"OL"===e.tagName},sv=function(e){return"INPUT"===e.tagName},rv=function(e){return"svg"===e.tagName},ov=function(e){return"BODY"===e.tagName},nv=function(e){return"CANVAS"===e.tagName},av=function(e){return"VIDEO"===e.tagName},lv=function(e){return"IMG"===e.tagName},Av=function(e){return"IFRAME"===e.tagName},hv=function(e){return"STYLE"===e.tagName},cv=function(e){return"TEXTAREA"===e.tagName},uv=function(e){return"SELECT"===e.tagName},dv=function(e){return"SLOT"===e.tagName},pv=function(e){return e.tagName.indexOf("-")>0},fv=function(){function e(){this.counters={}}return e.prototype.getCounterValue=function(e){var t=this.counters[e];return t&&t.length?t[t.length-1]:1},e.prototype.getCounterValues=function(e){var t=this.counters[e];return t||[]},e.prototype.pop=function(e){var t=this;e.forEach((function(e){return t.counters[e].pop()}))},e.prototype.parse=function(e){var t=this,i=e.counterIncrement,s=e.counterReset,r=!0;null!==i&&i.forEach((function(e){var i=t.counters[e.counter];i&&0!==e.increment&&(r=!1,i.length||i.push(1),i[Math.max(0,i.length-1)]+=e.increment)}));var o=[];return r&&s.forEach((function(e){var i=t.counters[e.counter];o.push(e.counter),i||(i=t.counters[e.counter]=[]),i.push(e.reset)})),o},e}(),gv={integers:[1e3,900,500,400,100,90,50,40,10,9,5,4,1],values:["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]},mv={integers:[9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],values:["Ք","Փ","Ւ","Ց","Ր","Տ","Վ","Ս","Ռ","Ջ","Պ","Չ","Ո","Շ","Ն","Յ","Մ","Ճ","Ղ","Ձ","Հ","Կ","Ծ","Խ","Լ","Ի","Ժ","Թ","Ը","Է","Զ","Ե","Դ","Գ","Բ","Ա"]},_v={integers:[1e4,9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,400,300,200,100,90,80,70,60,50,40,30,20,19,18,17,16,15,10,9,8,7,6,5,4,3,2,1],values:["י׳","ט׳","ח׳","ז׳","ו׳","ה׳","ד׳","ג׳","ב׳","א׳","ת","ש","ר","ק","צ","פ","ע","ס","נ","מ","ל","כ","יט","יח","יז","טז","טו","י","ט","ח","ז","ו","ה","ד","ג","ב","א"]},vv={integers:[1e4,9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],values:["ჵ","ჰ","ჯ","ჴ","ხ","ჭ","წ","ძ","ც","ჩ","შ","ყ","ღ","ქ","ფ","ჳ","ტ","ს","რ","ჟ","პ","ო","ჲ","ნ","მ","ლ","კ","ი","თ","ჱ","ზ","ვ","ე","დ","გ","ბ","ა"]},bv=function(e,t,i,s,r,o){return ei?Pv(e,r,o.length>0):s.integers.reduce((function(t,i,r){for(;e>=i;)e-=i,t+=s.values[r];return t}),"")+o},yv=function(e,t,i,s){var r="";do{i||e--,r=s(e)+r,e/=t}while(e*t>=t);return r},xv=function(e,t,i,s,r){var o=i-t+1;return(e<0?"-":"")+(yv(Math.abs(e),o,s,(function(e){return Zd(Math.floor(e%o)+t)}))+r)},Bv=function(e,t,i){void 0===i&&(i=". ");var s=t.length;return yv(Math.abs(e),s,!1,(function(e){return t[Math.floor(e%s)]}))+i},wv=function(e,t,i,s,r,o){if(e<-9999||e>9999)return Pv(e,4,r.length>0);var n=Math.abs(e),a=r;if(0===n)return t[0]+a;for(var l=0;n>0&&l<=4;l++){var A=n%10;0===A&&Om(o,1)&&""!==a?a=t[A]+a:A>1||1===A&&0===l||1===A&&1===l&&Om(o,2)||1===A&&1===l&&Om(o,4)&&e>100||1===A&&l>1&&Om(o,8)?a=t[A]+(l>0?i[l-1]:"")+a:1===A&&l>0&&(a=i[l-1]+a),n=Math.floor(n/10)}return(e<0?s:"")+a},Pv=function(e,t,i){var s=i?". ":"",r=i?"、":"",o=i?", ":"",n=i?" ":"";switch(t){case 0:return"•"+n;case 1:return"◦"+n;case 2:return"◾"+n;case 5:var a=xv(e,48,57,!0,s);return a.length<4?"0"+a:a;case 4:return Bv(e,"〇一二三四五六七八九",r);case 6:return bv(e,1,3999,gv,3,s).toLowerCase();case 7:return bv(e,1,3999,gv,3,s);case 8:return xv(e,945,969,!1,s);case 9:return xv(e,97,122,!1,s);case 10:return xv(e,65,90,!1,s);case 11:return xv(e,1632,1641,!0,s);case 12:case 49:return bv(e,1,9999,mv,3,s);case 35:return bv(e,1,9999,mv,3,s).toLowerCase();case 13:return xv(e,2534,2543,!0,s);case 14:case 30:return xv(e,6112,6121,!0,s);case 15:return Bv(e,"子丑寅卯辰巳午未申酉戌亥",r);case 16:return Bv(e,"甲乙丙丁戊己庚辛壬癸",r);case 17:case 48:return wv(e,"零一二三四五六七八九","十百千萬","負",r,14);case 47:return wv(e,"零壹貳參肆伍陸柒捌玖","拾佰仟萬","負",r,15);case 42:return wv(e,"零一二三四五六七八九","十百千萬","负",r,14);case 41:return wv(e,"零壹贰叁肆伍陆柒捌玖","拾佰仟萬","负",r,15);case 26:return wv(e,"〇一二三四五六七八九","十百千万","マイナス",r,0);case 25:return wv(e,"零壱弐参四伍六七八九","拾百千万","マイナス",r,7);case 31:return wv(e,"영일이삼사오육칠팔구","십백천만","마이너스",o,7);case 33:return wv(e,"零一二三四五六七八九","十百千萬","마이너스",o,0);case 32:return wv(e,"零壹貳參四五六七八九","拾百千","마이너스",o,7);case 18:return xv(e,2406,2415,!0,s);case 20:return bv(e,1,19999,vv,3,s);case 21:return xv(e,2790,2799,!0,s);case 22:return xv(e,2662,2671,!0,s);case 22:return bv(e,1,10999,_v,3,s);case 23:return Bv(e,"あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわゐゑをん");case 24:return Bv(e,"いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす");case 27:return xv(e,3302,3311,!0,s);case 28:return Bv(e,"アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヰヱヲン",r);case 29:return Bv(e,"イロハニホヘトチリヌルヲワカヨタレソツネナラムウヰノオクヤマケフコエテアサキユメミシヱヒモセス",r);case 34:return xv(e,3792,3801,!0,s);case 37:return xv(e,6160,6169,!0,s);case 38:return xv(e,4160,4169,!0,s);case 39:return xv(e,2918,2927,!0,s);case 40:return xv(e,1776,1785,!0,s);case 43:return xv(e,3046,3055,!0,s);case 44:return xv(e,3174,3183,!0,s);case 45:return xv(e,3664,3673,!0,s);case 46:return xv(e,3872,3881,!0,s);default:return xv(e,48,57,!0,s)}},Cv=function(){function e(e,t,i){if(this.context=e,this.options=i,this.scrolledElements=[],this.referenceElement=t,this.counters=new fv,this.quoteDepth=0,!t.ownerDocument)throw new Error("Cloned element does not have an owner document");this.documentElement=this.cloneNode(t.ownerDocument.documentElement,!1)}return e.prototype.toIFrame=function(e,t){var i=this,s=Ev(e,t);if(!s.contentWindow)return Promise.reject("Unable to find iframe window");var r=e.defaultView.pageXOffset,o=e.defaultView.pageYOffset,n=s.contentWindow,a=n.document,l=Dv(s).then((function(){return zd(i,void 0,void 0,(function(){var e,i;return Wd(this,(function(r){switch(r.label){case 0:return this.scrolledElements.forEach(Uv),n&&(n.scrollTo(t.left,t.top),!/(iPad|iPhone|iPod)/g.test(navigator.userAgent)||n.scrollY===t.top&&n.scrollX===t.left||(this.context.logger.warn("Unable to restore scroll position for cloned document"),this.context.windowBounds=this.context.windowBounds.add(n.scrollX-t.left,n.scrollY-t.top,0,0))),e=this.options.onclone,void 0===(i=this.clonedReferenceElement)?[2,Promise.reject("Error finding the "+this.referenceElement.nodeName+" in the cloned document")]:a.fonts&&a.fonts.ready?[4,a.fonts.ready]:[3,2];case 1:r.sent(),r.label=2;case 2:return/(AppleWebKit)/g.test(navigator.userAgent)?[4,Iv(a)]:[3,4];case 3:r.sent(),r.label=4;case 4:return"function"==typeof e?[2,Promise.resolve().then((function(){return e(a,i)})).then((function(){return s}))]:[2,s]}}))}))}));return a.open(),a.write(Rv(document.doctype)+""),Lv(this.referenceElement.ownerDocument,r,o),a.replaceChild(a.adoptNode(this.documentElement),a.documentElement),a.close(),l},e.prototype.createElementClone=function(e){if(qm(e,2),nv(e))return this.createCanvasClone(e);if(av(e))return this.createVideoClone(e);if(hv(e))return this.createStyleClone(e);var t=e.cloneNode(!1);return lv(t)&&(lv(e)&&e.currentSrc&&e.currentSrc!==e.src&&(t.src=e.currentSrc,t.srcset=""),"lazy"===t.loading&&(t.loading="eager")),pv(t)?this.createCustomElementClone(t):t},e.prototype.createCustomElementClone=function(e){var t=document.createElement("html2canvascustomelement");return Tv(e.style,t),t},e.prototype.createStyleClone=function(e){try{var t=e.sheet;if(t&&t.cssRules){var i=[].slice.call(t.cssRules,0).reduce((function(e,t){return t&&"string"==typeof t.cssText?e+t.cssText:e}),""),s=e.cloneNode(!1);return s.textContent=i,s}}catch(e){if(this.context.logger.error("Unable to access cssRules property",e),"SecurityError"!==e.name)throw e}return e.cloneNode(!1)},e.prototype.createCanvasClone=function(e){var t;if(this.options.inlineImages&&e.ownerDocument){var i=e.ownerDocument.createElement("img");try{return i.src=e.toDataURL(),i}catch(t){this.context.logger.info("Unable to inline canvas contents, canvas is tainted",e)}}var s=e.cloneNode(!1);try{s.width=e.width,s.height=e.height;var r=e.getContext("2d"),o=s.getContext("2d");if(o)if(!this.options.allowTaint&&r)o.putImageData(r.getImageData(0,0,e.width,e.height),0,0);else{var n=null!==(t=e.getContext("webgl2"))&&void 0!==t?t:e.getContext("webgl");if(n){var a=n.getContextAttributes();!1===(null==a?void 0:a.preserveDrawingBuffer)&&this.context.logger.warn("Unable to clone WebGL context as it has preserveDrawingBuffer=false",e)}o.drawImage(e,0,0)}return s}catch(t){this.context.logger.info("Unable to clone canvas as it is tainted",e)}return s},e.prototype.createVideoClone=function(e){var t=e.ownerDocument.createElement("canvas");t.width=e.offsetWidth,t.height=e.offsetHeight;var i=t.getContext("2d");try{return i&&(i.drawImage(e,0,0,t.width,t.height),this.options.allowTaint||i.getImageData(0,0,t.width,t.height)),t}catch(t){this.context.logger.info("Unable to clone video as it is tainted",e)}var s=e.ownerDocument.createElement("canvas");return s.width=e.offsetWidth,s.height=e.offsetHeight,s},e.prototype.appendChildNode=function(e,t,i){q_(t)&&(function(e){return"SCRIPT"===e.tagName}(t)||t.hasAttribute("data-html2canvas-ignore")||"function"==typeof this.options.ignoreElements&&this.options.ignoreElements(t))||this.options.copyStyles&&q_(t)&&hv(t)||e.appendChild(this.cloneNode(t,i))},e.prototype.cloneChildNodes=function(e,t,i){for(var s=this,r=e.shadowRoot?e.shadowRoot.firstChild:e.firstChild;r;r=r.nextSibling)if(q_(r)&&dv(r)&&"function"==typeof r.assignedNodes){var o=r.assignedNodes();o.length&&o.forEach((function(e){return s.appendChildNode(t,e,i)}))}else this.appendChildNode(t,r,i)},e.prototype.cloneNode=function(e,t){if(Z_(e))return document.createTextNode(e.data);if(!e.ownerDocument)return e.cloneNode(!1);var i=e.ownerDocument.defaultView;if(i&&q_(e)&&($_(e)||ev(e))){var s=this.createElementClone(e);s.style.transitionProperty="none";var r=i.getComputedStyle(e),o=i.getComputedStyle(e,":before"),n=i.getComputedStyle(e,":after");this.referenceElement===e&&$_(s)&&(this.clonedReferenceElement=s),ov(s)&&Nv(s);var a=this.counters.parse(new Ym(this.context,r)),l=this.resolvePseudoContent(e,s,o,l_.BEFORE);pv(e)&&(t=!0),av(e)||this.cloneChildNodes(e,s,t),l&&s.insertBefore(l,s.firstChild);var A=this.resolvePseudoContent(e,s,n,l_.AFTER);return A&&s.appendChild(A),this.counters.pop(a),(r&&(this.options.copyStyles||ev(e))&&!Av(e)||t)&&Tv(r,s),0===e.scrollTop&&0===e.scrollLeft||this.scrolledElements.push([s,e.scrollLeft,e.scrollTop]),(cv(e)||uv(e))&&(cv(s)||uv(s))&&(s.value=e.value),s}return e.cloneNode(!1)},e.prototype.resolvePseudoContent=function(e,t,i,s){var r=this;if(i){var o=i.content,n=t.ownerDocument;if(n&&o&&"none"!==o&&"-moz-alt-content"!==o&&"none"!==i.display){this.counters.parse(new Ym(this.context,i));var a=new Jm(this.context,i),l=n.createElement("html2canvaspseudoelement");Tv(i,l),a.content.forEach((function(t){if(0===t.type)l.appendChild(n.createTextNode(t.value));else if(22===t.type){var i=n.createElement("img");i.src=t.value,i.style.opacity="1",l.appendChild(i)}else if(18===t.type){if("attr"===t.name){var s=t.values.filter(Ff);s.length&&l.appendChild(n.createTextNode(e.getAttribute(s[0].value)||""))}else if("counter"===t.name){var o=t.values.filter(Tf),A=o[0],h=o[1];if(A&&Ff(A)){var c=r.counters.getCounterValue(A.value),u=h&&Ff(h)?sm.parse(r.context,h.value):3;l.appendChild(n.createTextNode(Pv(c,u,!1)))}}else if("counters"===t.name){var d=t.values.filter(Tf),p=(A=d[0],d[1]);h=d[2];if(A&&Ff(A)){var f=r.counters.getCounterValues(A.value),g=h&&Ff(h)?sm.parse(r.context,h.value):3,m=p&&0===p.type?p.value:"",_=f.map((function(e){return Pv(e,g,!1)})).join(m);l.appendChild(n.createTextNode(_))}}}else if(20===t.type)switch(t.value){case"open-quote":l.appendChild(n.createTextNode(jm(a.quotes,r.quoteDepth++,!0)));break;case"close-quote":l.appendChild(n.createTextNode(jm(a.quotes,--r.quoteDepth,!1)));break;default:l.appendChild(n.createTextNode(t.value))}})),l.className=Ov+" "+kv;var A=s===l_.BEFORE?" "+Ov:" "+kv;return ev(t)?t.className.baseValue+=A:t.className+=A,l}}},e.destroy=function(e){return!!e.parentNode&&(e.parentNode.removeChild(e),!0)},e}();!function(e){e[e.BEFORE=0]="BEFORE",e[e.AFTER=1]="AFTER"}(l_||(l_={}));var Mv,Ev=function(e,t){var i=e.createElement("iframe");return i.className="html2canvas-container",i.style.visibility="hidden",i.style.position="fixed",i.style.left="-10000px",i.style.top="0px",i.style.border="0",i.width=t.width.toString(),i.height=t.height.toString(),i.scrolling="no",i.setAttribute("data-html2canvas-ignore","true"),e.body.appendChild(i),i},Fv=function(e){return new Promise((function(t){e.complete?t():e.src?(e.onload=t,e.onerror=t):t()}))},Iv=function(e){return Promise.all([].slice.call(e.images,0).map(Fv))},Dv=function(e){return new Promise((function(t,i){var s=e.contentWindow;if(!s)return i("No window assigned for iframe");var r=s.document;s.onload=e.onload=function(){s.onload=e.onload=null;var i=setInterval((function(){r.body.childNodes.length>0&&"complete"===r.readyState&&(clearInterval(i),t(e))}),50)}}))},Sv=["all","d","content"],Tv=function(e,t){for(var i=e.length-1;i>=0;i--){var s=e.item(i);-1===Sv.indexOf(s)&&t.style.setProperty(s,e.getPropertyValue(s))}return t},Rv=function(e){var t="";return e&&(t+=""),t},Lv=function(e,t,i){e&&e.defaultView&&(t!==e.defaultView.pageXOffset||i!==e.defaultView.pageYOffset)&&e.defaultView.scrollTo(t,i)},Uv=function(e){var t=e[0],i=e[1],s=e[2];t.scrollLeft=i,t.scrollTop=s},Ov="___html2canvas___pseudoelement_before",kv="___html2canvas___pseudoelement_after",Nv=function(e){Qv(e,"."+Ov+':before{\n content: "" !important;\n display: none !important;\n}\n .'+kv+':after{\n content: "" !important;\n display: none !important;\n}')},Qv=function(e,t){var i=e.ownerDocument;if(i){var s=i.createElement("style");s.textContent=t,e.appendChild(s)}},Vv=function(){function e(){}return e.getOrigin=function(t){var i=e._link;return i?(i.href=t,i.href=i.href,i.protocol+i.hostname+i.port):"about:blank"},e.isSameOrigin=function(t){return e.getOrigin(t)===e._origin},e.setContext=function(t){e._link=t.document.createElement("a"),e._origin=e.getOrigin(t.location.href)},e._origin="about:blank",e}(),Hv=function(){function e(e,t){this.context=e,this._options=t,this._cache={}}return e.prototype.addImage=function(e){var t=Promise.resolve();return this.has(e)?t:Jv(e)||Wv(e)?((this._cache[e]=this.loadImage(e)).catch((function(){})),t):t},e.prototype.match=function(e){return this._cache[e]},e.prototype.loadImage=function(e){return zd(this,void 0,void 0,(function(){var t,i,s,r,o=this;return Wd(this,(function(n){switch(n.label){case 0:return t=Vv.isSameOrigin(e),i=!Kv(e)&&!0===this._options.useCORS&&y_.SUPPORT_CORS_IMAGES&&!t,s=!Kv(e)&&!t&&!Jv(e)&&"string"==typeof this._options.proxy&&y_.SUPPORT_CORS_XHR&&!i,t||!1!==this._options.allowTaint||Kv(e)||Jv(e)||s||i?(r=e,s?[4,this.proxy(r)]:[3,2]):[2];case 1:r=n.sent(),n.label=2;case 2:return this.context.logger.debug("Added image "+e.substring(0,256)),[4,new Promise((function(e,t){var s=new Image;s.onload=function(){return e(s)},s.onerror=t,(Xv(r)||i)&&(s.crossOrigin="anonymous"),s.src=r,!0===s.complete&&setTimeout((function(){return e(s)}),500),o._options.imageTimeout>0&&setTimeout((function(){return t("Timed out ("+o._options.imageTimeout+"ms) loading image")}),o._options.imageTimeout)}))];case 3:return[2,n.sent()]}}))}))},e.prototype.has=function(e){return void 0!==this._cache[e]},e.prototype.keys=function(){return Promise.resolve(Object.keys(this._cache))},e.prototype.proxy=function(e){var t=this,i=this._options.proxy;if(!i)throw new Error("No proxy defined");var s=e.substring(0,256);return new Promise((function(r,o){var n=y_.SUPPORT_RESPONSE_TYPE?"blob":"text",a=new XMLHttpRequest;a.onload=function(){if(200===a.status)if("text"===n)r(a.response);else{var e=new FileReader;e.addEventListener("load",(function(){return r(e.result)}),!1),e.addEventListener("error",(function(e){return o(e)}),!1),e.readAsDataURL(a.response)}else o("Failed to proxy resource "+s+" with status code "+a.status)},a.onerror=o;var l=i.indexOf("?")>-1?"&":"?";if(a.open("GET",""+i+l+"url="+encodeURIComponent(e)+"&responseType="+n),"text"!==n&&a instanceof XMLHttpRequest&&(a.responseType=n),t._options.imageTimeout){var A=t._options.imageTimeout;a.timeout=A,a.ontimeout=function(){return o("Timed out ("+A+"ms) proxying "+s)}}a.send()}))},e}(),jv=/^data:image\/svg\+xml/i,Gv=/^data:image\/.*;base64,/i,zv=/^data:image\/.*/i,Wv=function(e){return y_.SUPPORT_SVG_DRAWING||!Yv(e)},Kv=function(e){return zv.test(e)},Xv=function(e){return Gv.test(e)},Jv=function(e){return"blob"===e.substr(0,4)},Yv=function(e){return"svg"===e.substr(-3).toLowerCase()||jv.test(e)},Zv=function(){function e(e,t){this.type=0,this.x=e,this.y=t}return e.prototype.add=function(t,i){return new e(this.x+t,this.y+i)},e}(),qv=function(e,t,i){return new Zv(e.x+(t.x-e.x)*i,e.y+(t.y-e.y)*i)},$v=function(){function e(e,t,i,s){this.type=1,this.start=e,this.startControl=t,this.endControl=i,this.end=s}return e.prototype.subdivide=function(t,i){var s=qv(this.start,this.startControl,t),r=qv(this.startControl,this.endControl,t),o=qv(this.endControl,this.end,t),n=qv(s,r,t),a=qv(r,o,t),l=qv(n,a,t);return i?new e(this.start,s,n,l):new e(l,a,o,this.end)},e.prototype.add=function(t,i){return new e(this.start.add(t,i),this.startControl.add(t,i),this.endControl.add(t,i),this.end.add(t,i))},e.prototype.reverse=function(){return new e(this.end,this.endControl,this.startControl,this.start)},e}(),eb=function(e){return 1===e.type},tb=function(e){var t=e.styles,i=e.bounds,s=Hf(t.borderTopLeftRadius,i.width,i.height),r=s[0],o=s[1],n=Hf(t.borderTopRightRadius,i.width,i.height),a=n[0],l=n[1],A=Hf(t.borderBottomRightRadius,i.width,i.height),h=A[0],c=A[1],u=Hf(t.borderBottomLeftRadius,i.width,i.height),d=u[0],p=u[1],f=[];f.push((r+a)/i.width),f.push((d+h)/i.width),f.push((o+p)/i.height),f.push((l+c)/i.height);var g=Math.max.apply(Math,f);g>1&&(r/=g,o/=g,a/=g,l/=g,h/=g,c/=g,d/=g,p/=g);var m=i.width-a,_=i.height-c,v=i.width-h,b=i.height-p,y=t.borderTopWidth,x=t.borderRightWidth,B=t.borderBottomWidth,w=t.borderLeftWidth,P=jf(t.paddingTop,e.bounds.width),C=jf(t.paddingRight,e.bounds.width),M=jf(t.paddingBottom,e.bounds.width),E=jf(t.paddingLeft,e.bounds.width);this.topLeftBorderDoubleOuterBox=r>0||o>0?ib(i.left+w/3,i.top+y/3,r-w/3,o-y/3,Mv.TOP_LEFT):new Zv(i.left+w/3,i.top+y/3),this.topRightBorderDoubleOuterBox=r>0||o>0?ib(i.left+m,i.top+y/3,a-x/3,l-y/3,Mv.TOP_RIGHT):new Zv(i.left+i.width-x/3,i.top+y/3),this.bottomRightBorderDoubleOuterBox=h>0||c>0?ib(i.left+v,i.top+_,h-x/3,c-B/3,Mv.BOTTOM_RIGHT):new Zv(i.left+i.width-x/3,i.top+i.height-B/3),this.bottomLeftBorderDoubleOuterBox=d>0||p>0?ib(i.left+w/3,i.top+b,d-w/3,p-B/3,Mv.BOTTOM_LEFT):new Zv(i.left+w/3,i.top+i.height-B/3),this.topLeftBorderDoubleInnerBox=r>0||o>0?ib(i.left+2*w/3,i.top+2*y/3,r-2*w/3,o-2*y/3,Mv.TOP_LEFT):new Zv(i.left+2*w/3,i.top+2*y/3),this.topRightBorderDoubleInnerBox=r>0||o>0?ib(i.left+m,i.top+2*y/3,a-2*x/3,l-2*y/3,Mv.TOP_RIGHT):new Zv(i.left+i.width-2*x/3,i.top+2*y/3),this.bottomRightBorderDoubleInnerBox=h>0||c>0?ib(i.left+v,i.top+_,h-2*x/3,c-2*B/3,Mv.BOTTOM_RIGHT):new Zv(i.left+i.width-2*x/3,i.top+i.height-2*B/3),this.bottomLeftBorderDoubleInnerBox=d>0||p>0?ib(i.left+2*w/3,i.top+b,d-2*w/3,p-2*B/3,Mv.BOTTOM_LEFT):new Zv(i.left+2*w/3,i.top+i.height-2*B/3),this.topLeftBorderStroke=r>0||o>0?ib(i.left+w/2,i.top+y/2,r-w/2,o-y/2,Mv.TOP_LEFT):new Zv(i.left+w/2,i.top+y/2),this.topRightBorderStroke=r>0||o>0?ib(i.left+m,i.top+y/2,a-x/2,l-y/2,Mv.TOP_RIGHT):new Zv(i.left+i.width-x/2,i.top+y/2),this.bottomRightBorderStroke=h>0||c>0?ib(i.left+v,i.top+_,h-x/2,c-B/2,Mv.BOTTOM_RIGHT):new Zv(i.left+i.width-x/2,i.top+i.height-B/2),this.bottomLeftBorderStroke=d>0||p>0?ib(i.left+w/2,i.top+b,d-w/2,p-B/2,Mv.BOTTOM_LEFT):new Zv(i.left+w/2,i.top+i.height-B/2),this.topLeftBorderBox=r>0||o>0?ib(i.left,i.top,r,o,Mv.TOP_LEFT):new Zv(i.left,i.top),this.topRightBorderBox=a>0||l>0?ib(i.left+m,i.top,a,l,Mv.TOP_RIGHT):new Zv(i.left+i.width,i.top),this.bottomRightBorderBox=h>0||c>0?ib(i.left+v,i.top+_,h,c,Mv.BOTTOM_RIGHT):new Zv(i.left+i.width,i.top+i.height),this.bottomLeftBorderBox=d>0||p>0?ib(i.left,i.top+b,d,p,Mv.BOTTOM_LEFT):new Zv(i.left,i.top+i.height),this.topLeftPaddingBox=r>0||o>0?ib(i.left+w,i.top+y,Math.max(0,r-w),Math.max(0,o-y),Mv.TOP_LEFT):new Zv(i.left+w,i.top+y),this.topRightPaddingBox=a>0||l>0?ib(i.left+Math.min(m,i.width-x),i.top+y,m>i.width+x?0:Math.max(0,a-x),Math.max(0,l-y),Mv.TOP_RIGHT):new Zv(i.left+i.width-x,i.top+y),this.bottomRightPaddingBox=h>0||c>0?ib(i.left+Math.min(v,i.width-w),i.top+Math.min(_,i.height-B),Math.max(0,h-x),Math.max(0,c-B),Mv.BOTTOM_RIGHT):new Zv(i.left+i.width-x,i.top+i.height-B),this.bottomLeftPaddingBox=d>0||p>0?ib(i.left+w,i.top+Math.min(b,i.height-B),Math.max(0,d-w),Math.max(0,p-B),Mv.BOTTOM_LEFT):new Zv(i.left+w,i.top+i.height-B),this.topLeftContentBox=r>0||o>0?ib(i.left+w+E,i.top+y+P,Math.max(0,r-(w+E)),Math.max(0,o-(y+P)),Mv.TOP_LEFT):new Zv(i.left+w+E,i.top+y+P),this.topRightContentBox=a>0||l>0?ib(i.left+Math.min(m,i.width+w+E),i.top+y+P,m>i.width+w+E?0:a-w+E,l-(y+P),Mv.TOP_RIGHT):new Zv(i.left+i.width-(x+C),i.top+y+P),this.bottomRightContentBox=h>0||c>0?ib(i.left+Math.min(v,i.width-(w+E)),i.top+Math.min(_,i.height+y+P),Math.max(0,h-(x+C)),c-(B+M),Mv.BOTTOM_RIGHT):new Zv(i.left+i.width-(x+C),i.top+i.height-(B+M)),this.bottomLeftContentBox=d>0||p>0?ib(i.left+w+E,i.top+b,Math.max(0,d-(w+E)),p-(B+M),Mv.BOTTOM_LEFT):new Zv(i.left+w+E,i.top+i.height-(B+M))};!function(e){e[e.TOP_LEFT=0]="TOP_LEFT",e[e.TOP_RIGHT=1]="TOP_RIGHT",e[e.BOTTOM_RIGHT=2]="BOTTOM_RIGHT",e[e.BOTTOM_LEFT=3]="BOTTOM_LEFT"}(Mv||(Mv={}));var ib=function(e,t,i,s,r){var o=(Math.sqrt(2)-1)/3*4,n=i*o,a=s*o,l=e+i,A=t+s;switch(r){case Mv.TOP_LEFT:return new $v(new Zv(e,A),new Zv(e,A-a),new Zv(l-n,t),new Zv(l,t));case Mv.TOP_RIGHT:return new $v(new Zv(e,t),new Zv(e+n,t),new Zv(l,A-a),new Zv(l,A));case Mv.BOTTOM_RIGHT:return new $v(new Zv(l,t),new Zv(l,t+a),new Zv(e+n,A),new Zv(e,A));case Mv.BOTTOM_LEFT:default:return new $v(new Zv(l,A),new Zv(l-n,A),new Zv(e,t+a),new Zv(e,t))}},sb=function(e){return[e.topLeftBorderBox,e.topRightBorderBox,e.bottomRightBorderBox,e.bottomLeftBorderBox]},rb=function(e){return[e.topLeftPaddingBox,e.topRightPaddingBox,e.bottomRightPaddingBox,e.bottomLeftPaddingBox]},ob=function(e,t,i){this.offsetX=e,this.offsetY=t,this.matrix=i,this.type=0,this.target=6},nb=function(e,t){this.path=e,this.target=t,this.type=1},ab=function(e){this.opacity=e,this.type=2,this.target=6},lb=function(e){return 1===e.type},Ab=function(e,t){return e.length===t.length&&e.some((function(e,i){return e===t[i]}))},hb=function(e){this.element=e,this.inlineLevel=[],this.nonInlineLevel=[],this.negativeZIndex=[],this.zeroOrAutoZIndexOrTransformedOrOpacity=[],this.positiveZIndex=[],this.nonPositionedFloats=[],this.nonPositionedInlineLevel=[]},cb=function(){function e(e,t){if(this.container=e,this.parent=t,this.effects=[],this.curves=new tb(this.container),this.container.styles.opacity<1&&this.effects.push(new ab(this.container.styles.opacity)),null!==this.container.styles.transform){var i=this.container.bounds.left+this.container.styles.transformOrigin[0].number,s=this.container.bounds.top+this.container.styles.transformOrigin[1].number,r=this.container.styles.transform;this.effects.push(new ob(i,s,r))}if(0!==this.container.styles.overflowX){var o=sb(this.curves),n=rb(this.curves);Ab(o,n)?this.effects.push(new nb(o,6)):(this.effects.push(new nb(o,2)),this.effects.push(new nb(n,4)))}}return e.prototype.getEffects=function(e){for(var t=-1===[2,3].indexOf(this.container.styles.position),i=this.parent,s=this.effects.slice(0);i;){var r=i.effects.filter((function(e){return!lb(e)}));if(t||0!==i.container.styles.position||!i.parent){if(s.unshift.apply(s,r),t=-1===[2,3].indexOf(i.container.styles.position),0!==i.container.styles.overflowX){var o=sb(i.curves),n=rb(i.curves);Ab(o,n)||s.unshift(new nb(n,6))}}else s.unshift.apply(s,r);i=i.parent}return s.filter((function(t){return Om(t.target,e)}))},e}(),ub=function(e,t,i,s){e.container.elements.forEach((function(r){var o=Om(r.flags,4),n=Om(r.flags,2),a=new cb(r,e);Om(r.styles.display,2048)&&s.push(a);var l=Om(r.flags,8)?[]:s;if(o||n){var A=o||r.styles.isPositioned()?i:t,h=new hb(a);if(r.styles.isPositioned()||r.styles.opacity<1||r.styles.isTransformed()){var c=r.styles.zIndex.order;if(c<0){var u=0;A.negativeZIndex.some((function(e,t){return c>e.element.container.styles.zIndex.order?(u=t,!1):u>0})),A.negativeZIndex.splice(u,0,h)}else if(c>0){var d=0;A.positiveZIndex.some((function(e,t){return c>=e.element.container.styles.zIndex.order?(d=t+1,!1):d>0})),A.positiveZIndex.splice(d,0,h)}else A.zeroOrAutoZIndexOrTransformedOrOpacity.push(h)}else r.styles.isFloating()?A.nonPositionedFloats.push(h):A.nonPositionedInlineLevel.push(h);ub(a,h,o?h:i,l)}else r.styles.isInlineLevel()?t.inlineLevel.push(a):t.nonInlineLevel.push(a),ub(a,t,i,l);Om(r.flags,8)&&db(r,l)}))},db=function(e,t){for(var i=e instanceof O_?e.start:1,s=e instanceof O_&&e.reversed,r=0;r0&&e.intrinsicHeight>0){var s=_b(e),r=rb(t);this.path(r),this.ctx.save(),this.ctx.clip(),this.ctx.drawImage(i,0,0,e.intrinsicWidth,e.intrinsicHeight,s.left,s.top,s.width,s.height),this.ctx.restore()}},t.prototype.renderNodeContent=function(e){return zd(this,void 0,void 0,(function(){var i,s,r,o,n,a,l,A,h,c,u,d,p,f,g,m,_,v;return Wd(this,(function(b){switch(b.label){case 0:this.applyEffects(e.getEffects(4)),i=e.container,s=e.curves,r=i.styles,o=0,n=i.textNodes,b.label=1;case 1:return o0&&B>0&&(m=s.ctx.createPattern(p,"repeat"),s.renderRepeat(v,m,P,C))):function(e){return 2===e.type}(i)&&(_=vb(e,t,[null,null,null]),v=_[0],b=_[1],y=_[2],x=_[3],B=_[4],w=0===i.position.length?[Qf]:i.position,P=jf(w[0],x),C=jf(w[w.length-1],B),M=function(e,t,i,s,r){var o=0,n=0;switch(e.size){case 0:0===e.shape?o=n=Math.min(Math.abs(t),Math.abs(t-s),Math.abs(i),Math.abs(i-r)):1===e.shape&&(o=Math.min(Math.abs(t),Math.abs(t-s)),n=Math.min(Math.abs(i),Math.abs(i-r)));break;case 2:if(0===e.shape)o=n=Math.min(hg(t,i),hg(t,i-r),hg(t-s,i),hg(t-s,i-r));else if(1===e.shape){var a=Math.min(Math.abs(i),Math.abs(i-r))/Math.min(Math.abs(t),Math.abs(t-s)),l=cg(s,r,t,i,!0),A=l[0],h=l[1];n=a*(o=hg(A-t,(h-i)/a))}break;case 1:0===e.shape?o=n=Math.max(Math.abs(t),Math.abs(t-s),Math.abs(i),Math.abs(i-r)):1===e.shape&&(o=Math.max(Math.abs(t),Math.abs(t-s)),n=Math.max(Math.abs(i),Math.abs(i-r)));break;case 3:if(0===e.shape)o=n=Math.max(hg(t,i),hg(t,i-r),hg(t-s,i),hg(t-s,i-r));else if(1===e.shape){a=Math.max(Math.abs(i),Math.abs(i-r))/Math.max(Math.abs(t),Math.abs(t-s));var c=cg(s,r,t,i,!1);A=c[0],h=c[1],n=a*(o=hg(A-t,(h-i)/a))}}return Array.isArray(e.size)&&(o=jf(e.size[0],s),n=2===e.size.length?jf(e.size[1],r):o),[o,n]}(i,P,C,x,B),E=M[0],F=M[1],E>0&&F>0&&(I=s.ctx.createRadialGradient(b+P,y+C,0,b+P,y+C,E),lg(i.stops,2*E).forEach((function(e){return I.addColorStop(e.stop,Yf(e.color))})),s.path(v),s.ctx.fillStyle=I,E!==F?(D=e.bounds.left+.5*e.bounds.width,S=e.bounds.top+.5*e.bounds.height,R=1/(T=F/E),s.ctx.save(),s.ctx.translate(D,S),s.ctx.transform(1,0,0,T,0,0),s.ctx.translate(-D,-S),s.ctx.fillRect(b,R*(y-S)+S,x,B*R),s.ctx.restore()):s.ctx.fill())),L.label=6;case 6:return t--,[2]}}))},s=this,r=0,o=e.styles.backgroundImage.slice(0).reverse(),a.label=1;case 1:return r0?2!==l.style?[3,5]:[4,this.renderDashedDottedBorder(l.color,l.width,o,e.curves,2)]:[3,11]:[3,13];case 4:return h.sent(),[3,11];case 5:return 3!==l.style?[3,7]:[4,this.renderDashedDottedBorder(l.color,l.width,o,e.curves,3)];case 6:return h.sent(),[3,11];case 7:return 4!==l.style?[3,9]:[4,this.renderDoubleBorder(l.color,l.width,o,e.curves)];case 8:return h.sent(),[3,11];case 9:return[4,this.renderSolidBorder(l.color,o,e.curves)];case 10:h.sent(),h.label=11;case 11:o++,h.label=12;case 12:return n++,[3,3];case 13:return[2]}}))}))},t.prototype.renderDashedDottedBorder=function(e,t,i,s,r){return zd(this,void 0,void 0,(function(){var o,n,a,l,A,h,c,u,d,p,f,g,m,_,v,b;return Wd(this,(function(y){return this.ctx.save(),o=function(e,t){switch(t){case 0:return fb(e.topLeftBorderStroke,e.topRightBorderStroke);case 1:return fb(e.topRightBorderStroke,e.bottomRightBorderStroke);case 2:return fb(e.bottomRightBorderStroke,e.bottomLeftBorderStroke);default:return fb(e.bottomLeftBorderStroke,e.topLeftBorderStroke)}}(s,i),n=pb(s,i),2===r&&(this.path(n),this.ctx.clip()),eb(n[0])?(a=n[0].start.x,l=n[0].start.y):(a=n[0].x,l=n[0].y),eb(n[1])?(A=n[1].end.x,h=n[1].end.y):(A=n[1].x,h=n[1].y),c=0===i||2===i?Math.abs(a-A):Math.abs(l-h),this.ctx.beginPath(),3===r?this.formatPath(o):this.formatPath(n.slice(0,2)),u=t<3?3*t:2*t,d=t<3?2*t:t,3===r&&(u=t,d=t),p=!0,c<=2*u?p=!1:c<=2*u+d?(u*=f=c/(2*u+d),d*=f):(g=Math.floor((c+d)/(u+d)),m=(c-g*u)/(g-1),d=(_=(c-(g+1)*u)/g)<=0||Math.abs(d-m){})),Zb(this,"_reject",(()=>{})),this.name=e,this.workerThread=t,this.result=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}postMessage(e,t){this.workerThread.postMessage({source:"loaders.gl",type:e,payload:t})}done(e){Gb(this.isRunning),this.isRunning=!1,this._resolve(e)}error(e){Gb(this.isRunning),this.isRunning=!1,this._reject(e)}}class $b{}const ey=new Map;function ty(e){Gb(e.source&&!e.url||!e.source&&e.url);let t=ey.get(e.source||e.url);return t||(e.url&&(t=function(e){if(!e.startsWith("http"))return e;return iy((t=e,"try {\n importScripts('".concat(t,"');\n} catch (error) {\n console.error(error);\n throw error;\n}")));var t}(e.url),ey.set(e.url,t)),e.source&&(t=iy(e.source),ey.set(e.source,t))),Gb(t),t}function iy(e){const t=new Blob([e],{type:"application/javascript"});return URL.createObjectURL(t)}function sy(e,t=!0,i){const s=i||new Set;if(e){if(ry(e))s.add(e);else if(ry(e.buffer))s.add(e.buffer);else if(ArrayBuffer.isView(e));else if(t&&"object"==typeof e)for(const i in e)sy(e[i],t,s)}else;return void 0===i?Array.from(s):[]}function ry(e){return!!e&&(e instanceof ArrayBuffer||("undefined"!=typeof MessagePort&&e instanceof MessagePort||("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)))}const oy=()=>{};class ny{static isSupported(){return"undefined"!=typeof Worker&&Kb||void 0!==typeof $b}constructor(e){Zb(this,"name",void 0),Zb(this,"source",void 0),Zb(this,"url",void 0),Zb(this,"terminated",!1),Zb(this,"worker",void 0),Zb(this,"onMessage",void 0),Zb(this,"onError",void 0),Zb(this,"_loadableURL","");const{name:t,source:i,url:s}=e;Gb(i||s),this.name=t,this.source=i,this.url=s,this.onMessage=oy,this.onError=e=>console.log(e),this.worker=Kb?this._createBrowserWorker():this._createNodeWorker()}destroy(){this.onMessage=oy,this.onError=oy,this.worker.terminate(),this.terminated=!0}get isRunning(){return Boolean(this.onMessage)}postMessage(e,t){t=t||sy(e),this.worker.postMessage(e,t)}_getErrorFromErrorEvent(e){let t="Failed to load ";return t+="worker ".concat(this.name," from ").concat(this.url,". "),e.message&&(t+="".concat(e.message," in ")),e.lineno&&(t+=":".concat(e.lineno,":").concat(e.colno)),new Error(t)}_createBrowserWorker(){this._loadableURL=ty({source:this.source,url:this.url});const e=new Worker(this._loadableURL,{name:this.name});return e.onmessage=e=>{e.data?this.onMessage(e.data):this.onError(new Error("No data received"))},e.onerror=e=>{this.onError(this._getErrorFromErrorEvent(e)),this.terminated=!0},e.onmessageerror=e=>console.error(e),e}_createNodeWorker(){let e;if(this.url){const t=this.url.includes(":/")||this.url.startsWith("/")?this.url:"./".concat(this.url);e=new $b(t,{eval:!1})}else{if(!this.source)throw new Error("no worker");e=new $b(this.source,{eval:!0})}return e.on("message",(e=>{this.onMessage(e)})),e.on("error",(e=>{this.onError(e)})),e.on("exit",(e=>{})),e}}class ay{static isSupported(){return ny.isSupported()}constructor(e){Zb(this,"name","unnamed"),Zb(this,"source",void 0),Zb(this,"url",void 0),Zb(this,"maxConcurrency",1),Zb(this,"maxMobileConcurrency",1),Zb(this,"onDebug",(()=>{})),Zb(this,"reuseWorkers",!0),Zb(this,"props",{}),Zb(this,"jobQueue",[]),Zb(this,"idleQueue",[]),Zb(this,"count",0),Zb(this,"isDestroyed",!1),this.source=e.source,this.url=e.url,this.setProps(e)}destroy(){this.idleQueue.forEach((e=>e.destroy())),this.isDestroyed=!0}setProps(e){this.props={...this.props,...e},void 0!==e.name&&(this.name=e.name),void 0!==e.maxConcurrency&&(this.maxConcurrency=e.maxConcurrency),void 0!==e.maxMobileConcurrency&&(this.maxMobileConcurrency=e.maxMobileConcurrency),void 0!==e.reuseWorkers&&(this.reuseWorkers=e.reuseWorkers),void 0!==e.onDebug&&(this.onDebug=e.onDebug)}async startJob(e,t=((e,t,i)=>e.done(i)),i=((e,t)=>e.error(t))){const s=new Promise((s=>(this.jobQueue.push({name:e,onMessage:t,onError:i,onStart:s}),this)));return this._startQueuedJob(),await s}async _startQueuedJob(){if(!this.jobQueue.length)return;const e=this._getAvailableWorker();if(!e)return;const t=this.jobQueue.shift();if(t){this.onDebug({message:"Starting job",name:t.name,workerThread:e,backlog:this.jobQueue.length});const i=new qb(t.name,e);e.onMessage=e=>t.onMessage(i,e.type,e.payload),e.onError=e=>t.onError(i,e),t.onStart(i);try{await i.result}finally{this.returnWorkerToQueue(e)}}}returnWorkerToQueue(e){this.isDestroyed||!this.reuseWorkers||this.count>this._getMaxConcurrency()?(e.destroy(),this.count--):this.idleQueue.push(e),this.isDestroyed||this._startQueuedJob()}_getAvailableWorker(){if(this.idleQueue.length>0)return this.idleQueue.shift()||null;if(this.count{}};class Ay{static isSupported(){return ny.isSupported()}static getWorkerFarm(e={}){return Ay._workerFarm=Ay._workerFarm||new Ay({}),Ay._workerFarm.setProps(e),Ay._workerFarm}constructor(e){Zb(this,"props",void 0),Zb(this,"workerPools",new Map),this.props={...ly},this.setProps(e),this.workerPools=new Map}destroy(){for(const e of this.workerPools.values())e.destroy();this.workerPools=new Map}setProps(e){this.props={...this.props,...e};for(const e of this.workerPools.values())e.setProps(this._getWorkerPoolProps())}getWorkerPool(e){const{name:t,source:i,url:s}=e;let r=this.workerPools.get(t);return r||(r=new ay({name:t,source:i,url:s}),r.setProps(this._getWorkerPoolProps()),this.workerPools.set(t,r)),r}_getWorkerPoolProps(){return{maxConcurrency:this.props.maxConcurrency,maxMobileConcurrency:this.props.maxMobileConcurrency,reuseWorkers:this.props.reuseWorkers,onDebug:this.props.onDebug}}}Zb(Ay,"_workerFarm",void 0);var hy=Object.freeze({__proto__:null,default:{}});const cy={};async function uy(e,t=null,i={}){return t&&(e=function(e,t,i){if(e.startsWith("http"))return e;const s=i.modules||{};if(s[e])return s[e];if(!Kb)return"modules/".concat(t,"/dist/libs/").concat(e);if(i.CDN)return Gb(i.CDN.startsWith("http")),"".concat(i.CDN,"/").concat(t,"@").concat("3.2.6","/dist/libs/").concat(e);if(Xb)return"../src/libs/".concat(e);return"modules/".concat(t,"/src/libs/").concat(e)}(e,t,i)),cy[e]=cy[e]||async function(e){if(e.endsWith("wasm")){const t=await fetch(e);return await t.arrayBuffer()}if(!Kb)try{return hy&&void 0}catch{return null}if(Xb)return importScripts(e);const t=await fetch(e);return function(e,t){if(!Kb)return;if(Xb)return eval.call(Wb,e),null;const i=document.createElement("script");i.id=t;try{i.appendChild(document.createTextNode(e))}catch(t){i.text=e}return document.body.appendChild(i),null}(await t.text(),e)}(e),await cy[e]}async function dy(e,t,i,s,r){const o=e.id,n=function(e,t={}){const i=t[e.id]||{},s="".concat(e.id,"-worker.js");let r=i.workerUrl;if(r||"compression"!==e.id||(r=t.workerUrl),"test"===t._workerType&&(r="modules/".concat(e.module,"/dist/").concat(s)),!r){let t=e.version;"latest"===t&&(t="latest");const i=t?"@".concat(t):"";r="https://unpkg.com/@loaders.gl/".concat(e.module).concat(i,"/dist/").concat(s)}return Gb(r),r}(e,i),a=Ay.getWorkerFarm(i).getWorkerPool({name:o,url:n});i=JSON.parse(JSON.stringify(i)),s=JSON.parse(JSON.stringify(s||{}));const l=await a.startJob("process-on-worker",py.bind(null,r));l.postMessage("process",{input:t,options:i,context:s});const A=await l.result;return await A.result}async function py(e,t,i,s){switch(i){case"done":t.done(s);break;case"error":t.error(new Error(s.error));break;case"process":const{id:r,input:o,options:n}=s;try{const i=await e(o,n);t.postMessage("done",{id:r,result:i})}catch(e){const i=e instanceof Error?e.message:"unknown error";t.postMessage("error",{id:r,error:i})}break;default:console.warn("parse-with-worker unknown message ".concat(i))}}function fy(e,t,i){if(e.byteLength<=t+i)return"";const s=new DataView(e);let r="";for(let e=0;e=0),Vb(t>0),e+(t-1)&~(t-1)}function yy(e,t,i){let s;if(e instanceof ArrayBuffer)s=new Uint8Array(e);else{const t=e.byteOffset,i=e.byteLength;s=new Uint8Array(e.buffer||e.arrayBuffer,t,i)}return t.set(s,i),i+by(s.byteLength,4)}async function xy(e){const t=[];for await(const i of e)t.push(i);return function(...e){const t=e.map((e=>e instanceof ArrayBuffer?new Uint8Array(e):e)),i=t.reduce(((e,t)=>e+t.byteLength),0),s=new Uint8Array(i);let r=0;for(const e of t)s.set(e,r),r+=e.byteLength;return s.buffer}(...t)}const By={};const wy=e=>"function"==typeof e,Py=e=>null!==e&&"object"==typeof e,Cy=e=>Py(e)&&e.constructor==={}.constructor,My=e=>"undefined"!=typeof Response&&e instanceof Response||e&&e.arrayBuffer&&e.text&&e.json,Ey=e=>"undefined"!=typeof Blob&&e instanceof Blob,Fy=e=>(e=>"undefined"!=typeof ReadableStream&&e instanceof ReadableStream||Py(e)&&wy(e.tee)&&wy(e.cancel)&&wy(e.getReader))(e)||(e=>Py(e)&&wy(e.read)&&wy(e.pipe)&&(e=>"boolean"==typeof e)(e.readable))(e),Iy=/^data:([-\w.]+\/[-\w.+]+)(;|,)/,Dy=/^([-\w.]+\/[-\w.+]+)/;function Sy(e){const t=Dy.exec(e);return t?t[1]:e}function Ty(e){const t=Iy.exec(e);return t?t[1]:""}const Ry=/\?.*/;function Ly(e){if(My(e)){const t=Uy(e.url||"");return{url:t,type:Sy(e.headers.get("content-type")||"")||Ty(t)}}return Ey(e)?{url:Uy(e.name||""),type:e.type||""}:"string"==typeof e?{url:Uy(e),type:Ty(e)}:{url:"",type:""}}function Uy(e){return e.replace(Ry,"")}async function Oy(e){if(My(e))return e;const t={},i=function(e){return My(e)?e.headers["content-length"]||-1:Ey(e)?e.size:"string"==typeof e?e.length:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:-1}(e);i>=0&&(t["content-length"]=String(i));const{url:s,type:r}=Ly(e);r&&(t["content-type"]=r);const o=await async function(e){const t=5;if("string"==typeof e)return"data:,".concat(e.slice(0,t));if(e instanceof Blob){const t=e.slice(0,5);return await new Promise((e=>{const i=new FileReader;i.onload=t=>{var i;return e(null==t||null===(i=t.target)||void 0===i?void 0:i.result)},i.readAsDataURL(t)}))}if(e instanceof ArrayBuffer){const i=function(e){let t="";const i=new Uint8Array(e);for(let e=0;e=0)}();class Gy{constructor(e,t,i="sessionStorage"){this.storage=function(e){try{const t=window[e],i="__storage_test__";return t.setItem(i,i),t.removeItem(i),t}catch(e){return null}}(i),this.id=e,this.config={},Object.assign(this.config,t),this._loadConfiguration()}getConfiguration(){return this.config}setConfiguration(e){return this.config={},this.updateConfiguration(e)}updateConfiguration(e){if(Object.assign(this.config,e),this.storage){const e=JSON.stringify(this.config);this.storage.setItem(this.id,e)}return this}_loadConfiguration(){let e={};if(this.storage){const t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}}function zy(e,t,i,s=600){const r=e.src.replace(/\(/g,"%28").replace(/\)/g,"%29");e.width>s&&(i=Math.min(i,s/e.width));const o=e.width*i,n=e.height*i,a=["font-size:1px;","padding:".concat(Math.floor(n/2),"px ").concat(Math.floor(o/2),"px;"),"line-height:".concat(n,"px;"),"background:url(".concat(r,");"),"background-size:".concat(o,"px ").concat(n,"px;"),"color:transparent;"].join("");return["".concat(t," %c+"),a]}const Wy={BLACK:30,RED:31,GREEN:32,YELLOW:33,BLUE:34,MAGENTA:35,CYAN:36,WHITE:37,BRIGHT_BLACK:90,BRIGHT_RED:91,BRIGHT_GREEN:92,BRIGHT_YELLOW:93,BRIGHT_BLUE:94,BRIGHT_MAGENTA:95,BRIGHT_CYAN:96,BRIGHT_WHITE:97};function Ky(e){return"string"==typeof e?Wy[e.toUpperCase()]||Wy.WHITE:e}function Xy(e,t){if(!e)throw new Error(t||"Assertion failed")}function Jy(){let e;if(jy&&Qy.performance)e=Qy.performance.now();else if(Vy.hrtime){const t=Vy.hrtime();e=1e3*t[0]+t[1]/1e6}else e=Date.now();return e}const Yy={debug:jy&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},Zy={enabled:!0,level:0};function qy(){}const $y={},ex={once:!0};function tx(e){for(const t in e)for(const i in e[t])return i||"untitled";return"empty"}class ix{constructor({id:e}={id:""}){this.id=e,this.VERSION=Hy,this._startTs=Jy(),this._deltaTs=Jy(),this.LOG_THROTTLE_TIMEOUT=0,this._storage=new Gy("__probe-".concat(this.id,"__"),Zy),this.userData={},this.timeStamp("".concat(this.id," started")),function(e,t=["constructor"]){const i=Object.getPrototypeOf(e),s=Object.getOwnPropertyNames(i);for(const i of s)"function"==typeof e[i]&&(t.find((e=>i===e))||(e[i]=e[i].bind(e)))}(this),Object.seal(this)}set level(e){this.setLevel(e)}get level(){return this.getLevel()}isEnabled(){return this._storage.config.enabled}getLevel(){return this._storage.config.level}getTotal(){return Number((Jy()-this._startTs).toPrecision(10))}getDelta(){return Number((Jy()-this._deltaTs).toPrecision(10))}set priority(e){this.level=e}get priority(){return this.level}getPriority(){return this.level}enable(e=!0){return this._storage.updateConfiguration({enabled:e}),this}setLevel(e){return this._storage.updateConfiguration({level:e}),this}assert(e,t){Xy(e,t)}warn(e){return this._getLogFunction(0,e,Yy.warn,arguments,ex)}error(e){return this._getLogFunction(0,e,Yy.error,arguments)}deprecated(e,t){return this.warn("`".concat(e,"` is deprecated and will be removed in a later version. Use `").concat(t,"` instead"))}removed(e,t){return this.error("`".concat(e,"` has been removed. Use `").concat(t,"` instead"))}probe(e,t){return this._getLogFunction(e,t,Yy.log,arguments,{time:!0,once:!0})}log(e,t){return this._getLogFunction(e,t,Yy.debug,arguments)}info(e,t){return this._getLogFunction(e,t,console.info,arguments)}once(e,t){return this._getLogFunction(e,t,Yy.debug||Yy.info,arguments,ex)}table(e,t,i){return t?this._getLogFunction(e,t,console.table||qy,i&&[i],{tag:tx(t)}):qy}image({logLevel:e,priority:t,image:i,message:s="",scale:r=1}){return this._shouldLog(e||t)?jy?function({image:e,message:t="",scale:i=1}){if("string"==typeof e){const s=new Image;return s.onload=()=>{const e=zy(s,t,i);console.log(...e)},s.src=e,qy}const s=e.nodeName||"";if("img"===s.toLowerCase())return console.log(...zy(e,t,i)),qy;if("canvas"===s.toLowerCase()){const s=new Image;return s.onload=()=>console.log(...zy(s,t,i)),s.src=e.toDataURL(),qy}return qy}({image:i,message:s,scale:r}):function({image:e,message:t="",scale:i=1}){let s=null;try{s=module.require("asciify-image")}catch(e){}if(s)return()=>s(e,{fit:"box",width:"".concat(Math.round(80*i),"%")}).then((e=>console.log(e)));return qy}({image:i,message:s,scale:r}):qy}settings(){console.table?console.table(this._storage.config):console.log(this._storage.config)}get(e){return this._storage.config[e]}set(e,t){this._storage.updateConfiguration({[e]:t})}time(e,t){return this._getLogFunction(e,t,console.time?console.time:console.info)}timeEnd(e,t){return this._getLogFunction(e,t,console.timeEnd?console.timeEnd:console.info)}timeStamp(e,t){return this._getLogFunction(e,t,console.timeStamp||qy)}group(e,t,i={collapsed:!1}){i=rx({logLevel:e,message:t,opts:i});const{collapsed:s}=i;return i.method=(s?console.groupCollapsed:console.group)||console.info,this._getLogFunction(i)}groupCollapsed(e,t,i={}){return this.group(e,t,Object.assign({},i,{collapsed:!0}))}groupEnd(e){return this._getLogFunction(e,"",console.groupEnd||qy)}withGroup(e,t,i){this.group(e,t)();try{i()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&this.getLevel()>=sx(e)}_getLogFunction(e,t,i,s=[],r){if(this._shouldLog(e)){r=rx({logLevel:e,message:t,args:s,opts:r}),Xy(i=i||r.method),r.total=this.getTotal(),r.delta=this.getDelta(),this._deltaTs=Jy();const o=r.tag||r.message;if(r.once){if($y[o])return qy;$y[o]=Jy()}return t=function(e,t,i){if("string"==typeof t){const s=i.time?function(e,t=8){const i=Math.max(t-e.length,0);return"".concat(" ".repeat(i)).concat(e)}(function(e){let t;return t=e<10?"".concat(e.toFixed(2),"ms"):e<100?"".concat(e.toFixed(1),"ms"):e<1e3?"".concat(e.toFixed(0),"ms"):"".concat((e/1e3).toFixed(2),"s"),t}(i.total)):"";t=i.time?"".concat(e,": ").concat(s," ").concat(t):"".concat(e,": ").concat(t),t=function(e,t,i){return jy||"string"!=typeof e||(t&&(t=Ky(t),e="[".concat(t,"m").concat(e,"")),i&&(t=Ky(i),e="[".concat(i+10,"m").concat(e,""))),e}(t,i.color,i.background)}return t}(this.id,r.message,r),i.bind(console,t,...r.args)}return qy}}function sx(e){if(!e)return 0;let t;switch(typeof e){case"number":t=e;break;case"object":t=e.logLevel||e.priority||0;break;default:return 0}return Xy(Number.isFinite(t)&&t>=0),t}function rx(e){const{logLevel:t,message:i}=e;e.logLevel=sx(t);const s=e.args?Array.from(e.args):[];for(;s.length&&s.shift()!==i;);switch(e.args=s,typeof t){case"string":case"function":void 0!==i&&s.unshift(i),e.message=t;break;case"object":Object.assign(e,t)}"function"==typeof e.message&&(e.message=e.message());const r=typeof e.message;return Xy("string"===r||"object"===r),Object.assign(e,e.opts)}ix.VERSION=Hy;const ox=new ix({id:"loaders.gl"});class nx{log(){return()=>{}}info(){return()=>{}}warn(){return()=>{}}error(){return()=>{}}}const ax={fetch:null,mimeType:void 0,nothrow:!1,log:new class{constructor(){Zb(this,"console",void 0),this.console=console}log(...e){return this.console.log.bind(this.console,...e)}info(...e){return this.console.info.bind(this.console,...e)}warn(...e){return this.console.warn.bind(this.console,...e)}error(...e){return this.console.error.bind(this.console,...e)}},CDN:"https://unpkg.com/@loaders.gl",worker:!0,maxConcurrency:3,maxMobileConcurrency:1,reuseWorkers:Hb,_nodeWorkers:!1,_workerType:"",limit:0,_limitMB:0,batchSize:"auto",batchDebounceMs:0,metadata:!1,transforms:[]},lx={throws:"nothrow",dataType:"(no longer used)",uri:"baseUri",method:"fetch.method",headers:"fetch.headers",body:"fetch.body",mode:"fetch.mode",credentials:"fetch.credentials",cache:"fetch.cache",redirect:"fetch.redirect",referrer:"fetch.referrer",referrerPolicy:"fetch.referrerPolicy",integrity:"fetch.integrity",keepalive:"fetch.keepalive",signal:"fetch.signal"};function Ax(){globalThis.loaders=globalThis.loaders||{};const{loaders:e}=globalThis;return e._state=e._state||{},e._state}const hx=()=>{const e=Ax();return e.globalOptions=e.globalOptions||{...ax},e.globalOptions};function cx(e,t,i,s){return i=i||[],function(e,t){dx(e,null,ax,lx,t);for(const i of t){const s=e&&e[i.id]||{},r=i.options&&i.options[i.id]||{},o=i.deprecatedOptions&&i.deprecatedOptions[i.id]||{};dx(s,i.id,r,o,t)}}(e,i=Array.isArray(i)?i:[i]),function(e,t,i){const s={...e.options||{}};(function(e,t){t&&!("baseUri"in e)&&(e.baseUri=t)})(s,i),null===s.log&&(s.log=new nx);return fx(s,hx()),fx(s,t),s}(t,e,s)}function ux(e,t){const i=hx(),s=e||i;return"function"==typeof s.fetch?s.fetch:Py(s.fetch)?e=>ky(e,s):null!=t&&t.fetch?null==t?void 0:t.fetch:ky}function dx(e,t,i,s,r){const o=t||"Top level",n=t?"".concat(t,"."):"";for(const a in e){const l=!t&&Py(e[a]),A="baseUri"===a&&!t,h="workerUrl"===a&&t;if(!(a in i)&&!A&&!h)if(a in s)ox.warn("".concat(o," loader option '").concat(n).concat(a,"' no longer supported, use '").concat(s[a],"'"))();else if(!l){const e=px(a,r);ox.warn("".concat(o," loader option '").concat(n).concat(a,"' not recognized. ").concat(e))()}}}function px(e,t){const i=e.toLowerCase();let s="";for(const r of t)for(const t in r.options){if(e===t)return"Did you mean '".concat(r.id,".").concat(t,"'?");const o=t.toLowerCase();(i.startsWith(o)||o.startsWith(i))&&(s=s||"Did you mean '".concat(r.id,".").concat(t,"'?"))}return s}function fx(e,t){for(const i in t)if(i in t){const s=t[i];Cy(s)&&Cy(e[i])?e[i]={...e[i],...t[i]}:e[i]=t[i]}}function gx(e){var t;if(!e)return!1;Array.isArray(e)&&(e=e[0]);return Array.isArray(null===(t=e)||void 0===t?void 0:t.extensions)}function mx(e){var t,i;let s;return Vb(e,"null loader"),Vb(gx(e),"invalid loader"),Array.isArray(e)&&(s=e[1],e=e[0],e={...e,options:{...e.options,...s}}),(null!==(t=e)&&void 0!==t&&t.parseTextSync||null!==(i=e)&&void 0!==i&&i.parseText)&&(e.text=!0),e.text||(e.binary=!0),e}function _x(){return(()=>{const e=Ax();return e.loaderRegistry=e.loaderRegistry||[],e.loaderRegistry})()}function vx(){return!("object"==typeof process&&"[object process]"===String(process)&&!process.browser)||function(e){if("undefined"!=typeof window&&"object"==typeof window.process&&"renderer"===window.process.type)return!0;if("undefined"!=typeof process&&"object"==typeof process.versions&&Boolean(process.versions.electron))return!0;const t="object"==typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent,i=e||t;return!!(i&&i.indexOf("Electron")>=0)}()}const bx={self:"undefined"!=typeof self&&self,window:"undefined"!=typeof window&&window,global:"undefined"!=typeof global&&global,document:"undefined"!=typeof document&&document,process:"object"==typeof process&&process},yx=bx.window||bx.self||bx.global,xx=bx.process||{},Bx="undefined"!=typeof __VERSION__?__VERSION__:"untranspiled source";vx();class wx{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"sessionStorage";Zb(this,"storage",void 0),Zb(this,"id",void 0),Zb(this,"config",{}),this.storage=function(e){try{const t=window[e],i="__storage_test__";return t.setItem(i,i),t.removeItem(i),t}catch(e){return null}}(i),this.id=e,this.config={},Object.assign(this.config,t),this._loadConfiguration()}getConfiguration(){return this.config}setConfiguration(e){return this.config={},this.updateConfiguration(e)}updateConfiguration(e){if(Object.assign(this.config,e),this.storage){const e=JSON.stringify(this.config);this.storage.setItem(this.id,e)}return this}_loadConfiguration(){let e={};if(this.storage){const t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}}function Px(e,t,i){let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:600;const r=e.src.replace(/\(/g,"%28").replace(/\)/g,"%29");e.width>s&&(i=Math.min(i,s/e.width));const o=e.width*i,n=e.height*i,a=["font-size:1px;","padding:".concat(Math.floor(n/2),"px ").concat(Math.floor(o/2),"px;"),"line-height:".concat(n,"px;"),"background:url(".concat(r,");"),"background-size:".concat(o,"px ").concat(n,"px;"),"color:transparent;"].join("");return["".concat(t," %c+"),a]}let Cx;function Mx(e){return"string"==typeof e?Cx[e.toUpperCase()]||Cx.WHITE:e}function Ex(e,t){if(!e)throw new Error(t||"Assertion failed")}function Fx(){let e;var t,i;if(vx&&"performance"in yx)e=null==yx||null===(t=yx.performance)||void 0===t||null===(i=t.now)||void 0===i?void 0:i.call(t);else if("hrtime"in xx){var s;const t=null==xx||null===(s=xx.hrtime)||void 0===s?void 0:s.call(xx);e=1e3*t[0]+t[1]/1e6}else e=Date.now();return e}!function(e){e[e.BLACK=30]="BLACK",e[e.RED=31]="RED",e[e.GREEN=32]="GREEN",e[e.YELLOW=33]="YELLOW",e[e.BLUE=34]="BLUE",e[e.MAGENTA=35]="MAGENTA",e[e.CYAN=36]="CYAN",e[e.WHITE=37]="WHITE",e[e.BRIGHT_BLACK=90]="BRIGHT_BLACK",e[e.BRIGHT_RED=91]="BRIGHT_RED",e[e.BRIGHT_GREEN=92]="BRIGHT_GREEN",e[e.BRIGHT_YELLOW=93]="BRIGHT_YELLOW",e[e.BRIGHT_BLUE=94]="BRIGHT_BLUE",e[e.BRIGHT_MAGENTA=95]="BRIGHT_MAGENTA",e[e.BRIGHT_CYAN=96]="BRIGHT_CYAN",e[e.BRIGHT_WHITE=97]="BRIGHT_WHITE"}(Cx||(Cx={}));const Ix={debug:vx&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},Dx={enabled:!0,level:0};function Sx(){}const Tx={},Rx={once:!0};class Lx{constructor(){let{id:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{id:""};Zb(this,"id",void 0),Zb(this,"VERSION",Bx),Zb(this,"_startTs",Fx()),Zb(this,"_deltaTs",Fx()),Zb(this,"_storage",void 0),Zb(this,"userData",{}),Zb(this,"LOG_THROTTLE_TIMEOUT",0),this.id=e,this._storage=new wx("__probe-".concat(this.id,"__"),Dx),this.userData={},this.timeStamp("".concat(this.id," started")),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:["constructor"];const i=Object.getPrototypeOf(e),s=Object.getOwnPropertyNames(i);for(const i of s)"function"==typeof e[i]&&(t.find((e=>i===e))||(e[i]=e[i].bind(e)))}(this),Object.seal(this)}set level(e){this.setLevel(e)}get level(){return this.getLevel()}isEnabled(){return this._storage.config.enabled}getLevel(){return this._storage.config.level}getTotal(){return Number((Fx()-this._startTs).toPrecision(10))}getDelta(){return Number((Fx()-this._deltaTs).toPrecision(10))}set priority(e){this.level=e}get priority(){return this.level}getPriority(){return this.level}enable(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this._storage.updateConfiguration({enabled:e}),this}setLevel(e){return this._storage.updateConfiguration({level:e}),this}get(e){return this._storage.config[e]}set(e,t){this._storage.updateConfiguration({[e]:t})}settings(){console.table?console.table(this._storage.config):console.log(this._storage.config)}assert(e,t){Ex(e,t)}warn(e){return this._getLogFunction(0,e,Ix.warn,arguments,Rx)}error(e){return this._getLogFunction(0,e,Ix.error,arguments)}deprecated(e,t){return this.warn("`".concat(e,"` is deprecated and will be removed in a later version. Use `").concat(t,"` instead"))}removed(e,t){return this.error("`".concat(e,"` has been removed. Use `").concat(t,"` instead"))}probe(e,t){return this._getLogFunction(e,t,Ix.log,arguments,{time:!0,once:!0})}log(e,t){return this._getLogFunction(e,t,Ix.debug,arguments)}info(e,t){return this._getLogFunction(e,t,console.info,arguments)}once(e,t){for(var i=arguments.length,s=new Array(i>2?i-2:0),r=2;r{const t=Px(e,i,s);console.log(...t)},e.src=t,Sx}const r=t.nodeName||"";if("img"===r.toLowerCase())return console.log(...Px(t,i,s)),Sx;if("canvas"===r.toLowerCase()){const e=new Image;return e.onload=()=>console.log(...Px(e,i,s)),e.src=t.toDataURL(),Sx}return Sx}({image:s,message:r,scale:o}):function(e){let{image:t,message:i="",scale:s=1}=e,r=null;try{r=module.require("asciify-image")}catch(e){}if(r)return()=>r(t,{fit:"box",width:"".concat(Math.round(80*s),"%")}).then((e=>console.log(e)));return Sx}({image:s,message:r,scale:o}):Sx}time(e,t){return this._getLogFunction(e,t,console.time?console.time:console.info)}timeEnd(e,t){return this._getLogFunction(e,t,console.timeEnd?console.timeEnd:console.info)}timeStamp(e,t){return this._getLogFunction(e,t,console.timeStamp||Sx)}group(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{collapsed:!1};const s=Ox({logLevel:e,message:t,opts:i}),{collapsed:r}=i;return s.method=(r?console.groupCollapsed:console.group)||console.info,this._getLogFunction(s)}groupCollapsed(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.group(e,t,Object.assign({},i,{collapsed:!0}))}groupEnd(e){return this._getLogFunction(e,"",console.groupEnd||Sx)}withGroup(e,t,i){this.group(e,t)();try{i()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&this.getLevel()>=Ux(e)}_getLogFunction(e,t,i,s,r){if(this._shouldLog(e)){r=Ox({logLevel:e,message:t,args:s,opts:r}),Ex(i=i||r.method),r.total=this.getTotal(),r.delta=this.getDelta(),this._deltaTs=Fx();const o=r.tag||r.message;if(r.once){if(Tx[o])return Sx;Tx[o]=Fx()}return t=function(e,t,i){if("string"==typeof t){const s=i.time?function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8;const i=Math.max(t-e.length,0);return"".concat(" ".repeat(i)).concat(e)}(function(e){let t;return t=e<10?"".concat(e.toFixed(2),"ms"):e<100?"".concat(e.toFixed(1),"ms"):e<1e3?"".concat(e.toFixed(0),"ms"):"".concat((e/1e3).toFixed(2),"s"),t}(i.total)):"";t=i.time?"".concat(e,": ").concat(s," ").concat(t):"".concat(e,": ").concat(t),t=function(e,t,i){return vx||"string"!=typeof e||(t&&(t=Mx(t),e="[".concat(t,"m").concat(e,"")),i&&(t=Mx(i),e="[".concat(i+10,"m").concat(e,""))),e}(t,i.color,i.background)}return t}(this.id,r.message,r),i.bind(console,t,...r.args)}return Sx}}function Ux(e){if(!e)return 0;let t;switch(typeof e){case"number":t=e;break;case"object":t=e.logLevel||e.priority||0;break;default:return 0}return Ex(Number.isFinite(t)&&t>=0),t}function Ox(e){const{logLevel:t,message:i}=e;e.logLevel=Ux(t);const s=e.args?Array.from(e.args):[];for(;s.length&&s.shift()!==i;);switch(typeof t){case"string":case"function":void 0!==i&&s.unshift(i),e.message=t;break;case"object":Object.assign(e,t)}"function"==typeof e.message&&(e.message=e.message());const r=typeof e.message;return Ex("string"===r||"object"===r),Object.assign(e,{args:s},e.opts)}function kx(e){for(const t in e)for(const i in e[t])return i||"untitled";return"empty"}Zb(Lx,"VERSION",Bx);const Nx=new Lx({id:"loaders.gl"}),Qx=/\.([^.]+)$/;function Vx(e,t=[],i,s){if(!Hx(e))return null;if(t&&!Array.isArray(t))return mx(t);let r=[];t&&(r=r.concat(t)),null!=i&&i.ignoreRegisteredLoaders||r.push(..._x()),function(e){for(const t of e)mx(t)}(r);const o=function(e,t,i,s){const{url:r,type:o}=Ly(e),n=r||(null==s?void 0:s.url);let a=null,l="";null!=i&&i.mimeType&&(a=Gx(t,null==i?void 0:i.mimeType),l="match forced by supplied MIME type ".concat(null==i?void 0:i.mimeType));var A;a=a||function(e,t){const i=t&&Qx.exec(t),s=i&&i[1];return s?function(e,t){t=t.toLowerCase();for(const i of e)for(const e of i.extensions)if(e.toLowerCase()===t)return i;return null}(e,s):null}(t,n),l=l||(a?"matched url ".concat(n):""),a=a||Gx(t,o),l=l||(a?"matched MIME type ".concat(o):""),a=a||function(e,t){if(!t)return null;for(const i of e)if("string"==typeof t){if(zx(t,i))return i}else if(ArrayBuffer.isView(t)){if(Wx(t.buffer,t.byteOffset,i))return i}else if(t instanceof ArrayBuffer){if(Wx(t,0,i))return i}return null}(t,e),l=l||(a?"matched initial data ".concat(Kx(e)):""),a=a||Gx(t,null==i?void 0:i.fallbackMimeType),l=l||(a?"matched fallback MIME type ".concat(o):""),l&&Nx.log(1,"selectLoader selected ".concat(null===(A=a)||void 0===A?void 0:A.name,": ").concat(l,"."));return a}(e,r,i,s);if(!(o||null!=i&&i.nothrow))throw new Error(jx(e));return o}function Hx(e){return!(e instanceof Response&&204===e.status)}function jx(e){const{url:t,type:i}=Ly(e);let s="No valid loader found (";s+=t?"".concat(function(e){const t=e&&e.lastIndexOf("/");return t>=0?e.substr(t+1):""}(t),", "):"no url provided, ",s+="MIME type: ".concat(i?'"'.concat(i,'"'):"not provided",", ");const r=e?Kx(e):"";return s+=r?' first bytes: "'.concat(r,'"'):"first bytes: not available",s+=")",s}function Gx(e,t){for(const i of e){if(i.mimeTypes&&i.mimeTypes.includes(t))return i;if(t==="application/x.".concat(i.id))return i}return null}function zx(e,t){if(t.testText)return t.testText(e);return(Array.isArray(t.tests)?t.tests:[t.tests]).some((t=>e.startsWith(t)))}function Wx(e,t,i){return(Array.isArray(i.tests)?i.tests:[i.tests]).some((s=>function(e,t,i,s){if(s instanceof ArrayBuffer)return function(e,t,i){if(i=i||e.byteLength,e.byteLength60?"".concat(t.slice(0,60),"..."):t}catch(e){}return t}(e);throw new Error(t)}}(i),t.binary?await i.arrayBuffer():await i.text()}if(Fy(e)&&(e=Zx(e,i)),(r=e)&&"function"==typeof r[Symbol.iterator]||(e=>e&&"function"==typeof e[Symbol.asyncIterator])(e))return xy(e);var r;throw new Error(qx)}async function eB(e,t,i,s){Gb(!s||"object"==typeof s),!t||Array.isArray(t)||gx(t)||(s=void 0,i=t,t=void 0),e=await e,i=i||{};const{url:r}=Ly(e),o=function(e,t){if(!t&&e&&!Array.isArray(e))return e;let i;if(e&&(i=Array.isArray(e)?e:[e]),t&&t.loaders){const e=Array.isArray(t.loaders)?t.loaders:[t.loaders];i=i?[...i,...e]:e}return i&&i.length?i:null}(t,s),n=await async function(e,t=[],i,s){if(!Hx(e))return null;let r=Vx(e,t,{...i,nothrow:!0},s);if(r)return r;if(Ey(e)&&(r=Vx(e=await e.slice(0,10).arrayBuffer(),t,i,s)),!(r||null!=i&&i.nothrow))throw new Error(jx(e));return r}(e,o,i);return n?(s=function(e,t,i=null){if(i)return i;const s={fetch:ux(t,e),...e};return Array.isArray(s.loaders)||(s.loaders=null),s}({url:r,parse:eB,loaders:o},i=cx(i,n,o,r),s),await async function(e,t,i,s){if(function(e,t="3.2.6"){Gb(e,"no worker provided");const i=e.version}(e),My(t)){const e=t,{ok:i,redirected:r,status:o,statusText:n,type:a,url:l}=e,A=Object.fromEntries(e.headers.entries());s.response={headers:A,ok:i,redirected:r,status:o,statusText:n,type:a,url:l}}if(t=await $x(t,e,i),e.parseTextSync&&"string"==typeof t)return i.dataType="text",e.parseTextSync(t,i,s,e);if(function(e,t){return!!Ay.isSupported()&&!!(Kb||null!=t&&t._nodeWorkers)&&e.worker&&(null==t?void 0:t.worker)}(e,i))return await dy(e,t,i,s,eB);if(e.parseText&&"string"==typeof t)return await e.parseText(t,i,s,e);if(e.parse)return await e.parse(t,i,s,e);throw Gb(!e.parseSync),new Error("".concat(e.id," loader - no parser found and worker is disabled"))}(n,e,i,s)):null}const tB="https://unpkg.com/@loaders.gl/textures@".concat("3.2.6","/dist/libs/basis_encoder.wasm"),iB="https://unpkg.com/@loaders.gl/textures@".concat("3.2.6","/dist/libs/basis_encoder.js");let sB,rB;async function oB(e){const t=e.modules||{};return t.basis?t.basis:(sB=sB||async function(e){let t=null,i=null;return[t,i]=await Promise.all([await uy("basis_transcoder.js","textures",e),await uy("basis_transcoder.wasm","textures",e)]),t=t||globalThis.BASIS,await function(e,t){const i={};t&&(i.wasmBinary=t);return new Promise((t=>{e(i).then((e=>{const{BasisFile:i,initializeBasis:s}=e;s(),t({BasisFile:i})}))}))}(t,i)}(e),await sB)}async function nB(e){const t=e.modules||{};return t.basisEncoder?t.basisEncoder:(rB=rB||async function(e){let t=null,i=null;return[t,i]=await Promise.all([await uy(iB,"textures",e),await uy(tB,"textures",e)]),t=t||globalThis.BASIS,await function(e,t){const i={};t&&(i.wasmBinary=t);return new Promise((t=>{e(i).then((e=>{const{BasisFile:i,KTX2File:s,initializeBasis:r,BasisEncoder:o}=e;r(),t({BasisFile:i,KTX2File:s,BasisEncoder:o})}))}))}(t,i)}(e),await rB)}const aB=33776,lB=33779,AB=35840,hB=35842,cB=36196,uB=37808,dB=["","WEBKIT_","MOZ_"],pB={WEBGL_compressed_texture_s3tc:"dxt",WEBGL_compressed_texture_s3tc_srgb:"dxt-srgb",WEBGL_compressed_texture_etc1:"etc1",WEBGL_compressed_texture_etc:"etc2",WEBGL_compressed_texture_pvrtc:"pvrtc",WEBGL_compressed_texture_atc:"atc",WEBGL_compressed_texture_astc:"astc",EXT_texture_compression_rgtc:"rgtc"};let fB=null;function gB(e){if(!fB){e=e||function(){try{return document.createElement("canvas").getContext("webgl")}catch(e){return null}}()||void 0,fB=new Set;for(const t of dB)for(const i in pB)if(e&&e.getExtension("".concat(t).concat(i))){const e=pB[i];fB.add(e)}}return fB}var mB,_B,vB,bB,yB,xB,BB,wB,PB;(PB=mB||(mB={}))[PB.NONE=0]="NONE",PB[PB.BASISLZ=1]="BASISLZ",PB[PB.ZSTD=2]="ZSTD",PB[PB.ZLIB=3]="ZLIB",function(e){e[e.BASICFORMAT=0]="BASICFORMAT"}(_B||(_B={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.ETC1S=163]="ETC1S",e[e.UASTC=166]="UASTC"}(vB||(vB={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.SRGB=1]="SRGB"}(bB||(bB={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.LINEAR=1]="LINEAR",e[e.SRGB=2]="SRGB",e[e.ITU=3]="ITU",e[e.NTSC=4]="NTSC",e[e.SLOG=5]="SLOG",e[e.SLOG2=6]="SLOG2"}(yB||(yB={})),function(e){e[e.ALPHA_STRAIGHT=0]="ALPHA_STRAIGHT",e[e.ALPHA_PREMULTIPLIED=1]="ALPHA_PREMULTIPLIED"}(xB||(xB={})),function(e){e[e.RGB=0]="RGB",e[e.RRR=3]="RRR",e[e.GGG=4]="GGG",e[e.AAA=15]="AAA"}(BB||(BB={})),function(e){e[e.RGB=0]="RGB",e[e.RGBA=3]="RGBA",e[e.RRR=4]="RRR",e[e.RRRG=5]="RRRG"}(wB||(wB={}));const CB=[171,75,84,88,32,50,48,187,13,10,26,10];const MB={etc1:{basisFormat:0,compressed:!0,format:cB},etc2:{basisFormat:1,compressed:!0},bc1:{basisFormat:2,compressed:!0,format:aB},bc3:{basisFormat:3,compressed:!0,format:lB},bc4:{basisFormat:4,compressed:!0},bc5:{basisFormat:5,compressed:!0},"bc7-m6-opaque-only":{basisFormat:6,compressed:!0},"bc7-m5":{basisFormat:7,compressed:!0},"pvrtc1-4-rgb":{basisFormat:8,compressed:!0,format:AB},"pvrtc1-4-rgba":{basisFormat:9,compressed:!0,format:hB},"astc-4x4":{basisFormat:10,compressed:!0,format:uB},"atc-rgb":{basisFormat:11,compressed:!0},"atc-rgba-interpolated-alpha":{basisFormat:12,compressed:!0},rgba32:{basisFormat:13,compressed:!1},rgb565:{basisFormat:14,compressed:!1},bgr565:{basisFormat:15,compressed:!1},rgba4444:{basisFormat:16,compressed:!1}};function EB(e,t,i){const s=new e(new Uint8Array(t));try{if(!s.startTranscoding())throw new Error("Failed to start basis transcoding");const e=s.getNumImages(),t=[];for(let r=0;r{try{i.onload=()=>t(i),i.onerror=t=>s(new Error("Could not load image ".concat(e,": ").concat(t)))}catch(e){s(e)}}))}(o||s,t)}finally{o&&r.revokeObjectURL(o)}}const WB={};let KB=!0;async function XB(e,t,i){let s;if(jB(i)){s=await zB(e,t,i)}else s=GB(e,i);const r=t&&t.imagebitmap;return await async function(e,t=null){!function(e){for(const t in e||WB)return!1;return!0}(t)&&KB||(t=null);if(t)try{return await createImageBitmap(e,t)}catch(e){console.warn(e),KB=!1}return await createImageBitmap(e)}(s,r)}function JB(e){const t=YB(e);return function(e){const t=YB(e);if(!(t.byteLength>=24&&2303741511===t.getUint32(0,false)))return null;return{mimeType:"image/png",width:t.getUint32(16,false),height:t.getUint32(20,false)}}(t)||function(e){const t=YB(e);if(!(t.byteLength>=3&&65496===t.getUint16(0,false)&&255===t.getUint8(2)))return null;const{tableMarkers:i,sofMarkers:s}=function(){const e=new Set([65499,65476,65484,65501,65534]);for(let t=65504;t<65520;++t)e.add(t);const t=new Set([65472,65473,65474,65475,65477,65478,65479,65481,65482,65483,65485,65486,65487,65502]);return{tableMarkers:e,sofMarkers:t}}();let r=2;for(;r+9=10&&1195984440===t.getUint32(0,false)))return null;return{mimeType:"image/gif",width:t.getUint16(6,true),height:t.getUint16(8,true)}}(t)||function(e){const t=YB(e);if(!(t.byteLength>=14&&16973===t.getUint16(0,false)&&t.getUint32(2,true)===t.byteLength))return null;return{mimeType:"image/bmp",width:t.getUint32(18,true),height:t.getUint32(22,true)}}(t)}function YB(e){if(e instanceof DataView)return e;if(ArrayBuffer.isView(e))return new DataView(e.buffer);if(e instanceof ArrayBuffer)return new DataView(e);throw new Error("toDataView")}const ZB={id:"image",module:"images",name:"Images",version:"3.2.6",mimeTypes:["image/png","image/jpeg","image/gif","image/webp","image/bmp","image/vnd.microsoft.icon","image/svg+xml"],extensions:["png","jpg","jpeg","gif","webp","bmp","ico","svg"],parse:async function(e,t,i){const s=((t=t||{}).image||{}).type||"auto",{url:r}=i||{};let o;switch(function(e){switch(e){case"auto":case"data":return function(){if(OB)return"imagebitmap";if(UB)return"image";if(NB)return"data";throw new Error("Install '@loaders.gl/polyfills' to parse images under Node.js")}();default:return function(e){switch(e){case"auto":return OB||UB||NB;case"imagebitmap":return OB;case"image":return UB;case"data":return NB;default:throw new Error("@loaders.gl/images: image ".concat(e," not supported in this environment"))}}(e),e}}(s)){case"imagebitmap":o=await XB(e,t,r);break;case"image":o=await zB(e,t,r);break;case"data":o=await async function(e,t){const{mimeType:i}=JB(e)||{},s=globalThis._parseImageNode;return Vb(s),await s(e,i)}(e);break;default:Vb(!1)}return"data"===s&&(o=function(e){switch(QB(e)){case"data":return e;case"image":case"imagebitmap":const t=document.createElement("canvas"),i=t.getContext("2d");if(!i)throw new Error("getImageData");return t.width=e.width,t.height=e.height,i.drawImage(e,0,0),i.getImageData(0,0,e.width,e.height);default:throw new Error("getImageData")}}(o)),o},tests:[e=>Boolean(JB(new DataView(e)))],options:{image:{type:"auto",decode:!0}}},qB=["image/png","image/jpeg","image/gif"],$B={};function ew(e){return void 0===$B[e]&&($B[e]=function(e){switch(e){case"image/webp":return function(){if(!Hb)return!1;try{return 0===document.createElement("canvas").toDataURL("image/webp").indexOf("data:image/webp")}catch{return!1}}();case"image/svg":return Hb;default:if(!Hb){const{_parseImageNode:t}=globalThis;return Boolean(t)&&qB.includes(e)}return!0}}(e)),$B[e]}function tw(e,t){if(!e)throw new Error(t||"assert failed: gltf")}function iw(e,t){if(e.startsWith("data:")||e.startsWith("http:")||e.startsWith("https:"))return e;const i=t.baseUri||t.uri;if(!i)throw new Error("'baseUri' must be provided to resolve relative url ".concat(e));return i.substr(0,i.lastIndexOf("/")+1)+e}const sw=["SCALAR","VEC2","VEC3","VEC4"],rw=[[Int8Array,5120],[Uint8Array,5121],[Int16Array,5122],[Uint16Array,5123],[Uint32Array,5125],[Float32Array,5126],[Float64Array,5130]],ow=new Map(rw),nw={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},aw={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},lw={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array};function Aw(e){return sw[e-1]||sw[0]}function hw(e){const t=ow.get(e.constructor);if(!t)throw new Error("Illegal typed array");return t}function cw(e,t){const i=lw[e.componentType],s=nw[e.type],r=aw[e.componentType],o=e.count*s,n=e.count*s*r;return tw(n>=0&&n<=t.byteLength),{ArrayType:i,length:o,byteLength:n}}const uw={asset:{version:"2.0",generator:"loaders.gl"},buffers:[]};class dw{constructor(e){Zb(this,"gltf",void 0),Zb(this,"sourceBuffers",void 0),Zb(this,"byteLength",void 0),this.gltf=e||{json:{...uw},buffers:[]},this.sourceBuffers=[],this.byteLength=0,this.gltf.buffers&&this.gltf.buffers[0]&&(this.byteLength=this.gltf.buffers[0].byteLength,this.sourceBuffers=[this.gltf.buffers[0]])}get json(){return this.gltf.json}getApplicationData(e){return this.json[e]}getExtraData(e){return(this.json.extras||{})[e]}getExtension(e){const t=this.getUsedExtensions().find((t=>t===e)),i=this.json.extensions||{};return t?i[e]||!0:null}getRequiredExtension(e){const t=this.getRequiredExtensions().find((t=>t===e));return t?this.getExtension(e):null}getRequiredExtensions(){return this.json.extensionsRequired||[]}getUsedExtensions(){return this.json.extensionsUsed||[]}getObjectExtension(e,t){return(e.extensions||{})[t]}getScene(e){return this.getObject("scenes",e)}getNode(e){return this.getObject("nodes",e)}getSkin(e){return this.getObject("skins",e)}getMesh(e){return this.getObject("meshes",e)}getMaterial(e){return this.getObject("materials",e)}getAccessor(e){return this.getObject("accessors",e)}getTexture(e){return this.getObject("textures",e)}getSampler(e){return this.getObject("samplers",e)}getImage(e){return this.getObject("images",e)}getBufferView(e){return this.getObject("bufferViews",e)}getBuffer(e){return this.getObject("buffers",e)}getObject(e,t){if("object"==typeof t)return t;const i=this.json[e]&&this.json[e][t];if(!i)throw new Error("glTF file error: Could not find ".concat(e,"[").concat(t,"]"));return i}getTypedArrayForBufferView(e){const t=(e=this.getBufferView(e)).buffer,i=this.gltf.buffers[t];tw(i);const s=(e.byteOffset||0)+i.byteOffset;return new Uint8Array(i.arrayBuffer,s,e.byteLength)}getTypedArrayForAccessor(e){e=this.getAccessor(e);const t=this.getBufferView(e.bufferView),i=this.getBuffer(t.buffer).data,{ArrayType:s,length:r}=cw(e,t);return new s(i,t.byteOffset+e.byteOffset,r)}getTypedArrayForImageData(e){e=this.getAccessor(e);const t=this.getBufferView(e.bufferView),i=this.getBuffer(t.buffer).data,s=t.byteOffset||0;return new Uint8Array(i,s,t.byteLength)}addApplicationData(e,t){return this.json[e]=t,this}addExtraData(e,t){return this.json.extras=this.json.extras||{},this.json.extras[e]=t,this}addObjectExtension(e,t,i){return e.extensions=e.extensions||{},e.extensions[t]=i,this.registerUsedExtension(t),this}setObjectExtension(e,t,i){(e.extensions||{})[t]=i}removeObjectExtension(e,t){const i=e.extensions||{},s=i[t];return delete i[t],s}addExtension(e,t={}){return tw(t),this.json.extensions=this.json.extensions||{},this.json.extensions[e]=t,this.registerUsedExtension(e),t}addRequiredExtension(e,t={}){return tw(t),this.addExtension(e,t),this.registerRequiredExtension(e),t}registerUsedExtension(e){this.json.extensionsUsed=this.json.extensionsUsed||[],this.json.extensionsUsed.find((t=>t===e))||this.json.extensionsUsed.push(e)}registerRequiredExtension(e){this.registerUsedExtension(e),this.json.extensionsRequired=this.json.extensionsRequired||[],this.json.extensionsRequired.find((t=>t===e))||this.json.extensionsRequired.push(e)}removeExtension(e){this.json.extensionsRequired&&this._removeStringFromArray(this.json.extensionsRequired,e),this.json.extensionsUsed&&this._removeStringFromArray(this.json.extensionsUsed,e),this.json.extensions&&delete this.json.extensions[e]}setDefaultScene(e){this.json.scene=e}addScene(e){const{nodeIndices:t}=e;return this.json.scenes=this.json.scenes||[],this.json.scenes.push({nodes:t}),this.json.scenes.length-1}addNode(e){const{meshIndex:t,matrix:i}=e;this.json.nodes=this.json.nodes||[];const s={mesh:t};return i&&(s.matrix=i),this.json.nodes.push(s),this.json.nodes.length-1}addMesh(e){const{attributes:t,indices:i,material:s,mode:r=4}=e,o={primitives:[{attributes:this._addAttributes(t),mode:r}]};if(i){const e=this._addIndices(i);o.primitives[0].indices=e}return Number.isFinite(s)&&(o.primitives[0].material=s),this.json.meshes=this.json.meshes||[],this.json.meshes.push(o),this.json.meshes.length-1}addPointCloud(e){const t={primitives:[{attributes:this._addAttributes(e),mode:0}]};return this.json.meshes=this.json.meshes||[],this.json.meshes.push(t),this.json.meshes.length-1}addImage(e,t){const i=JB(e),s=t||(null==i?void 0:i.mimeType),r={bufferView:this.addBufferView(e),mimeType:s};return this.json.images=this.json.images||[],this.json.images.push(r),this.json.images.length-1}addBufferView(e){const t=e.byteLength;tw(Number.isFinite(t)),this.sourceBuffers=this.sourceBuffers||[],this.sourceBuffers.push(e);const i={buffer:0,byteOffset:this.byteLength,byteLength:t};return this.byteLength+=by(t,4),this.json.bufferViews=this.json.bufferViews||[],this.json.bufferViews.push(i),this.json.bufferViews.length-1}addAccessor(e,t){const i={bufferView:e,type:Aw(t.size),componentType:t.componentType,count:t.count,max:t.max,min:t.min};return this.json.accessors=this.json.accessors||[],this.json.accessors.push(i),this.json.accessors.length-1}addBinaryBuffer(e,t={size:3}){const i=this.addBufferView(e);let s={min:t.min,max:t.max};s.min&&s.max||(s=this._getAccessorMinMax(e,t.size));const r={size:t.size,componentType:hw(e),count:Math.round(e.length/t.size),min:s.min,max:s.max};return this.addAccessor(i,Object.assign(r,t))}addTexture(e){const{imageIndex:t}=e,i={source:t};return this.json.textures=this.json.textures||[],this.json.textures.push(i),this.json.textures.length-1}addMaterial(e){return this.json.materials=this.json.materials||[],this.json.materials.push(e),this.json.materials.length-1}createBinaryChunk(){var e,t;this.gltf.buffers=[];const i=this.byteLength,s=new ArrayBuffer(i),r=new Uint8Array(s);let o=0;for(const e of this.sourceBuffers||[])o=yy(e,r,o);null!==(e=this.json)&&void 0!==e&&null!==(t=e.buffers)&&void 0!==t&&t[0]?this.json.buffers[0].byteLength=i:this.json.buffers=[{byteLength:i}],this.gltf.binary=s,this.sourceBuffers=[s]}_removeStringFromArray(e,t){let i=!0;for(;i;){const s=e.indexOf(t);s>-1?e.splice(s,1):i=!1}}_addAttributes(e={}){const t={};for(const i in e){const s=e[i],r=this._getGltfAttributeName(i),o=this.addBinaryBuffer(s.value,s);t[r]=o}return t}_addIndices(e){return this.addBinaryBuffer(e,{size:1})}_getGltfAttributeName(e){switch(e.toLowerCase()){case"position":case"positions":case"vertices":return"POSITION";case"normal":case"normals":return"NORMAL";case"color":case"colors":return"COLOR_0";case"texcoord":case"texcoords":return"TEXCOORD_0";default:return e}}_getAccessorMinMax(e,t){const i={min:null,max:null};if(e.length96?s-71:s>64?s-65:s>47?s+4:s>46?63:62}let i=0;for(let s=0;st[e.name]));return new Mw(i,this.metadata)}selectAt(...e){const t=e.map((e=>this.fields[e])).filter(Boolean);return new Mw(t,this.metadata)}assign(e){let t,i=this.metadata;if(e instanceof Mw){const s=e;t=s.fields,i=Ew(Ew(new Map,this.metadata),s.metadata)}else t=e;const s=Object.create(null);for(const e of this.fields)s[e.name]=e;for(const e of t)s[e.name]=e;const r=Object.values(s);return new Mw(r,i)}}function Ew(e,t){return new Map([...e||new Map,...t||new Map])}class Fw{constructor(e,t,i=!1,s=new Map){Zb(this,"name",void 0),Zb(this,"type",void 0),Zb(this,"nullable",void 0),Zb(this,"metadata",void 0),this.name=e,this.type=t,this.nullable=i,this.metadata=s}get typeId(){return this.type&&this.type.typeId}clone(){return new Fw(this.name,this.type,this.nullable,this.metadata)}compareTo(e){return this.name===e.name&&this.type===e.type&&this.nullable===e.nullable&&this.metadata===e.metadata}toString(){return"".concat(this.type).concat(this.nullable?", nullable":"").concat(this.metadata?", metadata: ".concat(this.metadata):"")}}let Iw,Dw,Sw,Tw;!function(e){e[e.NONE=0]="NONE",e[e.Null=1]="Null",e[e.Int=2]="Int",e[e.Float=3]="Float",e[e.Binary=4]="Binary",e[e.Utf8=5]="Utf8",e[e.Bool=6]="Bool",e[e.Decimal=7]="Decimal",e[e.Date=8]="Date",e[e.Time=9]="Time",e[e.Timestamp=10]="Timestamp",e[e.Interval=11]="Interval",e[e.List=12]="List",e[e.Struct=13]="Struct",e[e.Union=14]="Union",e[e.FixedSizeBinary=15]="FixedSizeBinary",e[e.FixedSizeList=16]="FixedSizeList",e[e.Map=17]="Map",e[e.Dictionary=-1]="Dictionary",e[e.Int8=-2]="Int8",e[e.Int16=-3]="Int16",e[e.Int32=-4]="Int32",e[e.Int64=-5]="Int64",e[e.Uint8=-6]="Uint8",e[e.Uint16=-7]="Uint16",e[e.Uint32=-8]="Uint32",e[e.Uint64=-9]="Uint64",e[e.Float16=-10]="Float16",e[e.Float32=-11]="Float32",e[e.Float64=-12]="Float64",e[e.DateDay=-13]="DateDay",e[e.DateMillisecond=-14]="DateMillisecond",e[e.TimestampSecond=-15]="TimestampSecond",e[e.TimestampMillisecond=-16]="TimestampMillisecond",e[e.TimestampMicrosecond=-17]="TimestampMicrosecond",e[e.TimestampNanosecond=-18]="TimestampNanosecond",e[e.TimeSecond=-19]="TimeSecond",e[e.TimeMillisecond=-20]="TimeMillisecond",e[e.TimeMicrosecond=-21]="TimeMicrosecond",e[e.TimeNanosecond=-22]="TimeNanosecond",e[e.DenseUnion=-23]="DenseUnion",e[e.SparseUnion=-24]="SparseUnion",e[e.IntervalDayTime=-25]="IntervalDayTime",e[e.IntervalYearMonth=-26]="IntervalYearMonth"}(Iw||(Iw={}));class Rw{static isNull(e){return e&&e.typeId===Iw.Null}static isInt(e){return e&&e.typeId===Iw.Int}static isFloat(e){return e&&e.typeId===Iw.Float}static isBinary(e){return e&&e.typeId===Iw.Binary}static isUtf8(e){return e&&e.typeId===Iw.Utf8}static isBool(e){return e&&e.typeId===Iw.Bool}static isDecimal(e){return e&&e.typeId===Iw.Decimal}static isDate(e){return e&&e.typeId===Iw.Date}static isTime(e){return e&&e.typeId===Iw.Time}static isTimestamp(e){return e&&e.typeId===Iw.Timestamp}static isInterval(e){return e&&e.typeId===Iw.Interval}static isList(e){return e&&e.typeId===Iw.List}static isStruct(e){return e&&e.typeId===Iw.Struct}static isUnion(e){return e&&e.typeId===Iw.Union}static isFixedSizeBinary(e){return e&&e.typeId===Iw.FixedSizeBinary}static isFixedSizeList(e){return e&&e.typeId===Iw.FixedSizeList}static isMap(e){return e&&e.typeId===Iw.Map}static isDictionary(e){return e&&e.typeId===Iw.Dictionary}get typeId(){return Iw.NONE}compareTo(e){return this===e}}Dw=Symbol.toStringTag;class Lw extends Rw{constructor(e,t){super(),Zb(this,"isSigned",void 0),Zb(this,"bitWidth",void 0),this.isSigned=e,this.bitWidth=t}get typeId(){return Iw.Int}get[Dw](){return"Int"}toString(){return"".concat(this.isSigned?"I":"Ui","nt").concat(this.bitWidth)}}class Uw extends Lw{constructor(){super(!0,8)}}class Ow extends Lw{constructor(){super(!0,16)}}class kw extends Lw{constructor(){super(!0,32)}}class Nw extends Lw{constructor(){super(!1,8)}}class Qw extends Lw{constructor(){super(!1,16)}}class Vw extends Lw{constructor(){super(!1,32)}}const Hw=32,jw=64;Sw=Symbol.toStringTag;class Gw extends Rw{constructor(e){super(),Zb(this,"precision",void 0),this.precision=e}get typeId(){return Iw.Float}get[Sw](){return"Float"}toString(){return"Float".concat(this.precision)}}class zw extends Gw{constructor(){super(Hw)}}class Ww extends Gw{constructor(){super(jw)}}Tw=Symbol.toStringTag;class Kw extends Rw{constructor(e,t){super(),Zb(this,"listSize",void 0),Zb(this,"children",void 0),this.listSize=e,this.children=[t]}get typeId(){return Iw.FixedSizeList}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get[Tw](){return"FixedSizeList"}toString(){return"FixedSizeList[".concat(this.listSize,"]<").concat(this.valueType,">")}}function Xw(e,t,i){const s=function(e){switch(e.constructor){case Int8Array:return new Uw;case Uint8Array:return new Nw;case Int16Array:return new Ow;case Uint16Array:return new Qw;case Int32Array:return new kw;case Uint32Array:return new Vw;case Float32Array:return new zw;case Float64Array:return new Ww;default:throw new Error("array type not supported")}}(t.value),r=i||function(e){const t=new Map;"byteOffset"in e&&t.set("byteOffset",e.byteOffset.toString(10));"byteStride"in e&&t.set("byteStride",e.byteStride.toString(10));"normalized"in e&&t.set("normalized",e.normalized.toString());return t}(t);return new Fw(e,new Kw(t.size,new Fw("value",s)),!1,r)}function Jw(e,t,i){return Xw(e,t,i?Yw(i.metadata):void 0)}function Yw(e){const t=new Map;for(const i in e)t.set("".concat(i,".string"),JSON.stringify(e[i]));return t}const Zw={POSITION:"POSITION",NORMAL:"NORMAL",COLOR:"COLOR_0",TEX_COORD:"TEXCOORD_0"},qw={1:Int8Array,2:Uint8Array,3:Int16Array,4:Uint16Array,5:Int32Array,6:Uint32Array,9:Float32Array};class $w{constructor(e){Zb(this,"draco",void 0),Zb(this,"decoder",void 0),Zb(this,"metadataQuerier",void 0),this.draco=e,this.decoder=new this.draco.Decoder,this.metadataQuerier=new this.draco.MetadataQuerier}destroy(){this.draco.destroy(this.decoder),this.draco.destroy(this.metadataQuerier)}parseSync(e,t={}){const i=new this.draco.DecoderBuffer;i.Init(new Int8Array(e),e.byteLength),this._disableAttributeTransforms(t);const s=this.decoder.GetEncodedGeometryType(i),r=s===this.draco.TRIANGULAR_MESH?new this.draco.Mesh:new this.draco.PointCloud;try{let e;switch(s){case this.draco.TRIANGULAR_MESH:e=this.decoder.DecodeBufferToMesh(i,r);break;case this.draco.POINT_CLOUD:e=this.decoder.DecodeBufferToPointCloud(i,r);break;default:throw new Error("DRACO: Unknown geometry type.")}if(!e.ok()||!r.ptr){const t="DRACO decompression failed: ".concat(e.error_msg());throw new Error(t)}const o=this._getDracoLoaderData(r,s,t),n=this._getMeshData(r,o,t),a=function(e){let t=1/0,i=1/0,s=1/0,r=-1/0,o=-1/0,n=-1/0;const a=e.POSITION?e.POSITION.value:[],l=a&&a.length;for(let e=0;er?l:r,o=A>o?A:o,n=h>n?h:n}return[[t,i,s],[r,o,n]]}(n.attributes),l=function(e,t,i){const s=Yw(t.metadata),r=[],o=function(e){const t={};for(const i in e){const s=e[i];t[s.name||"undefined"]=s}return t}(t.attributes);for(const t in e){const i=Jw(t,e[t],o[t]);r.push(i)}if(i){const e=Jw("indices",i);r.push(e)}return new Mw(r,s)}(n.attributes,o,n.indices);return{loader:"draco",loaderData:o,header:{vertexCount:r.num_points(),boundingBox:a},...n,schema:l}}finally{this.draco.destroy(i),r&&this.draco.destroy(r)}}_getDracoLoaderData(e,t,i){const s=this._getTopLevelMetadata(e),r=this._getDracoAttributes(e,i);return{geometry_type:t,num_attributes:e.num_attributes(),num_points:e.num_points(),num_faces:e instanceof this.draco.Mesh?e.num_faces():0,metadata:s,attributes:r}}_getDracoAttributes(e,t){const i={};for(let s=0;sthis.decoder[e])).includes(s)){const t=new this.draco.AttributeQuantizationTransform;try{if(t.InitFromAttribute(e))return{quantization_bits:t.quantization_bits(),range:t.range(),min_values:new Float32Array([1,2,3]).map((e=>t.min_value(e)))}}finally{this.draco.destroy(t)}}return null}_getOctahedronTransform(e,t){const{octahedronAttributes:i=[]}=t,s=e.attribute_type();if(i.map((e=>this.decoder[e])).includes(s)){const t=new this.draco.AttributeQuantizationTransform;try{if(t.InitFromAttribute(e))return{quantization_bits:t.quantization_bits()}}finally{this.draco.destroy(t)}}return null}}const eP="https://www.gstatic.com/draco/versioned/decoders/".concat("1.4.1","/draco_decoder.js"),tP="https://www.gstatic.com/draco/versioned/decoders/".concat("1.4.1","/draco_wasm_wrapper.js"),iP="https://www.gstatic.com/draco/versioned/decoders/".concat("1.4.1","/draco_decoder.wasm");let sP;async function rP(e){const t=e.modules||{};return sP=t.draco3d?sP||t.draco3d.createDecoderModule({}).then((e=>({draco:e}))):sP||async function(e){let t,i;if("js"===(e.draco&&e.draco.decoderType))t=await uy(eP,"draco",e);else[t,i]=await Promise.all([await uy(tP,"draco",e),await uy(iP,"draco",e)]);return t=t||globalThis.DracoDecoderModule,await function(e,t){const i={};t&&(i.wasmBinary=t);return new Promise((t=>{e({...i,onModuleLoaded:e=>t({draco:e})})}))}(t,i)}(e),await sP}const oP={...Cw,parse:async function(e,t){const{draco:i}=await rP(t),s=new $w(i);try{return s.parseSync(e,null==t?void 0:t.draco)}finally{s.destroy()}}};function nP(e){const{buffer:t,size:i,count:s}=function(e){let t=e,i=1,s=0;e&&e.value&&(t=e.value,i=e.size||1);t&&(ArrayBuffer.isView(t)||(t=function(e,t,i=!1){if(!e)return null;if(Array.isArray(e))return new t(e);if(i&&!(e instanceof t))return new t(e);return e}(t,Float32Array)),s=t.length/i);return{buffer:t,size:i,count:s}}(e);return{value:t,size:i,byteOffset:0,count:s,type:Aw(i),componentType:hw(t)}}async function aP(e,t,i,s){const r=e.getObjectExtension(t,"KHR_draco_mesh_compression");if(!r)return;const o=e.getTypedArrayForBufferView(r.bufferView),n=vy(o.buffer,o.byteOffset),{parse:a}=s,l={...i};delete l["3d-tiles"];const A=await a(n,oP,l,s),h=function(e){const t={};for(const i in e){const s=e[i];if("indices"!==i){const e=nP(s);t[i]=e}}return t}(A.attributes);for(const[i,s]of Object.entries(h))if(i in t.attributes){const r=t.attributes[i],o=e.getAccessor(r);null!=o&&o.min&&null!=o&&o.max&&(s.min=o.min,s.max=o.max)}t.attributes=h,A.indices&&(t.indices=nP(A.indices)),function(e){if(!e.attributes&&Object.keys(e.attributes).length>0)throw new Error("glTF: Empty primitive detected: Draco decompression failure?")}(t)}function lP(e,t,i=4,s,r){var o;if(!s.DracoWriter)throw new Error("options.gltf.DracoWriter not provided");const n=s.DracoWriter.encodeSync({attributes:e}),a=null==r||null===(o=r.parseSync)||void 0===o?void 0:o.call(r,{attributes:e}),l=s._addFauxAttributes(a.attributes);return{primitives:[{attributes:l,mode:i,extensions:{KHR_draco_mesh_compression:{bufferView:s.addBufferView(n),attributes:l}}}]}}function*AP(e){for(const t of e.json.meshes||[])for(const e of t.primitives)yield e}var hP=Object.freeze({__proto__:null,name:"KHR_draco_mesh_compression",preprocess:function(e,t,i){const s=new dw(e);for(const e of AP(s))s.getObjectExtension(e,"KHR_draco_mesh_compression")},decode:async function(e,t,i){var s;if(null==t||null===(s=t.gltf)||void 0===s||!s.decompressMeshes)return;const r=new dw(e),o=[];for(const e of AP(r))r.getObjectExtension(e,"KHR_draco_mesh_compression")&&o.push(aP(r,e,t,i));await Promise.all(o),r.removeExtension("KHR_draco_mesh_compression")},encode:function(e,t={}){const i=new dw(e);for(const e of i.json.meshes||[])lP(e),i.addRequiredExtension("KHR_draco_mesh_compression")}});var cP=Object.freeze({__proto__:null,name:"KHR_lights_punctual",decode:async function(e){const t=new dw(e),{json:i}=t,s=t.getExtension("KHR_lights_punctual");s&&(t.json.lights=s.lights,t.removeExtension("KHR_lights_punctual"));for(const e of i.nodes||[]){const i=t.getObjectExtension(e,"KHR_lights_punctual");i&&(e.light=i.light),t.removeObjectExtension(e,"KHR_lights_punctual")}},encode:async function(e){const t=new dw(e),{json:i}=t;if(i.lights){const e=t.addExtension("KHR_lights_punctual");tw(!e.lights),e.lights=i.lights,delete i.lights}if(t.json.lights){for(const e of t.json.lights){const i=e.node;t.addObjectExtension(i,"KHR_lights_punctual",e)}delete t.json.lights}}});function uP(e,t){const i=Object.assign({},e.values);return Object.keys(e.uniforms||{}).forEach((t=>{e.uniforms[t].value&&!(t in i)&&(i[t]=e.uniforms[t].value)})),Object.keys(i).forEach((e=>{"object"==typeof i[e]&&void 0!==i[e].index&&(i[e].texture=t.getTexture(i[e].index))})),i}const dP=[Bw,ww,Pw,hP,cP,Object.freeze({__proto__:null,name:"KHR_materials_unlit",decode:async function(e){const t=new dw(e),{json:i}=t;t.removeExtension("KHR_materials_unlit");for(const e of i.materials||[]){e.extensions&&e.extensions.KHR_materials_unlit&&(e.unlit=!0),t.removeObjectExtension(e,"KHR_materials_unlit")}},encode:function(e){const t=new dw(e),{json:i}=t;if(t.materials)for(const e of i.materials||[])e.unlit&&(delete e.unlit,t.addObjectExtension(e,"KHR_materials_unlit",{}),t.addExtension("KHR_materials_unlit"))}}),Object.freeze({__proto__:null,name:"KHR_techniques_webgl",decode:async function(e){const t=new dw(e),{json:i}=t,s=t.getExtension("KHR_techniques_webgl");if(s){const e=function(e,t){const{programs:i=[],shaders:s=[],techniques:r=[]}=e,o=new TextDecoder;return s.forEach((e=>{if(!Number.isFinite(e.bufferView))throw new Error("KHR_techniques_webgl: no shader code");e.code=o.decode(t.getTypedArrayForBufferView(e.bufferView))})),i.forEach((e=>{e.fragmentShader=s[e.fragmentShader],e.vertexShader=s[e.vertexShader]})),r.forEach((e=>{e.program=i[e.program]})),r}(s,t);for(const s of i.materials||[]){const i=t.getObjectExtension(s,"KHR_techniques_webgl");i&&(s.technique=Object.assign({},i,e[i.technique]),s.technique.values=uP(s.technique,t)),t.removeObjectExtension(s,"KHR_techniques_webgl")}t.removeExtension("KHR_techniques_webgl")}},encode:async function(e,t){}})];function pP(e,t){var i;const s=(null==t||null===(i=t.gltf)||void 0===i?void 0:i.excludeExtensions)||{};return!(e in s&&!s[e])}const fP={accessors:"accessor",animations:"animation",buffers:"buffer",bufferViews:"bufferView",images:"image",materials:"material",meshes:"mesh",nodes:"node",samplers:"sampler",scenes:"scene",skins:"skin",textures:"texture"},gP={accessor:"accessors",animations:"animation",buffer:"buffers",bufferView:"bufferViews",image:"images",material:"materials",mesh:"meshes",node:"nodes",sampler:"samplers",scene:"scenes",skin:"skins",texture:"textures"};class mP{constructor(){Zb(this,"idToIndexMap",{animations:{},accessors:{},buffers:{},bufferViews:{},images:{},materials:{},meshes:{},nodes:{},samplers:{},scenes:{},skins:{},textures:{}}),Zb(this,"json",void 0)}normalize(e,t){this.json=e.json;const i=e.json;switch(i.asset&&i.asset.version){case"2.0":return;case void 0:case"1.0":break;default:return void console.warn("glTF: Unknown version ".concat(i.asset.version))}if(!t.normalize)throw new Error("glTF v1 is not supported.");console.warn("Converting glTF v1 to glTF v2 format. This is experimental and may fail."),this._addAsset(i),this._convertTopLevelObjectsToArrays(i),function(e){const t=new dw(e),{json:i}=t;for(const e of i.images||[]){const i=t.getObjectExtension(e,"KHR_binary_glTF");i&&Object.assign(e,i),t.removeObjectExtension(e,"KHR_binary_glTF")}i.buffers&&i.buffers[0]&&delete i.buffers[0].uri,t.removeExtension("KHR_binary_glTF")}(e),this._convertObjectIdsToArrayIndices(i),this._updateObjects(i),this._updateMaterial(i)}_addAsset(e){e.asset=e.asset||{},e.asset.version="2.0",e.asset.generator=e.asset.generator||"Normalized to glTF 2.0 by loaders.gl"}_convertTopLevelObjectsToArrays(e){for(const t in fP)this._convertTopLevelObjectToArray(e,t)}_convertTopLevelObjectToArray(e,t){const i=e[t];if(i&&!Array.isArray(i)){e[t]=[];for(const s in i){const r=i[s];r.id=r.id||s;const o=e[t].length;e[t].push(r),this.idToIndexMap[t][s]=o}}}_convertObjectIdsToArrayIndices(e){for(const t in fP)this._convertIdsToIndices(e,t);"scene"in e&&(e.scene=this._convertIdToIndex(e.scene,"scene"));for(const t of e.textures)this._convertTextureIds(t);for(const t of e.meshes)this._convertMeshIds(t);for(const t of e.nodes)this._convertNodeIds(t);for(const t of e.scenes)this._convertSceneIds(t)}_convertTextureIds(e){e.source&&(e.source=this._convertIdToIndex(e.source,"image"))}_convertMeshIds(e){for(const t of e.primitives){const{attributes:e,indices:i,material:s}=t;for(const t in e)e[t]=this._convertIdToIndex(e[t],"accessor");i&&(t.indices=this._convertIdToIndex(i,"accessor")),s&&(t.material=this._convertIdToIndex(s,"material"))}}_convertNodeIds(e){e.children&&(e.children=e.children.map((e=>this._convertIdToIndex(e,"node")))),e.meshes&&(e.meshes=e.meshes.map((e=>this._convertIdToIndex(e,"mesh"))))}_convertSceneIds(e){e.nodes&&(e.nodes=e.nodes.map((e=>this._convertIdToIndex(e,"node"))))}_convertIdsToIndices(e,t){e[t]||(console.warn("gltf v1: json doesn't contain attribute ".concat(t)),e[t]=[]);for(const i of e[t])for(const e in i){const t=i[e],s=this._convertIdToIndex(t,e);i[e]=s}}_convertIdToIndex(e,t){const i=gP[t];if(i in this.idToIndexMap){const s=this.idToIndexMap[i][e];if(!Number.isFinite(s))throw new Error("gltf v1: failed to resolve ".concat(t," with id ").concat(e));return s}return e}_updateObjects(e){for(const e of this.json.buffers)delete e.type}_updateMaterial(e){for(const s of e.materials){var t,i;s.pbrMetallicRoughness={baseColorFactor:[1,1,1,1],metallicFactor:1,roughnessFactor:1};const r=(null===(t=s.values)||void 0===t?void 0:t.tex)||(null===(i=s.values)||void 0===i?void 0:i.texture2d_0),o=e.textures.findIndex((e=>e.id===r));-1!==o&&(s.pbrMetallicRoughness.baseColorTexture={index:o})}}}const _P={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},vP={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},bP=10240,yP=10241,xP=10242,BP=10243,wP=10497,PP={magFilter:bP,minFilter:yP,wrapS:xP,wrapT:BP},CP={[bP]:9729,[yP]:9986,[xP]:wP,[BP]:wP};class MP{constructor(){Zb(this,"baseUri",""),Zb(this,"json",{}),Zb(this,"buffers",[]),Zb(this,"images",[])}postProcess(e,t={}){const{json:i,buffers:s=[],images:r=[],baseUri:o=""}=e;return tw(i),this.baseUri=o,this.json=i,this.buffers=s,this.images=r,this._resolveTree(this.json,t),this.json}_resolveTree(e,t={}){e.bufferViews&&(e.bufferViews=e.bufferViews.map(((e,t)=>this._resolveBufferView(e,t)))),e.images&&(e.images=e.images.map(((e,t)=>this._resolveImage(e,t)))),e.samplers&&(e.samplers=e.samplers.map(((e,t)=>this._resolveSampler(e,t)))),e.textures&&(e.textures=e.textures.map(((e,t)=>this._resolveTexture(e,t)))),e.accessors&&(e.accessors=e.accessors.map(((e,t)=>this._resolveAccessor(e,t)))),e.materials&&(e.materials=e.materials.map(((e,t)=>this._resolveMaterial(e,t)))),e.meshes&&(e.meshes=e.meshes.map(((e,t)=>this._resolveMesh(e,t)))),e.nodes&&(e.nodes=e.nodes.map(((e,t)=>this._resolveNode(e,t)))),e.skins&&(e.skins=e.skins.map(((e,t)=>this._resolveSkin(e,t)))),e.scenes&&(e.scenes=e.scenes.map(((e,t)=>this._resolveScene(e,t)))),void 0!==e.scene&&(e.scene=e.scenes[this.json.scene])}getScene(e){return this._get("scenes",e)}getNode(e){return this._get("nodes",e)}getSkin(e){return this._get("skins",e)}getMesh(e){return this._get("meshes",e)}getMaterial(e){return this._get("materials",e)}getAccessor(e){return this._get("accessors",e)}getCamera(e){return null}getTexture(e){return this._get("textures",e)}getSampler(e){return this._get("samplers",e)}getImage(e){return this._get("images",e)}getBufferView(e){return this._get("bufferViews",e)}getBuffer(e){return this._get("buffers",e)}_get(e,t){if("object"==typeof t)return t;const i=this.json[e]&&this.json[e][t];return i||console.warn("glTF file error: Could not find ".concat(e,"[").concat(t,"]")),i}_resolveScene(e,t){return e.id=e.id||"scene-".concat(t),e.nodes=(e.nodes||[]).map((e=>this.getNode(e))),e}_resolveNode(e,t){return e.id=e.id||"node-".concat(t),e.children&&(e.children=e.children.map((e=>this.getNode(e)))),void 0!==e.mesh?e.mesh=this.getMesh(e.mesh):void 0!==e.meshes&&e.meshes.length&&(e.mesh=e.meshes.reduce(((e,t)=>{const i=this.getMesh(t);return e.id=i.id,e.primitives=e.primitives.concat(i.primitives),e}),{primitives:[]})),void 0!==e.camera&&(e.camera=this.getCamera(e.camera)),void 0!==e.skin&&(e.skin=this.getSkin(e.skin)),e}_resolveSkin(e,t){return e.id=e.id||"skin-".concat(t),e.inverseBindMatrices=this.getAccessor(e.inverseBindMatrices),e}_resolveMesh(e,t){return e.id=e.id||"mesh-".concat(t),e.primitives&&(e.primitives=e.primitives.map((e=>{const t=(e={...e}).attributes;e.attributes={};for(const i in t)e.attributes[i]=this.getAccessor(t[i]);return void 0!==e.indices&&(e.indices=this.getAccessor(e.indices)),void 0!==e.material&&(e.material=this.getMaterial(e.material)),e}))),e}_resolveMaterial(e,t){if(e.id=e.id||"material-".concat(t),e.normalTexture&&(e.normalTexture={...e.normalTexture},e.normalTexture.texture=this.getTexture(e.normalTexture.index)),e.occlusionTexture&&(e.occlustionTexture={...e.occlustionTexture},e.occlusionTexture.texture=this.getTexture(e.occlusionTexture.index)),e.emissiveTexture&&(e.emmisiveTexture={...e.emmisiveTexture},e.emissiveTexture.texture=this.getTexture(e.emissiveTexture.index)),e.emissiveFactor||(e.emissiveFactor=e.emmisiveTexture?[1,1,1]:[0,0,0]),e.pbrMetallicRoughness){e.pbrMetallicRoughness={...e.pbrMetallicRoughness};const t=e.pbrMetallicRoughness;t.baseColorTexture&&(t.baseColorTexture={...t.baseColorTexture},t.baseColorTexture.texture=this.getTexture(t.baseColorTexture.index)),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture={...t.metallicRoughnessTexture},t.metallicRoughnessTexture.texture=this.getTexture(t.metallicRoughnessTexture.index))}return e}_resolveAccessor(e,t){var i,s;if(e.id=e.id||"accessor-".concat(t),void 0!==e.bufferView&&(e.bufferView=this.getBufferView(e.bufferView)),e.bytesPerComponent=(i=e.componentType,vP[i]),e.components=(s=e.type,_P[s]),e.bytesPerElement=e.bytesPerComponent*e.components,e.bufferView){const t=e.bufferView.buffer,{ArrayType:i,byteLength:s}=cw(e,e.bufferView),r=(e.bufferView.byteOffset||0)+(e.byteOffset||0)+t.byteOffset;let o=t.arrayBuffer.slice(r,r+s);e.bufferView.byteStride&&(o=this._getValueFromInterleavedBuffer(t,r,e.bufferView.byteStride,e.bytesPerElement,e.count)),e.value=new i(o)}return e}_getValueFromInterleavedBuffer(e,t,i,s,r){const o=new Uint8Array(r*s);for(let n=0;n20);const s=t.getUint32(i+0,FP),r=t.getUint32(i+4,FP);return i+=8,Vb(0===r),DP(e,t,i,s),i+=s,i+=SP(e,t,i,e.header.byteLength)}(e,r,i);case 2:return function(e,t,i,s){return Vb(e.header.byteLength>20),function(e,t,i,s){for(;i+8<=e.header.byteLength;){const r=t.getUint32(i+0,FP),o=t.getUint32(i+4,FP);switch(i+=8,o){case 1313821514:DP(e,t,i,r);break;case 5130562:SP(e,t,i,r);break;case 0:s.strict||DP(e,t,i,r);break;case 1:s.strict||SP(e,t,i,r)}i+=by(r,4)}}(e,t,i,s),i+e.header.byteLength}(e,r,i,{});default:throw new Error("Invalid GLB version ".concat(e.version,". Only supports v1 and v2."))}}function DP(e,t,i,s){const r=new Uint8Array(t.buffer,i,s),o=new TextDecoder("utf8").decode(r);return e.json=JSON.parse(o),by(s,4)}function SP(e,t,i,s){return e.header.hasBinChunk=!0,e.binChunks.push({byteOffset:i,byteLength:s,arrayBuffer:t.buffer}),by(s,4)}async function TP(e,t,i=0,s,r){var o,n,a,l;!function(e,t,i,s){s.uri&&(e.baseUri=s.uri);if(t instanceof ArrayBuffer&&!function(e,t=0,i={}){const s=new DataView(e),{magic:r=EP}=i,o=s.getUint32(t,!1);return o===r||o===EP}(t,i,s)){t=(new TextDecoder).decode(t)}if("string"==typeof t)e.json=gy(t);else if(t instanceof ArrayBuffer){const r={};i=IP(r,t,i,s.glb),tw("glTF"===r.type,"Invalid GLB magic string ".concat(r.type)),e._glb=r,e.json=r.json}else tw(!1,"GLTF: must be ArrayBuffer or string");const r=e.json.buffers||[];if(e.buffers=new Array(r.length).fill(null),e._glb&&e._glb.header.hasBinChunk){const{binChunks:t}=e._glb;e.buffers[0]={arrayBuffer:t[0].arrayBuffer,byteOffset:t[0].byteOffset,byteLength:t[0].byteLength}}const o=e.json.images||[];e.images=new Array(o.length).fill({})}(e,t,i,s),function(e,t={}){(new mP).normalize(e,t)}(e,{normalize:null==s||null===(o=s.gltf)||void 0===o?void 0:o.normalize}),function(e,t={},i){const s=dP.filter((e=>pP(e.name,t)));for(const o of s){var r;null===(r=o.preprocess)||void 0===r||r.call(o,e,t,i)}}(e,s,r);const A=[];if(null!=s&&null!==(n=s.gltf)&&void 0!==n&&n.loadBuffers&&e.json.buffers&&await async function(e,t,i){const s=e.json.buffers||[];for(let n=0;npP(e.name,t)));for(const o of s){var r;await(null===(r=o.decode)||void 0===r?void 0:r.call(o,e,t,i))}}(e,s,r);return A.push(h),await Promise.all(A),null!=s&&null!==(l=s.gltf)&&void 0!==l&&l.postProcess?function(e,t){return(new MP).postProcess(e,t)}(e,s):e}async function RP(e,t,i,s,r){const{fetch:o,parse:n}=r;let a;if(t.uri){const e=iw(t.uri,s),i=await o(e);a=await i.arrayBuffer()}if(Number.isFinite(t.bufferView)){const i=function(e,t,i){const s=e.bufferViews[i];tw(s);const r=t[s.buffer];tw(r);const o=(s.byteOffset||0)+r.byteOffset;return new Uint8Array(r.arrayBuffer,o,s.byteLength)}(e.json,e.buffers,t.bufferView);a=vy(i.buffer,i.byteOffset,i.byteLength)}tw(a,"glTF image has no data");let l=await n(a,[ZB,RB],{mimeType:t.mimeType,basis:s.basis||{format:TB()}},r);l&&l[0]&&(l={compressed:!0,mipmaps:!1,width:l[0].width,height:l[0].height,data:l[0]}),e.images=e.images||[],e.images[i]=l}const LP={name:"glTF",id:"gltf",module:"gltf",version:"3.2.6",extensions:["gltf","glb"],mimeTypes:["model/gltf+json","model/gltf-binary"],text:!0,binary:!0,tests:["glTF"],parse:async function(e,t={},i){(t={...LP.options,...t}).gltf={...LP.options.gltf,...t.gltf};const{byteOffset:s=0}=t;return await TP({},e,s,t,i)},options:{gltf:{normalize:!0,loadBuffers:!0,loadImages:!0,decompressMeshes:!0,postProcess:!0},log:console},deprecatedOptions:{fetchImages:"gltf.loadImages",createImages:"gltf.loadImages",decompress:"gltf.decompressMeshes",postProcess:"gltf.postProcess",gltf:{decompress:"gltf.decompressMeshes"}}};class UP{constructor(e){}load(e,t,i,s,r,o,n){!function(e,t,i,s,r,o,n){const a=e.viewer.scene.canvas.spinner;a.processes++;"glb"===t.split(".").pop()?e.dataSource.getGLB(t,(n=>{s.basePath=OP(t),kP(e,t,n,i,s,r,o),a.processes--}),(e=>{a.processes--,n(e)})):e.dataSource.getGLTF(t,(n=>{s.basePath=OP(t),kP(e,t,n,i,s,r,o),a.processes--}),(e=>{a.processes--,n(e)}))}(e,t,i,s=s||{},r,(function(){I.scheduleTask((function(){r.scene.fire("modelLoaded",r.id),r.fire("loaded",!0,!1)})),o&&o()}),(function(t){e.error(t),n&&n(t),r.fire("error",t)}))}parse(e,t,i,s,r,o,n){kP(e,"",t,i,s=s||{},r,(function(){r.scene.fire("modelLoaded",r.id),r.fire("loaded",!0,!1),o&&o()}))}}function OP(e){const t=e.lastIndexOf("/");return 0!==t?e.substring(0,t+1):""}function kP(e,t,i,s,r,o,n){const a=e.viewer.scene.canvas.spinner;a.processes++,eB(i,LP,{baseUri:r.basePath}).then((i=>{const l={src:t,entityId:r.entityId,metaModelJSON:s,autoMetaModel:r.autoMetaModel,globalizeObjectIds:r.globalizeObjectIds,metaObjects:[],loadBuffer:r.loadBuffer,basePath:r.basePath,handlenode:r.handlenode,backfaces:!!r.backfaces,gltfData:i,scene:o.scene,plugin:e,sceneModel:o,numObjects:0,nodes:[],nextId:0,log:t=>{e.log(t)}};!function(e){const t=e.gltfData.textures;if(t)for(let i=0,s=t.length;i{const i=t.mesh;i&&(i.instances||=0,i.instances+=1),t.children&&e(t.children)}))}(s);const r=[];let o=null;!function t(i,s,n){i.forEach((i=>{const a=i.name;let l=null!=a&&a||0===s&&"entity-"+e.nextId++;if(l){for(;e.sceneModel.objects[l];)l="entity-"+e.nextId++;r.push(o),o=[]}const A=function(e,t){let i;e.matrix&&(i=e.matrix,t=t?d.mulMat4(t,i,d.mat4()):i);e.translation&&(i=d.translationMat4v(e.translation),t=t?d.mulMat4(t,i,d.mat4()):i);e.rotation&&(i=d.quaternionToMat4(e.rotation),t=t?d.mulMat4(t,i,d.mat4()):i);e.scale&&(i=d.scalingMat4v(e.scale),t=t?d.mulMat4(t,i,d.mat4()):i);return t}(i,n);if(i.mesh&&function(e,t,i,s){const r=e.mesh;if(!r)return;const o=r.primitives.length;if(o>0)for(let e=0;e0){const t=e.globalizeObjectIds?d.globalizeObjectId(e.sceneModel.id,l):l;e.sceneModel.createEntity({id:t,meshIds:o,isObject:!0}),e.autoMetaModel&&e.metaObjects.push({id:t,type:"Default",name:t,parent:e.sceneModel.id})}o=r.pop()}}))}(s,0,null)}(l),o.finalize(),r.autoMetaModel&&e.viewer.metaScene.createMetaModel(o.id,{metaObjects:l.metaObjects}),a.processes--,n()}))}function NP(e,t){if(!t.source||!t.source.image)return;const i="texture-"+e.nextId++;let s=1005;switch(t.sampler.minFilter){case 9728:s=1003;break;case 9729:s=1006;break;case 9984:s=1004;break;case 9985:s=1007;break;case 9986:s=1005;break;case 9987:s=1008}let r=1006;switch(t.sampler.magFilter){case 9728:r=1003;break;case 9729:r=1006}let o=1e3;switch(t.sampler.wrapS){case 33071:o=1001;break;case 33648:o=1002;break;case 10497:o=1e3}let n=1e3;switch(t.sampler.wrapT){case 33071:n=1001;break;case 33648:n=1002;break;case 10497:n=1e3}let a=1e3;switch(t.sampler.wrapR){case 33071:a=1001;break;case 33648:a=1002;break;case 10497:a=1e3}e.sceneModel.createTexture({id:i,image:t.source.image,flipY:!!t.flipY,minFilter:s,magFilter:r,wrapS:o,wrapT:n,wrapR:a,encoding:3001}),t._textureId=i}function QP(e,t){const i={};switch(t.normalTexture&&(i.normalTextureId=t.normalTexture.texture._textureId),t.occlusionTexture&&(i.occlusionTextureId=t.occlusionTexture.texture._textureId),t.emissiveTexture&&(i.emissiveTextureId=t.emissiveTexture.texture._textureId),t.alphaMode){case"OPAQUE":break;case"MASK":const e=t.alphaCutoff;i.alphaCutoff=void 0!==e?e:.5}const s=t.pbrMetallicRoughness;if(t.pbrMetallicRoughness){const r=t.pbrMetallicRoughness,o=r.baseColorTexture||r.colorTexture;o&&(o.texture?i.colorTextureId=o.texture._textureId:i.colorTextureId=e.gltfData.textures[o.index]._textureId),s.metallicRoughnessTexture&&(i.metallicRoughnessTextureId=s.metallicRoughnessTexture.texture._textureId)}const r=t.extensions;if(r){const t=r.KHR_materials_pbrSpecularGlossiness;if(t){t.specularTexture;const s=t.specularColorTexture;null!=s&&(i.colorTextureId=e.gltfData.textures[s.index]._textureId)}}return void 0!==i.normalTextureId||void 0!==i.occlusionTextureId||void 0!==i.emissiveTextureId||void 0!==i.colorTextureId||void 0!==i.metallicRoughnessTextureId?(i.id=`textureSet-${e.nextId++};`,e.sceneModel.createTextureSet(i),i.id):null}function VP(e,t){const i=t.extensions,s={color:new Float32Array([1,1,1,1]),opacity:1,metallic:0,roughness:1,doubleSided:!0};if(i){const e=i.KHR_materials_pbrSpecularGlossiness;if(e){const t=e.diffuseFactor;null!=t&&s.color.set(t)}const t=i.KHR_materials_common;if(t){const e=t.technique,i=t.values||{},r="BLINN"===e,o="PHONG"===e,n="LAMBERT"===e,a=i.diffuse;a&&(r||o||n)&&(y.isString(a)||s.color.set(a));const l=i.transparency;null!=l&&(s.opacity=l);const A=i.transparent;null!=A&&(s.opacity=A)}}const r=t.pbrMetallicRoughness;if(r){const e=r.baseColorFactor;e&&(s.color[0]=e[0],s.color[1]=e[1],s.color[2]=e[2],s.opacity=e[3]);const t=r.metallicFactor;null!=t&&(s.metallic=t);const i=r.roughnessFactor;null!=i&&(s.roughness=i)}return s.doubleSided=!1!==t.doubleSided,s}const HP={DEFAULT:{}};class jP extends z{constructor(e,t={}){super("GLTFLoader",e,t),this._sceneModelLoader=new UP(this,t),this.dataSource=t.dataSource,this.objectDefaults=t.objectDefaults}set dataSource(e){this._dataSource=e||new pu}get dataSource(){return this._dataSource}set objectDefaults(e){this._objectDefaults=e||HP}get objectDefaults(){return this._objectDefaults}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 Gc(this.viewer.scene,y.apply(e,{isModel:!0,dtxEnabled:e.dtxEnabled})),i=t.id;if(!e.src&&!e.gltf)return this.error("load() param expected: src or gltf"),t;if(e.metaModelSrc||e.metaModelJSON){const s=s=>{this.viewer.metaScene.createMetaModel(i,s,{}),this.viewer.scene.canvas.spinner.processes--,e.src?this._sceneModelLoader.load(this,e.src,s,e,t):this._sceneModelLoader.parse(this,e.gltf,s,e,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--,s(e)}),(e=>{this.error(`load(): Failed to load model metadata for model '${i} from '${t}' - ${e}`),this.viewer.scene.canvas.spinner.processes--}))}else e.metaModelJSON&&s(e.metaModelJSON)}else e.src?this._sceneModelLoader.load(this,e.src,null,e,t):this._sceneModelLoader.parse(this,e.gltf,null,e,t);return t.once("destroyed",(()=>{this.viewer.metaScene.destroyMetaModel(i)})),t}destroy(){super.destroy()}}function GP(e,t,i={}){const s="lightgrey",r=i.hoverColor||"rgba(0,0,0,0.4)",o=i.textColor||"black",n=500,a=n+n/3,l=a/24,A=[{boundary:[6,6,6,6],color:i.frontColor||i.color||"#55FF55"},{boundary:[18,6,6,6],color:i.backColor||i.color||"#55FF55"},{boundary:[12,6,6,6],color:i.rightColor||i.color||"#FF5555"},{boundary:[0,6,6,6],color:i.leftColor||i.color||"#FF5555"},{boundary:[6,0,6,6],color:i.topColor||i.color||"#7777FF"},{boundary:[6,12,6,6],color:i.bottomColor||i.color||"#7777FF"}],h=[{label:"NavCube.front",boundaries:[[7,7,4,4]],dir:[0,1,0],up:[0,0,1]},{label:"NavCube.back",boundaries:[[19,7,4,4]],dir:[0,-1,0],up:[0,0,1]},{label:"NavCube.right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,0,1]},{label:"NavCube.left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,0,1]},{label:"NavCube.top",boundaries:[[7,1,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"NavCube.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]}];i.frontColor||i.color,i.backColor||i.color,i.rightColor||i.color,i.leftColor||i.color,i.topColor||i.color,i.bottomColor||i.color;const c=[{yUp:"",label:"NavCube.front",boundaries:[[7,7,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"NavCube.back",boundaries:[[19,7,4,4]],dir:[0,0,1],up:[0,1,0]},{label:"NavCube.right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,1,0]},{label:"NavCube.left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,1,0]},{label:"NavCube.top",boundaries:[[7,1,4,4]],dir:[0,-1,0],up:[0,0,-1]},{label:"NavCube.bottom",boundaries:[[7,13,4,4]],dir:[0,1,0],up:[0,0,1]},{boundaries:[[7,5,4,2]],dir:[0,-.7071,-.7071],up:[0,.7071,-.7071]},{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,-.7071,.7071],up:[0,.7071,.7071]},{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:[.5,.7071,-.5],up:[-.5,.7071,.5]},{boundaries:[[23,11,1,1],[6,17,1,1],[0,11,1,1]],dir:[.5,.7071,.5],up:[-.5,.7071,-.5]},{boundaries:[[5,5,2,2]],dir:[.5,-.7071,-.5],up:[.5,.7071,-.5]},{boundaries:[[11,17,1,1],[17,11,2,1]],dir:[-.5,.7071,.5],up:[.5,.7071,-.5]},{boundaries:[[17,6,2,1],[11,0,1,1]],dir:[-.5,-.7071,.5],up:[-.5,.7071,.5]},{boundaries:[[11,11,2,2]],dir:[-.5,.7071,-.5],up:[.5,.7071,.5]},{boundaries:[[0,6,1,1],[6,0,1,1],[23,6,1,1]],dir:[.5,-.7071,.5],up:[.5,.7071,.5]},{boundaries:[[11,5,2,2]],dir:[-.5,-.7071,-.5],up:[-.5,.7071,-.5]}];for(let e=0,t=h.length;e=r[0]*l&&t<=(r[0]+r[2])*l&&i>=r[1]*l&&i<=(r[1]+r[3])*l)return s}}return-1},this.setAreaHighlighted=function(e,t){var i=u[e];if(!i)throw"Area not found: "+e;i.highlighted=!!t,g()},this.getAreaDir=function(e){var t=u[e];if(!t)throw"Unknown area: "+e;return t.dir},this.getAreaUp=function(e){var t=u[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)}}const zP=d.vec3(),WP=d.vec3();d.mat4();class KP extends z{constructor(e,t={}){super("NavCube",e,t),e.navCube=this;try{this._navCubeScene=new vi(e,{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 Vt(i,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new Vt(i,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new Vt(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,i.edgeMaterial.edgeColor=[.2,.2,.2],i.edgeMaterial.edgeAlpha=.6,this._zUp=Boolean(e.camera.zUp);var s=this;this.setIsProjectNorth(t.isProjectNorth),this.setProjectNorthOffsetAngle(t.projectNorthOffsetAngle);const r=function(){const e=d.mat4();return function(t,i,r){return d.identityMat4(e),d.rotationMat4v(t*s._projectNorthOffsetAngle*d.DEGTORAD,[0,1,0],e),d.transformVec3(e,i,r)}}();this._synchCamera=function(){var t=d.rotationMat4c(-90*d.DEGTORAD,1,0,0),i=d.vec3(),o=d.vec3(),n=d.vec3();return function(){var a=e.camera.eye,l=e.camera.look,A=e.camera.up;i=d.mulVec3Scalar(d.normalizeVec3(d.subVec3(a,l,i)),5),s._isProjectNorth&&s._projectNorthOffsetAngle&&(i=r(-1,i,zP),A=r(-1,A,WP)),s._zUp?(d.transformVec3(t,i,o),d.transformVec3(t,A,n),s._navCubeCamera.look=[0,0,0],s._navCubeCamera.eye=d.transformVec3(t,i,o),s._navCubeCamera.up=d.transformPoint3(t,A,n)):(s._navCubeCamera.look=[0,0,0],s._navCubeCamera.eye=i,s._navCubeCamera.up=A)}}(),this._cubeTextureCanvas=new GP(e,i,t),this._cubeSampler=new so(i,{image:this._cubeTextureCanvas.getImage(),flipY:!0,wrapS:1001,wrapT:1001}),this._cubeMesh=new wr(i,{geometry:new ei(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 oi(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=!1===t.shadowVisible?null:new wr(i,{geometry:new ei(i,Cr({center:[0,0,0],radiusTop:.001,radiusBottom:1.4,height:.01,radialSegments:20,heightSegments:1,openEnded:!0})),material:new oi(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="ortho"===e||"perspective"===e?e:"perspective")}));var o=-1;function n(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 a,l,A=null,h=null,c=!1,u=!1,p=.5;s._navCubeCanvas.addEventListener("mouseenter",s._onMouseEnter=function(e){u=!0}),s._navCubeCanvas.addEventListener("mouseleave",s._onMouseLeave=function(e){u=!1}),s._navCubeCanvas.addEventListener("mousedown",s._onMouseDown=function(e){if(1===e.which){A=e.x,h=e.y,a=e.clientX,l=e.clientY;var t=n(e),s=i.pick({canvasPos:t});c=!!s}}),document.addEventListener("mouseup",s._onMouseUp=function(e){if(1===e.which&&(c=!1,null!==A)){var t=n(e),a=i.pick({canvasPos:t,pickSurface:!0});if(a&&a.uv){var l=s._cubeTextureCanvas.getArea(a.uv);if(l>=0&&(document.body.style.cursor="pointer",o>=0&&(s._cubeTextureCanvas.setAreaHighlighted(o,!1),s._repaint(),o=-1),l>=0)){if(s._cubeTextureCanvas.setAreaHighlighted(l,!0),o=l,s._repaint(),e.xA+3||e.yh+3)return;var u=s._cubeTextureCanvas.getAreaDir(l);if(u){var d=s._cubeTextureCanvas.getAreaUp(l);s._isProjectNorth&&s._projectNorthOffsetAngle&&(u=r(1,u,zP),d=r(1,d,WP)),f(u,d,(function(){o>=0&&(s._cubeTextureCanvas.setAreaHighlighted(o,!1),s._repaint(),o=-1),document.body.style.cursor="pointer",o>=0&&(s._cubeTextureCanvas.setAreaHighlighted(o,!1),s._repaint(),o=-1),l>=0&&(s._cubeTextureCanvas.setAreaHighlighted(l,!1),o=-1,s._repaint())}))}}}}}),document.addEventListener("mousemove",s._onMouseMove=function(t){if(o>=0&&(s._cubeTextureCanvas.setAreaHighlighted(o,!1),s._repaint(),o=-1),1!==t.buttons||c){if(c){var r=t.clientX,A=t.clientY;return document.body.style.cursor="move",void function(t,i){var s=(t-a)*-p,r=(i-l)*-p;e.camera.orbitYaw(s),e.camera.orbitPitch(-r),a=t,l=i}(r,A)}if(u){var h=n(t),d=i.pick({canvasPos:h,pickSurface:!0});if(d){if(d.uv){document.body.style.cursor="pointer";var f=s._cubeTextureCanvas.getArea(d.uv);if(f===o)return;o>=0&&s._cubeTextureCanvas.setAreaHighlighted(o,!1),f>=0&&(s._cubeTextureCanvas.setAreaHighlighted(f,!0),s._repaint(),o=f)}}else document.body.style.cursor="default",o>=0&&(s._cubeTextureCanvas.setAreaHighlighted(o,!1),s._repaint(),o=-1)}}});var f=function(){var t=d.vec3();return function(i,r,o){var n=s._fitVisible?e.scene.getAABB(e.scene.visibleObjectIds):e.scene.aabb,a=d.getAABB3Diag(n);d.getAABB3Center(n,t);var l=Math.abs(a/Math.tan(s._cameraFitFOV*d.DEGTORAD));e.cameraControl.pivotPos=t,s._cameraFly?e.cameraFlight.flyTo({look:t,eye:[t[0]-l*i[0],t[1]-l*i[1],t[2]-l*i[2]],up:r||[0,1,0],orthoScale:1.1*a,fitFOV:s._cameraFitFOV,duration:s._cameraFlyDuration},o):e.cameraFlight.jumpTo({look:t,eye:[t[0]-l*i[0],t[1]-l*i[1],t[2]-l*i[2]],up:r||[0,1,0],orthoScale:1.1*a,fitFOV:s._cameraFitFOV},o)}}();this._onUpdated=e.localeService.on("updated",(()=>{this._cubeTextureCanvas.clear(),this._repaint()})),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){if("language"===e)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&&(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}setIsProjectNorth(e=!1){this._isProjectNorth=e}getIsProjectNorth(){return this._isProjectNorth}setProjectNorthOffsetAngle(e){this._projectNorthOffsetAngle=e}getProjectNorthOffsetAngle(){return this._projectNorthOffsetAngle}destroy(){this._navCubeCanvas&&(this.viewer.localeService.off(this._onUpdated),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()}}const XP=d.vec3();class JP{load(e,t,i={}){var s=e.scene.canvas.spinner;s.processes++,YP(e,t,(function(t){!function(e,t,i){for(var s=t.basePath,r=Object.keys(t.materialLibraries),o=r.length,n=0,a=o;n=0?i-1:i+t/3)}function r(e,t){var i=parseInt(e,10);return 3*(i>=0?i-1:i+t/3)}function o(e,t){var i=parseInt(e,10);return 2*(i>=0?i-1:i+t/2)}function n(e,t,i,s){var r=e.positions,o=e.object.geometry.positions;o.push(r[t+0]),o.push(r[t+1]),o.push(r[t+2]),o.push(r[i+0]),o.push(r[i+1]),o.push(r[i+2]),o.push(r[s+0]),o.push(r[s+1]),o.push(r[s+2])}function a(e,t){var i=e.positions,s=e.object.geometry.positions;s.push(i[t+0]),s.push(i[t+1]),s.push(i[t+2])}function l(e,t,i,s){var r=e.normals,o=e.object.geometry.normals;o.push(r[t+0]),o.push(r[t+1]),o.push(r[t+2]),o.push(r[i+0]),o.push(r[i+1]),o.push(r[i+2]),o.push(r[s+0]),o.push(r[s+1]),o.push(r[s+2])}function A(e,t,i,s){var r=e.uv,o=e.object.geometry.uv;o.push(r[t+0]),o.push(r[t+1]),o.push(r[i+0]),o.push(r[i+1]),o.push(r[s+0]),o.push(r[s+1])}function h(e,t){var i=e.uv,s=e.object.geometry.uv;s.push(i[t+0]),s.push(i[t+1])}function c(e,t,i,a,h,c,u,d,p,f,g,m,_){var v,b=e.positions.length,y=s(t,b),x=s(i,b),B=s(a,b);if(void 0===h?n(e,y,x,B):(n(e,y,x,v=s(h,b)),n(e,x,B,v)),void 0!==c){var w=e.uv.length;y=o(c,w),x=o(u,w),B=o(d,w),void 0===h?A(e,y,x,B):(A(e,y,x,v=o(p,w)),A(e,x,B,v))}if(void 0!==f){var P=e.normals.length;y=r(f,P),x=f===g?y:r(g,P),B=f===m?y:r(m,P),void 0===h?l(e,y,x,B):(l(e,y,x,v=r(_,P)),l(e,x,B,v))}}function u(e,t,i){e.object.geometry.type="Line";for(var r=e.positions.length,n=e.uv.length,l=0,A=t.length;l=0?n.substring(0,a):n).toLowerCase(),A=(A=a>=0?n.substring(a+1):"").trim(),l.toLowerCase()){case"newmtl":i(e,u),u={id:A},d=!0;break;case"ka":u.ambient=s(A);break;case"kd":u.diffuse=s(A);break;case"ks":u.specular=s(A);break;case"map_kd":u.diffuseMap||(u.diffuseMap=t(e,o,A,"sRGB"));break;case"map_ks":u.specularMap||(u.specularMap=t(e,o,A,"linear"));break;case"map_bump":case"bump":u.normalMap||(u.normalMap=t(e,o,A));break;case"ns":u.shininess=parseFloat(A);break;case"d":(h=parseFloat(A))<1&&(u.alpha=h,u.alphaMode="blend");break;case"tr":(h=parseFloat(A))>0&&(u.alpha=1-h,u.alphaMode="blend")}d&&i(e,u)};function t(e,t,i,s){var r={},o=i.split(/\s+/),n=o.indexOf("-bm");return n>=0&&o.splice(n,2),(n=o.indexOf("-s"))>=0&&(r.scale=[parseFloat(o[n+1]),parseFloat(o[n+2])],o.splice(n,4)),(n=o.indexOf("-o"))>=0&&(r.translate=[parseFloat(o[n+1]),parseFloat(o[n+2])],o.splice(n,4)),r.src=t+o.join(" ").trim(),r.flipY=!0,r.encoding=s||"linear",new so(e,r).id}function i(e,t){new oi(e,t)}function s(t){var i=t.split(e,3);return[parseFloat(i[0]),parseFloat(i[1]),parseFloat(i[2])]}}();function eC(e,t){for(var i=0,s=t.objects.length;i0&&(n.normals=o.normals),o.uv.length>0&&(n.uv=o.uv);for(var a=new Array(n.positions.length/3),l=0;l{this.viewer.metaScene.createMetaModel(i,r),this._sceneGraphLoader.load(t,s,e)}),(e=>{this.error(`load(): Failed to load model modelMetadata for model '${i} from '${r}' - ${e}`)}))}else this._sceneGraphLoader.load(t,s,e);return t.once("destroyed",(()=>{this.viewer.metaScene.destroyMetaModel(i)})),t}destroy(){super.destroy()}}const sC=new Float64Array([0,0,1]),rC=new Float64Array(4);class oC{constructor(e){this.id=null,this._viewer=e.viewer,this._visible=!1,this._pos=d.vec3(),this._origin=d.vec3(),this._rtcPos=d.vec3(),this._baseDir=d.vec3(),this._rootNode=null,this._displayMeshes=null,this._affordanceMeshes=null,this._ignoreNextSectionPlaneDirUpdate=!1,this._createNodes(),this._bindEvents()}_setSectionPlane(e){this._sectionPlane&&(this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._onSectionPlanePos=null,this._onSectionPlaneDir=null,this._sectionPlane=null),e&&(this.id=e.id,this._setPos(e.pos),this._setDir(e.dir),this._sectionPlane=e,this._onSectionPlanePos=e.on("pos",(()=>{this._setPos(this._sectionPlane.pos)})),this._onSectionPlaneDir=e.on("dir",(()=>{this._ignoreNextSectionPlaneDirUpdate?this._ignoreNextSectionPlaneDirUpdate=!1:this._setDir(this._sectionPlane.dir)})))}get sectionPlane(){return this._sectionPlane}_setPos(e){this._pos.set(e),Y(this._pos,this._origin,this._rtcPos),this._rootNode.origin=this._origin,this._rootNode.position=this._rtcPos}_setDir(e){this._baseDir.set(e),this._rootNode.quaternion=d.vec3PairToQuaternion(sC,e,rC)}_setSectionPlaneDir(e){this._sectionPlane&&(this._ignoreNextSectionPlaneDirUpdate=!0,this._sectionPlane.dir=e)}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=!1,t=this._viewer.scene,i=.01;this._rootNode=new Vr(t,{position:[0,0,0],scale:[5,5,5],isObject:!1});const s=this._rootNode,r={arrowHead:new ei(s,Cr({radiusTop:.001,radiusBottom:.07,radialSegments:32,heightSegments:1,height:.2,openEnded:!1})),arrowHeadBig:new ei(s,Cr({radiusTop:.001,radiusBottom:.09,radialSegments:32,heightSegments:1,height:.25,openEnded:!1})),arrowHeadHandle:new ei(s,Cr({radiusTop:.09,radiusBottom:.09,radialSegments:8,heightSegments:1,height:.37,openEnded:!1})),curve:new ei(s,go({radius:.8,tube:i,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),curveHandle:new ei(s,go({radius:.8,tube:.06,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),hoop:new ei(s,go({radius:.8,tube:i,radialSegments:64,tubeSegments:8,arc:2*Math.PI})),axis:new ei(s,Cr({radiusTop:i,radiusBottom:i,radialSegments:20,heightSegments:1,height:1,openEnded:!1})),axisHandle:new ei(s,Cr({radiusTop:.08,radiusBottom:.08,radialSegments:20,heightSegments:1,height:1,openEnded:!1}))},o={pickable:new oi(s,{diffuse:[1,1,0],alpha:0,alphaMode:"blend"}),red:new oi(s,{diffuse:[1,0,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightRed:new ai(s,{edges:!1,fill:!0,fillColor:[1,0,0],fillAlpha:.6}),green:new oi(s,{diffuse:[0,1,0],emissive:[0,1,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightGreen:new ai(s,{edges:!1,fill:!0,fillColor:[0,1,0],fillAlpha:.6}),blue:new oi(s,{diffuse:[0,0,1],emissive:[0,0,1],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightBlue:new ai(s,{edges:!1,fill:!0,fillColor:[0,0,1],fillAlpha:.2}),center:new oi(s,{diffuse:[0,0,0],emissive:[0,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80}),highlightBall:new ai(s,{edges:!1,fill:!0,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1}),highlightPlane:new ai(s,{edges:!0,edgeWidth:3,fill:!1,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1})};this._displayMeshes={plane:s.addChild(new wr(s,{geometry:new ei(s,{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 oi(s,{emissive:[0,0,0],diffuse:[0,0,0],backfaces:!0}),opacity:.6,ghosted:!0,ghostMaterial:new ai(s,{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],isObject:!1}),e),planeFrame:s.addChild(new wr(s,{geometry:new ei(s,go({center:[0,0,0],radius:1.7,tube:.02,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new oi(s,{emissive:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],shininess:0}),highlightMaterial:new ai(s,{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],isObject:!1}),e),xCurve:s.addChild(new wr(s,{geometry:r.curve,material:o.red,matrix:function(){const e=d.rotationMat4v(90*d.DEGTORAD,[0,1,0],d.identityMat4()),t=d.rotationMat4v(270*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xCurveHandle:s.addChild(new wr(s,{geometry:r.curveHandle,material:o.pickable,matrix:function(){const e=d.rotationMat4v(90*d.DEGTORAD,[0,1,0],d.identityMat4()),t=d.rotationMat4v(270*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xCurveArrow1:s.addChild(new wr(s,{geometry:r.arrowHead,material:o.red,matrix:function(){const e=d.translateMat4c(0,-.07,-.8,d.identityMat4()),t=d.scaleMat4v([.6,.6,.6],d.identityMat4()),i=d.rotationMat4v(0*d.DEGTORAD,[0,0,1],d.identityMat4());return d.mulMat4(d.mulMat4(e,t,d.identityMat4()),i,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xCurveArrow2:s.addChild(new wr(s,{geometry:r.arrowHead,material:o.red,matrix:function(){const e=d.translateMat4c(0,-.8,-.07,d.identityMat4()),t=d.scaleMat4v([.6,.6,.6],d.identityMat4()),i=d.rotationMat4v(90*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(d.mulMat4(e,t,d.identityMat4()),i,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yCurve:s.addChild(new wr(s,{geometry:r.curve,material:o.green,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),yCurveHandle:s.addChild(new wr(s,{geometry:r.curveHandle,material:o.pickable,rotation:[-90,0,0],pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),yCurveArrow1:s.addChild(new wr(s,{geometry:r.arrowHead,material:o.green,matrix:function(){const e=d.translateMat4c(.07,0,-.8,d.identityMat4()),t=d.scaleMat4v([.6,.6,.6],d.identityMat4()),i=d.rotationMat4v(90*d.DEGTORAD,[0,0,1],d.identityMat4());return d.mulMat4(d.mulMat4(e,t,d.identityMat4()),i,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yCurveArrow2:s.addChild(new wr(s,{geometry:r.arrowHead,material:o.green,matrix:function(){const e=d.translateMat4c(.8,0,-.07,d.identityMat4()),t=d.scaleMat4v([.6,.6,.6],d.identityMat4()),i=d.rotationMat4v(90*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(d.mulMat4(e,t,d.identityMat4()),i,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurve:s.addChild(new wr(s,{geometry:r.curve,material:o.blue,matrix:d.rotationMat4v(180*d.DEGTORAD,[1,0,0],d.identityMat4()),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveHandle:s.addChild(new wr(s,{geometry:r.curveHandle,material:o.pickable,matrix:d.rotationMat4v(180*d.DEGTORAD,[1,0,0],d.identityMat4()),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveCurveArrow1:s.addChild(new wr(s,{geometry:r.arrowHead,material:o.blue,matrix:function(){const e=d.translateMat4c(.8,-.07,0,d.identityMat4()),t=d.scaleMat4v([.6,.6,.6],d.identityMat4());return d.mulMat4(e,t,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveArrow2:s.addChild(new wr(s,{geometry:r.arrowHead,material:o.blue,matrix:function(){const e=d.translateMat4c(.05,-.8,0,d.identityMat4()),t=d.scaleMat4v([.6,.6,.6],d.identityMat4()),i=d.rotationMat4v(90*d.DEGTORAD,[0,0,1],d.identityMat4());return d.mulMat4(d.mulMat4(e,t,d.identityMat4()),i,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),center:s.addChild(new wr(s,{geometry:new ei(s,Mr({radius:.05})),material:o.center,pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisArrow:s.addChild(new wr(s,{geometry:r.arrowHead,material:o.red,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[0,0,1],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisArrowHandle:s.addChild(new wr(s,{geometry:r.arrowHeadHandle,material:o.pickable,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[0,0,1],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxis:s.addChild(new wr(s,{geometry:r.axis,material:o.red,matrix:function(){const e=d.translateMat4c(0,.5,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[0,0,1],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisHandle:s.addChild(new wr(s,{geometry:r.axisHandle,material:o.pickable,matrix:function(){const e=d.translateMat4c(0,.5,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[0,0,1],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrow:s.addChild(new wr(s,{geometry:r.arrowHead,material:o.green,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(180*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrowHandle:s.addChild(new wr(s,{geometry:r.arrowHeadHandle,material:o.pickable,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(180*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,opacity:.2,isObject:!1}),e),yShaft:s.addChild(new wr(s,{geometry:r.axis,material:o.green,position:[0,-.5,0],pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yShaftHandle:s.addChild(new wr(s,{geometry:r.axisHandle,material:o.pickable,position:[0,-.5,0],pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrow:s.addChild(new wr(s,{geometry:r.arrowHead,material:o.blue,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[.8,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrowHandle:s.addChild(new wr(s,{geometry:r.arrowHeadHandle,material:o.pickable,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[.8,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zShaft:s.addChild(new wr(s,{geometry:r.axis,material:o.blue,matrix:function(){const e=d.translateMat4c(0,.5,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),clippable:!1,pickable:!1,collidable:!0,visible:!1,isObject:!1}),e),zAxisHandle:s.addChild(new wr(s,{geometry:r.axisHandle,material:o.pickable,matrix:function(){const e=d.translateMat4c(0,.5,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),clippable:!1,pickable:!0,collidable:!0,visible:!1,isObject:!1}),e)},this._affordanceMeshes={planeFrame:s.addChild(new wr(s,{geometry:new ei(s,go({center:[0,0,0],radius:2,tube:i,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new oi(s,{ambient:[1,1,1],diffuse:[0,0,0],emissive:[1,1,0]}),highlighted:!0,highlightMaterial:new ai(s,{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],isObject:!1}),e),xHoop:s.addChild(new wr(s,{geometry:r.hoop,material:o.red,highlighted:!0,highlightMaterial:o.highlightRed,matrix:function(){const e=d.rotationMat4v(90*d.DEGTORAD,[0,1,0],d.identityMat4()),t=d.rotationMat4v(270*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yHoop:s.addChild(new wr(s,{geometry:r.hoop,material:o.green,highlighted:!0,highlightMaterial:o.highlightGreen,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zHoop:s.addChild(new wr(s,{geometry:r.hoop,material:o.blue,highlighted:!0,highlightMaterial:o.highlightBlue,matrix:d.rotationMat4v(180*d.DEGTORAD,[1,0,0],d.identityMat4()),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xAxisArrow:s.addChild(new wr(s,{geometry:r.arrowHeadBig,material:o.red,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[0,0,1],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrow:s.addChild(new wr(s,{geometry:r.arrowHeadBig,material:o.green,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(180*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrow:s.addChild(new wr(s,{geometry:r.arrowHeadBig,material:o.blue,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[.8,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e)}}_bindEvents(){const e=this;var t=!1;const i=-1,s=0,r=1,o=2,n=3,a=4,l=5,A=this._rootNode;var h=null,c=null;const u=d.vec2(),p=d.vec3([1,0,0]),f=d.vec3([0,1,0]),g=d.vec3([0,0,1]),m=this._viewer.scene.canvas.canvas,_=this._viewer.camera,v=this._viewer.scene;{const e=d.vec3([0,0,0]);let t=-1;this._onCameraViewMatrix=v.camera.on("viewMatrix",(()=>{})),this._onCameraProjMatrix=v.camera.on("projMatrix",(()=>{})),this._onSceneTick=v.on("tick",(()=>{const i=Math.abs(d.lenVec3(d.subVec3(v.camera.eye,this._pos,e)));if(i!==t&&"perspective"===_.projection){const e=.07*(Math.tan(_.perspective.fov*d.DEGTORAD)*i);A.scale=[e,e,e],t=i}if("ortho"===_.projection){const e=_.ortho.scale/10;A.scale=[e,e,e],t=i}}))}const b=function(){const e=new Float64Array(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}}(),y=function(){const t=d.mat4();return function(i,s){return d.quaternionToMat4(e._rootNode.quaternion,t),d.transformVec3(t,i,s),d.normalizeVec3(s),s}}();var x=function(){const e=d.vec3();return function(t){const i=Math.abs(t[0]);return i>Math.abs(t[1])&&i>Math.abs(t[2])?d.cross3Vec3(t,[0,1,0],e):d.cross3Vec3(t,[1,0,0],e),d.cross3Vec3(e,t,e),d.normalizeVec3(e),e}}();const B=function(){const t=d.vec3(),i=d.vec3(),s=d.vec4();return function(r,o,n){y(r,s);const a=x(s,o,n);P(o,a,t),P(n,a,i),d.subVec3(i,t);const l=d.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 w=function(){const t=d.vec4(),i=d.vec4(),s=d.vec4(),r=d.vec4();return function(o,n,a){y(o,r);if(!(P(n,r,t)&&P(a,r,i))){const e=x(r,n,a);P(n,e,t,1),P(a,e,i,1);var l=d.dotVec3(t,r);t[0]-=l*r[0],t[1]-=l*r[1],t[2]-=l*r[2],l=d.dotVec3(i,r),i[0]-=l*r[0],i[1]-=l*r[1],i[2]-=l*r[2]}d.normalizeVec3(t),d.normalizeVec3(i),l=d.dotVec3(t,i),l=d.clamp(l,-1,1);var A=Math.acos(l)*d.RADTODEG;d.cross3Vec3(t,i,s),d.dotVec3(s,r)<0&&(A=-A),e._rootNode.rotate(o,A),C()}}(),P=function(){const t=d.vec4([0,0,0,1]),i=d.mat4();return function(s,r,o,n){n=n||0,t[0]=s[0]/m.width*2-1,t[1]=-(s[1]/m.height*2-1),t[2]=0,t[3]=1,d.mulMat4(_.projMatrix,_.viewMatrix,i),d.inverseMat4(i),d.transformVec4(i,t,t),d.mulVec4Scalar(t,1/t[3]);var a=_.eye;d.subVec4(t,a,t);const l=e._sectionPlane.pos;var A=-d.dotVec3(l,r)-n,h=d.dotVec3(r,t);if(Math.abs(h)>.005){var c=-(d.dotVec3(r,a)+A)/h;return d.mulVec3Scalar(t,c,o),d.addVec3(o,a),d.subVec3(o,l,o),!0}return!1}}();const C=function(){const t=d.vec3(),i=d.mat4();return function(){e.sectionPlane&&(d.quaternionToMat4(A.quaternion,i),d.transformVec3(i,[0,0,1],t),e._setSectionPlaneDir(t))}}();var M,E=!1;this._onCameraControlHover=this._viewer.cameraControl.on("hoverEnter",(e=>{if(!this._visible)return;if(E)return;var A;t=!1,M&&(M.visible=!1);switch(e.entity.id){case this._displayMeshes.xAxisArrowHandle.id:case this._displayMeshes.xAxisHandle.id:A=this._affordanceMeshes.xAxisArrow,h=s;break;case this._displayMeshes.yAxisArrowHandle.id:case this._displayMeshes.yShaftHandle.id:A=this._affordanceMeshes.yAxisArrow,h=r;break;case this._displayMeshes.zAxisArrowHandle.id:case this._displayMeshes.zAxisHandle.id:A=this._affordanceMeshes.zAxisArrow,h=o;break;case this._displayMeshes.xCurveHandle.id:A=this._affordanceMeshes.xHoop,h=n;break;case this._displayMeshes.yCurveHandle.id:A=this._affordanceMeshes.yHoop,h=a;break;case this._displayMeshes.zCurveHandle.id:A=this._affordanceMeshes.zHoop,h=l;break;default:return void(h=i)}A&&(A.visible=!0),M=A,t=!0})),this._onCameraControlHoverLeave=this._viewer.cameraControl.on("hoverOutEntity",(e=>{this._visible&&(M&&(M.visible=!1),M=null,h=i)})),m.addEventListener("mousedown",this._canvasMouseDownListener=e=>{if(e.preventDefault(),this._visible&&t&&(this._viewer.cameraControl.pointerEnabled=!1,1===e.which)){E=!0;var i=b(e);c=h,u[0]=i[0],u[1]=i[1]}}),m.addEventListener("mousemove",this._canvasMouseMoveListener=e=>{if(!this._visible)return;if(!E)return;var t=b(e);const i=t[0],A=t[1];switch(c){case s:B(p,u,t);break;case r:B(f,u,t);break;case o:B(g,u,t);break;case n:w(p,u,t);break;case a:w(f,u,t);break;case l:w(g,u,t)}u[0]=i,u[1]=A}),m.addEventListener("mouseup",this._canvasMouseUpListener=e=>{this._visible&&(this._viewer.cameraControl.pointerEnabled=!0,E&&(e.which,E=!1,t=!1))}),m.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._setSectionPlane(null),this._rootNode.destroy(),this._displayMeshes={},this._affordanceMeshes={}}}class nC{constructor(e,t,i){this.id=i.id,this._sectionPlane=i,this._mesh=new wr(t,{id:i.id,geometry:new ei(t,ti({xSize:.5,ySize:.5,zSize:.001})),material:new oi(t,{emissive:[1,1,1],diffuse:[0,0,0],backfaces:!1}),edgeMaterial:new Ai(t,{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),highlightMaterial:new ai(t,{fill:!0,fillColor:[.5,1,.5],fillAlpha:.7,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),selectedMaterial:new ai(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=d.vec3([0,0,0]),t=d.vec3(),i=d.vec3([0,0,1]),s=d.vec4(4),r=d.vec3(),o=()=>{const o=this._sectionPlane.scene.center,n=[-this._sectionPlane.dir[0],-this._sectionPlane.dir[1],-this._sectionPlane.dir[2]];d.subVec3(o,this._sectionPlane.pos,e);const a=-d.dotVec3(n,e);d.normalizeVec3(n),d.mulVec3Scalar(n,a,t);const l=d.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 aC{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 vi(this._viewer,{canvasId:this._canvas.id,transparent:!0}),this._scene.clearLights(),new Vt(this._scene,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new Vt(this._scene,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new Vt(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=d.rotationMat4c(-90*d.DEGTORAD,1,0,0),i=d.vec3(),s=d.vec3(),r=d.vec3();this._synchCamera=()=>{const o=this._viewer.camera.eye,n=this._viewer.camera.look,a=this._viewer.camera.up;d.mulVec3Scalar(d.normalizeVec3(d.subVec3(o,n,i)),7),this._zUp?(d.transformVec3(t,i,s),d.transformVec3(t,a,r),e.look=[0,0,0],e.eye=d.transformVec3(t,i,s),e.up=d.transformPoint3(t,a,r)):(e.look=[0,0,0],e.eye=i,e.up=a)}}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}));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 nC(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._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 lC=d.AABB3(),AC=d.vec3();class hC extends z{constructor(e,t={}){if(super("SectionPlanes",e),this._freeControls=[],this._sectionPlanes=e.scene.sectionPlanes,this._controls={},this._shownControlId=null,null!==t.overviewCanvasId&&void 0!==t.overviewCanvasId){const e=document.getElementById(t.overviewCanvasId);e?this._overview=new aC(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;lC.set(this.viewer.scene.aabb),d.getAABB3Center(lC,AC),lC[0]+=t[0]-AC[0],lC[1]+=t[1]-AC[1],lC[2]+=t[2]-AC[2],lC[3]+=t[0]-AC[0],lC[4]+=t[1]-AC[1],lC[5]+=t[2]-AC[2],this.viewer.cameraFlight.flyTo({aabb:lC,fitFOV:65})},onClickedNothing:()=>{this.hideControl()}}):this.warn("Can't find overview canvas: '"+t.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={}){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);return new Dr(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 oC(this);t._setSectionPlane(e),t.setVisible(!1),this._controls[e.id]=t,this._overview&&this._overview.addSectionPlane(e),e.once("destroyed",(()=>{this._sectionPlaneDestroyed(e)}))}flipSectionPlanes(){const e=this.viewer.scene.sectionPlanes;for(let t in e){e[t].flipDir()}}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{this._registerModelStoreys(e),this.fire("storeys",this.storeys)}))}_registerModelStoreys(e){const t=this.viewer,i=t.scene,s=t.metaScene,r=s.metaModels[e],o=i.models[e];if(!r||!r.rootMetaObjects)return;const n=r.rootMetaObjects;for(let t=0,r=n.length;t.5?a.length:0,h=new cC(this,o.aabb,l,e,n,A);h._onModelDestroyed=o.once("destroyed",(()=>{this._deregisterModelStoreys(e),this.fire("storeys",this.storeys)})),this.storeys[n]=h,this.modelStoreys[e]||(this.modelStoreys[e]={}),this.modelStoreys[e][n]=h}}}_deregisterModelStoreys(e){const t=this.modelStoreys[e];if(t){const i=this.viewer.scene;for(let e in t)if(t.hasOwnProperty(e)){const s=t[e],r=i.models[s.modelId];r&&r.off(s._onModelDestroyed),delete this.storeys[e]}delete this.modelStoreys[e]}}get fitStoreyMaps(){return this._fitStoreyMaps}gotoStoreyCamera(e,t={}){const i=this.storeys[e];if(!i)return this.error("IfcBuildingStorey not found with this ID: "+e),void(t.done&&t.done());const s=this.viewer,r=s.scene.camera,o=i.storeyAABB;if(o[3]{t.done()})):(s.cameraFlight.jumpTo(y.apply(t,{eye:h,look:n,up:c,orthoScale:A})),s.camera.ortho.scale=A)}showStoreyObjects(e,t={}){if(!this.storeys[e])return void this.error("IfcBuildingStorey not found with this ID: "+e);const i=this.viewer,s=i.scene;i.metaScene.metaObjects[e]&&(t.hideOthers&&s.setObjectsVisible(i.scene.visibleObjectIds,!1),this.withStoreyObjects(e,((e,t)=>{e&&(e.visible=!0)})))}withStoreyObjects(e,t){const i=this.viewer,s=i.scene,r=i.metaScene,o=r.metaObjects[e];if(!o)return;const n=o.getObjectIDsInSubtree();for(var a=0,l=n.length;athis.storeys[i[1]].storeyAABB[4]?i[1]:null}worldPosToStoreyMap(e,t,i){const s=e.storeyId,r=this.storeys[s];if(!r)return this.error("IfcBuildingStorey not found with this ID: "+s),!1;const o=this._fitStoreyMaps?r.storeyAABB:r.modelAABB,n=o[0],a=o[1],l=o[2],A=o[3]-n,h=o[4]-a,c=o[5]-l,u=this.viewer.camera.worldUp,d=u[0]>u[1]&&u[0]>u[2],p=!d&&u[1]>u[0]&&u[1]>u[2];!d&&!p&&u[2]>u[0]&&(u[2],u[1]);const f=e.width/A,g=p?e.height/c:e.height/h;return i[0]=Math.floor(e.width-(t[0]-n)*f),i[1]=Math.floor(e.height-(t[2]-l)*g),i[0]>=0&&i[0]=0&&i[1]<=e.height}worldDirToStoreyMap(e,t,i){const s=this.viewer.camera,r=s.eye,o=s.look,n=d.subVec3(o,r,dC),a=s.worldUp,l=a[0]>a[1]&&a[0]>a[2],A=!l&&a[1]>a[0]&&a[1]>a[2];!l&&!A&&a[2]>a[0]&&(a[2],a[1]),l?(i[0]=n[1],i[1]=n[2]):A?(i[0]=n[0],i[1]=n[2]):(i[0]=n[0],i[1]=n[1]),d.normalizeVec2(i)}destroy(){this.viewer.scene.off(this._onModelLoaded),super.destroy()}}const gC=new Float64Array([0,0,1]),mC=new Float64Array(4);class _C{constructor(e){this.id=null,this._viewer=e.viewer,this._plugin=e,this._visible=!1,this._pos=d.vec3(),this._origin=d.vec3(),this._rtcPos=d.vec3(),this._baseDir=d.vec3(),this._rootNode=null,this._displayMeshes=null,this._affordanceMeshes=null,this._ignoreNextSectionPlaneDirUpdate=!1,this._createNodes(),this._bindEvents()}_setSectionPlane(e){this._sectionPlane&&(this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._onSectionPlanePos=null,this._onSectionPlaneDir=null,this._sectionPlane=null),e&&(this.id=e.id,this._setPos(e.pos),this._setDir(e.dir),this._sectionPlane=e,this._onSectionPlanePos=e.on("pos",(()=>{this._setPos(this._sectionPlane.pos)})),this._onSectionPlaneDir=e.on("dir",(()=>{this._ignoreNextSectionPlaneDirUpdate?this._ignoreNextSectionPlaneDirUpdate=!1:this._setDir(this._sectionPlane.dir)})))}get sectionPlane(){return this._sectionPlane}_setPos(e){this._pos.set(e),Y(this._pos,this._origin,this._rtcPos),this._rootNode.origin=this._origin,this._rootNode.position=this._rtcPos}_setDir(e){this._baseDir.set(e),this._rootNode.quaternion=d.vec3PairToQuaternion(gC,e,mC)}_setSectionPlaneDir(e){this._sectionPlane&&(this._ignoreNextSectionPlaneDirUpdate=!0,this._sectionPlane.dir=e)}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=!1,t=this._viewer.scene,i=.01;this._rootNode=new Vr(t,{position:[0,0,0],scale:[5,5,5]});const s=this._rootNode,r={arrowHead:new ei(s,Cr({radiusTop:.001,radiusBottom:.07,radialSegments:32,heightSegments:1,height:.2,openEnded:!1})),arrowHeadBig:new ei(s,Cr({radiusTop:.001,radiusBottom:.09,radialSegments:32,heightSegments:1,height:.25,openEnded:!1})),axis:new ei(s,Cr({radiusTop:i,radiusBottom:i,radialSegments:20,heightSegments:1,height:1,openEnded:!1}))},o={red:new oi(s,{diffuse:[1,0,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),green:new oi(s,{diffuse:[0,1,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),blue:new oi(s,{diffuse:[0,0,1],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightRed:new ai(s,{edges:!1,fill:!0,fillColor:[1,0,0],fillAlpha:.6})};this._displayMeshes={plane:s.addChild(new wr(s,{geometry:new ei(s,{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 oi(s,{emissive:[0,0,0],diffuse:[0,0,0],backfaces:!0}),opacity:.6,ghosted:!0,pickable:!1,collidable:!0,clippable:!1,visible:!1,scale:[2.4,2.4,1]}),e),planeFrame:s.addChild(new wr(s,{geometry:new ei(s,go({center:[0,0,0],radius:1.7,tube:.02,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new oi(s,{emissive:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],shininess:0}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,.1],rotation:[0,0,45]}),e),center:s.addChild(new wr(s,{geometry:new ei(s,Mr({radius:.05})),material:o.center,pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),zAxisArrow:s.addChild(new wr(s,{geometry:r.arrowHead,material:o.blue,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[.8,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),zShaft:s.addChild(new wr(s,{geometry:r.axis,material:o.blue,matrix:function(){const e=d.translateMat4c(0,.5,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[1,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),clippable:!1,pickable:!1,collidable:!0,visible:!1}),e)},this._affordanceMeshes={planeFrame:s.addChild(new wr(s,{geometry:new ei(s,go({center:[0,0,0],radius:2,tube:i,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new oi(s,{ambient:[1,1,1],diffuse:[0,0,0],emissive:[1,1,0]}),highlighted:!0,highlightMaterial:new ai(s,{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]}),e),zAxisArrow:s.addChild(new wr(s,{geometry:r.arrowHeadBig,material:o.blue,matrix:function(){const e=d.translateMat4c(0,1.1,0,d.identityMat4()),t=d.rotationMat4v(-90*d.DEGTORAD,[.8,0,0],d.identityMat4());return d.mulMat4(t,e,d.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e)}}_bindEvents(){const e=this._rootNode,t=d.vec2(),i=this._viewer.camera,s=this._viewer.scene;let r=0,o=!1;{const t=d.vec3([0,0,0]);let n=-1;this._onCameraViewMatrix=s.camera.on("viewMatrix",(()=>{})),this._onCameraProjMatrix=s.camera.on("projMatrix",(()=>{})),this._onSceneTick=s.on("tick",(()=>{o=!1;const l=Math.abs(d.lenVec3(d.subVec3(s.camera.eye,this._pos,t)));if(l!==n&&"perspective"===i.projection){const t=.07*(Math.tan(i.perspective.fov*d.DEGTORAD)*l);e.scale=[t,t,t],n=l}if("ortho"===i.projection){const t=i.ortho.scale/10;e.scale=[t,t,t],n=l}0!==r&&(a(r),r=0)}))}const n=function(){const e=new Float64Array(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}}(),a=e=>{const t=this._sectionPlane.pos,i=this._sectionPlane.dir;d.addVec3(t,d.mulVec3Scalar(i,.1*e*this._plugin.getDragSensitivity(),d.vec3())),this._sectionPlane.pos=t};{let e=!1;this._plugin._controlElement.addEventListener("mousedown",this._canvasMouseDownListener=i=>{if(i.preventDefault(),this._visible&&(this._viewer.cameraControl.pointerEnabled=!1,1===i.which)){e=!0;var s=n(i);t[0]=s[0],t[1]=s[1]}}),this._plugin._controlElement.addEventListener("mousemove",this._canvasMouseMoveListener=i=>{if(!this._visible)return;if(!e)return;if(o)return;var s=n(i);const r=s[0],l=s[1];a(l-t[1]),t[0]=r,t[1]=l}),this._plugin._controlElement.addEventListener("mouseup",this._canvasMouseUpListener=t=>{this._visible&&(this._viewer.cameraControl.pointerEnabled=!0,e&&(t.which,e=!1))}),this._plugin._controlElement.addEventListener("wheel",this._canvasWheelListener=e=>{this._visible&&(r+=Math.max(-1,Math.min(1,40*-e.deltaY)))})}{let e,t,i=null;this._plugin._controlElement.addEventListener("touchstart",this._handleTouchStart=t=>{t.stopPropagation(),t.preventDefault(),this._visible&&(e=t.touches[0].clientY,i=e,r=0)}),this._plugin._controlElement.addEventListener("touchmove",this._handleTouchMove=e=>{e.stopPropagation(),e.preventDefault(),this._visible&&(o||(o=!0,t=e.touches[0].clientY,null!==i&&(r+=t-i),i=t))}),this._plugin._controlElement.addEventListener("touchend",this._handleTouchEnd=i=>{i.stopPropagation(),i.preventDefault(),this._visible&&(e=null,t=null,r=0)})}}_destroy(){this._unbindEvents(),this._destroyNodes()}_unbindEvents(){const e=this._viewer,t=e.scene,i=t.canvas.canvas,s=e.camera,r=this._plugin._controlElement;t.off(this._onSceneTick),i.removeEventListener("mousedown",this._canvasMouseDownListener),i.removeEventListener("mousemove",this._canvasMouseMoveListener),i.removeEventListener("mouseup",this._canvasMouseUpListener),i.removeEventListener("wheel",this._canvasWheelListener),r.removeEventListener("touchstart",this._handleTouchStart),r.removeEventListener("touchmove",this._handleTouchMove),r.removeEventListener("touchend",this._handleTouchEnd),s.off(this._onCameraViewMatrix),s.off(this._onCameraProjMatrix)}_destroyNodes(){this._setSectionPlane(null),this._rootNode.destroy(),this._displayMeshes={},this._affordanceMeshes={}}}class vC{constructor(e,t,i){this.id=i.id,this._sectionPlane=i,this._mesh=new wr(t,{id:i.id,geometry:new ei(t,ti({xSize:.5,ySize:.5,zSize:.001})),material:new oi(t,{emissive:[1,1,1],diffuse:[0,0,0],backfaces:!1}),edgeMaterial:new Ai(t,{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),highlightMaterial:new ai(t,{fill:!0,fillColor:[.5,1,.5],fillAlpha:.7,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),selectedMaterial:new ai(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=d.vec3([0,0,0]),t=d.vec3(),i=d.vec3([0,0,1]),s=d.vec4(4),r=d.vec3(),o=()=>{const o=this._sectionPlane.scene.center,n=[-this._sectionPlane.dir[0],-this._sectionPlane.dir[1],-this._sectionPlane.dir[2]];d.subVec3(o,this._sectionPlane.pos,e);const a=-d.dotVec3(n,e);d.normalizeVec3(n),d.mulVec3Scalar(n,a,t);const l=d.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 bC{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 vi(this._viewer,{canvasId:this._canvas.id,transparent:!0}),this._scene.clearLights(),new Vt(this._scene,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new Vt(this._scene,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new Vt(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=d.rotationMat4c(-90*d.DEGTORAD,1,0,0),i=d.vec3(),s=d.vec3(),r=d.vec3();this._synchCamera=()=>{const o=this._viewer.camera.eye,n=this._viewer.camera.look,a=this._viewer.camera.up;d.mulVec3Scalar(d.normalizeVec3(d.subVec3(o,n,i)),7),this._zUp?(d.transformVec3(t,i,s),d.transformVec3(t,a,r),e.look=[0,0,0],e.eye=d.transformVec3(t,i,s),e.up=d.transformPoint3(t,a,r)):(e.look=[0,0,0],e.eye=i,e.up=a)}}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}));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 vC(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._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 yC=d.AABB3(),xC=d.vec3();class BC extends z{constructor(e,t={}){if(super("FaceAlignedSectionPlanesPlugin",e),this._freeControls=[],this._sectionPlanes=e.scene.sectionPlanes,this._controls={},this._shownControlId=null,this._dragSensitivity=t.dragSensitivity||1,null!==t.overviewCanvasId&&void 0!==t.overviewCanvasId){const e=document.getElementById(t.overviewCanvasId);e?this._overview=new bC(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;yC.set(this.viewer.scene.aabb),d.getAABB3Center(yC,xC),yC[0]+=t[0]-xC[0],yC[1]+=t[1]-xC[1],yC[2]+=t[2]-xC[2],yC[3]+=t[0]-xC[0],yC[4]+=t[1]-xC[1],yC[5]+=t[2]-xC[2],this.viewer.cameraFlight.flyTo({aabb:yC,fitFOV:65})},onClickedNothing:()=>{this.hideControl()}}):this.warn("Can't find overview canvas: '"+t.overviewCanvasId+"' - will create plugin without overview")}null===t.controlElementId||void 0===t.controlElementId?this.error("Parameter expected: controlElementId"):(this._controlElement=document.getElementById(t.controlElementId),this._controlElement||this.warn("Can't find control element: '"+t.controlElementId+"' - will create plugin without control element")),this._onSceneSectionPlaneCreated=e.scene.on("sectionPlaneCreated",(e=>{this._sectionPlaneCreated(e)}))}setDragSensitivity(e){this._dragSensitivity=e||1}getDragSensitivity(){return this._dragSensitivity}setOverviewVisible(e){this._overview&&this._overview.setVisible(e)}getOverviewVisible(){if(this._overview)return this._overview.getVisible()}get sectionPlanes(){return this._sectionPlanes}createSectionPlane(e={}){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);return new Dr(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 _C(this);t._setSectionPlane(e),t.setVisible(!1),this._controls[e.id]=t,this._overview&&this._overview.addSectionPlane(e),e.once("destroyed",(()=>{this._sectionPlaneDestroyed(e)}))}flipSectionPlanes(){const e=this.viewer.scene.sectionPlanes;for(let t in e){e[t].flipDir()}}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(let 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){let 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(let t=0,i=e.length;t-1?e+"&_="+t:e+"?_="+t}getSTL(e,t,i){e=this._cacheBusterURL(e);const s=new XMLHttpRequest;s.overrideMimeType("application/json"),s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i(s.statusText))},s.send(null)}}const CC=d.vec3();class MC{load(e,t,i,s,r,o){s=s||{};const n=e.viewer.scene.canvas.spinner;n.processes++,e.dataSource.getSTL(i,(function(i){!function(e,t,i,s){try{const r=TC(i);EC(r)?FC(e,r,t,s):IC(e,SC(i),t,s)}catch(e){t.fire("error",e)}}(e,t,i,s);try{const o=TC(i);EC(o)?FC(e,o,t,s):IC(e,SC(i),t,s),n.processes--,I.scheduleTask((function(){t.fire("loaded",!0,!1)})),r&&r()}catch(i){n.processes--,e.error(i),o&&o(i),t.fire("error",i)}}),(function(i){n.processes--,e.error(i),o&&o(i),t.fire("error",i)}))}parse(e,t,i,s){const r=e.viewer.scene.canvas.spinner;r.processes++;try{const o=TC(i);EC(o)?FC(e,o,t,s):IC(e,SC(i),t,s),r.processes--,I.scheduleTask((function(){t.fire("loaded",!0,!1)}))}catch(e){r.processes--,t.fire("error",e)}}}function EC(e){const t=new DataView(e);if(84+50*t.getUint32(80,!0)===t.byteLength)return!0;const i=[115,111,108,105,100];for(var s=0;s<5;s++)if(i[s]!==t.getUint8(s,!1))return!0;return!1}function FC(e,t,i,s){const r=new DataView(t),o=r.getUint32(80,!0);let n,a,l,A,h,c,u,d=!1,p=null,f=null,g=null,m=!1;for(let e=0;e<70;e++)1129270351===r.getUint32(e,!1)&&82===r.getUint8(e+4)&&61===r.getUint8(e+5)&&(d=!0,A=[],h=r.getUint8(e+6)/255,c=r.getUint8(e+7)/255,u=r.getUint8(e+8)/255,r.getUint8(e+9));const _=new zr(i,{roughness:.5});let v=[],b=[],y=s.splitMeshes;for(let e=0;e>5&31)/31,l=(e>>10&31)/31):(n=h,a=c,l=u),(y&&n!==p||a!==f||l!==g)&&(null!==p&&(m=!0),p=n,f=a,g=l)}for(let e=1;e<=3;e++){let i=t+12*e;v.push(r.getFloat32(i,!0)),v.push(r.getFloat32(i+4,!0)),v.push(r.getFloat32(i+8,!0)),b.push(o,x,B),d&&A.push(n,a,l,1)}y&&m&&(DC(i,v,b,A,_,s),v=[],b=[],A=A?[]:null,m=!1)}v.length>0&&DC(i,v,b,A,_,s)}function IC(e,t,i,s){const r=/facet([\s\S]*?)endfacet/g;let o=0;const n=/[\s]+([+-]?(?:\d+.\d+|\d+.|\d+|.\d+)(?:[eE][+-]?\d+)?)/.source,a=new RegExp("vertex"+n+n+n,"g"),l=new RegExp("normal"+n+n+n,"g"),A=[],h=[];let c,u,d,p,f,g,m;for(;null!==(p=r.exec(t));){for(f=0,g=0,m=p[0];null!==(p=l.exec(m));)c=parseFloat(p[1]),u=parseFloat(p[2]),d=parseFloat(p[3]),g++;for(;null!==(p=a.exec(m));)A.push(parseFloat(p[1]),parseFloat(p[2]),parseFloat(p[3])),h.push(c,u,d),f++;1!==g&&e.error("Error in normal of face "+o),3!==f&&e.error("Error in positions of face "+o),o++}DC(i,A,h,null,new zr(i,{roughness:.5}),s)}function DC(e,t,i,s,r,o){const n=new Int32Array(t.length/3);for(let e=0,t=n.length;e0?i:null,s=s&&s.length>0?s:null,o.smoothNormals&&d.faceToVertexNormals(t,i,o);const a=CC;Z(t,t,a);const l=new ei(e,{primitive:"triangles",positions:t,normals:i,colors:s,indices:n}),A=new wr(e,{origin:0!==a[0]||0!==a[1]||0!==a[2]?a:null,geometry:l,material:r,edges:o.edges});e.addChild(A)}function SC(e){return"string"!=typeof e?function(e){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let i=0,s=e.length;i0){const i=document.createElement("a");i.href="#",i.id=`switch-${e.nodeId}`,i.textContent="+",i.classList.add("plus"),t&&i.addEventListener("click",t),o.appendChild(i)}const n=document.createElement("input");n.id=`checkbox-${e.nodeId}`,n.type="checkbox",n.checked=e.checked,n.style["pointer-events"]="all",i&&n.addEventListener("change",i),o.appendChild(n);const a=document.createElement("span");return a.textContent=e.title,o.appendChild(a),s&&(a.oncontextmenu=s),r&&(a.onclick=r),o}createDisabledNodeElement(e){const t=document.createElement("li"),i=document.createElement("a");i.href="#",i.textContent="!",i.classList.add("warn"),i.classList.add("warning"),t.appendChild(i);const s=document.createElement("span");return s.textContent=e,t.appendChild(s),t}addChildren(e,t){const i=document.createElement("ul");t.forEach((e=>{i.appendChild(e)})),e.parentElement.appendChild(i)}expand(e,t,i){e.classList.remove("plus"),e.classList.add("minus"),e.textContent="-",e.removeEventListener("click",t),e.addEventListener("click",i)}collapse(e,t,i){if(!e)return;const s=e.parentElement;if(!s)return;const r=s.querySelector("ul");r&&(s.removeChild(r),e.classList.remove("minus"),e.classList.add("plus"),e.textContent="+",e.removeEventListener("click",i),e.addEventListener("click",t))}isExpanded(e){return void 0!==e.parentElement.getElementsByTagName("li")[0]}getId(e){return e.parentElement.id}getIdFromCheckbox(e){return e.id.replace("checkbox-","")}getSwitchElement(e){return document.getElementById(`switch-${e}`)}isChecked(e){return e.checked}setCheckbox(e,t,i=!1){const s=document.getElementById(`checkbox-${e}`);s&&(t!==s.checked&&(s.checked=t),i!==s.indeterminate&&(s.indeterminate=i,i&&(s.checked=!1)))}setXRayed(e,t){const i=document.getElementById(e);i&&(t?i.classList.add("xrayed-node"):i.classList.remove("xrayed-node"))}setHighlighted(e,t){const i=document.getElementById(e);i&&(t?(i.scrollIntoView({block:"center"}),i.classList.add("highlighted-node")):i.classList.remove("highlighted-node"))}}const UC=[];class OC extends z{constructor(e,t={}){super("TreeViewPlugin",e),this.errors=[],this.valid=!0;const i=t.containerElement||document.getElementById(t.containerElementId);if(i instanceof HTMLElement){for(let e=0;;e++)if(!UC[e]){UC[e]=this,this._index=e,this._id=`tree-${e}`;break}if(this._containerElement=i,this._metaModels={},this._autoAddModels=!1!==t.autoAddModels,this._autoExpandDepth=t.autoExpandDepth||0,this._sortNodes=!1!==t.sortNodes,this._viewer=e,this._rootElement=null,this._muteSceneEvents=!1,this._muteTreeEvents=!1,this._rootNodes=[],this._objectNodes={},this._nodeNodes={},this._rootNames={},this._sortNodes=t.sortNodes,this._pruneEmptyNodes=t.pruneEmptyNodes,this._showListItemElementId=null,this._renderService=t.renderService||new LC,this._showIndeterminate=t.showIndeterminate??!1,!this._renderService)throw new Error("TreeViewPlugin: no render service set");if(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--,this._renderService.setCheckbox(i.nodeId,s);let r=i.parent;for(;r;){r.checked=s,s?r.numVisibleEntities++:r.numVisibleEntities--;const e=this._showIndeterminate&&r.numVisibleEntities>0&&r.numVisibleEntities0,e),r=r.parent}this._muteTreeEvents=!1})),this._onObjectXrayed=this._viewer.scene.on("objectXRayed",(e=>{if(this._muteSceneEvents)return;const t=e.id,i=this._objectNodes[t];if(!i)return;this._muteTreeEvents=!0;const s=e.xrayed;s!==i.xrayed&&(i.xrayed=s,this._renderService.setXRayed(i.nodeId,s),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=this._renderService.isChecked(t),s=this._renderService.getIdFromCheckbox(t),r=this._nodeNodes[s],o=this._viewer.scene.objects;let n=0;this._withNodeTree(r,(e=>{const t=e.objectId,s=o[t],r=0===e.children.length;e.numVisibleEntities=i?e.numEntities:0,r&&i!==e.checked&&n++,e.checked=i,this._renderService.setCheckbox(e.nodeId,i),s&&(s.visible=i)}));let a=r.parent;for(;a;){a.checked=i,i?a.numVisibleEntities+=n:a.numVisibleEntities-=n;const e=this._showIndeterminate&&a.numVisibleEntities>0&&a.numVisibleEntities0,e),a=a.parent}this._muteSceneEvents=!1},this._hierarchy=t.hierarchy||"containment",this._autoExpandDepth=t.autoExpandDepth||0,this._autoAddModels){const e=Object.keys(this.viewer.metaScene.metaModels);for(let t=0,i=e.length;t{this.viewer.metaScene.metaModels[e]&&this.addModel(e)}))}this.hierarchy=t.hierarchy}else this.error("Mandatory config expected: valid containerElementId or 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&&(this._hierarchy=e,this._createNodes())}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._metaModels[e]?this.warn("Model already added: "+e):(this._metaModels[e]=s,t&&t.rootName&&(this._rootNames[e]=t.rootName),i.on("destroyed",(()=>{this.removeModel(i.id)})),this._createNodes()):this.error("MetaModel not found: "+e)}removeModel(e){if(!this._containerElement)return;this._metaModels[e]&&(this._rootNames[e]&&delete this._rootNames[e],delete this._metaModels[e],this._createNodes())}showNode(e){this.unShowNode();const t=this._objectNodes[e];if(!t)return;this.collapse();const i=t.nodeId,s=this._renderService.getSwitchElement(i);if(s)return this._expandSwitchElement(s),s.scrollIntoView(),!0;const r=[];r.unshift(t);let o=t.parent;for(;o;)r.unshift(o),o=o.parent;for(let e=0,t=r.length;e{if(s===e)return;const r=this._renderService.getSwitchElement(i.nodeId);if(r){this._expandSwitchElement(r);const e=i.children;for(var o=0,n=e.length;o0;return this.valid}_validateMetaModelForStoreysHierarchy(e=0,t,i){return!0}_createEnabledNodes(){switch(this._pruneEmptyNodes&&this._findEmptyNodes(),this._hierarchy){case"storeys":this._createStoreysNodes(),0===this._rootNodes.length&&this.error("Failed to build storeys hierarchy");break;case"types":this._createTypesNodes();break;default:this._createContainmentNodes()}this._sortNodes&&this._doSortNodes(),this._synchNodesToEntities(),this._createTrees(),this.expandToDepth(this._autoExpandDepth)}_createDisabledNodes(){const e=this._renderService.createRootNode();this._rootElement=e,this._containerElement.appendChild(e);const t=this._viewer.metaScene.rootMetaObjects;for(let i in t){const s=t[i],r=s.type,o=s.name,n=o&&""!==o&&"Undefined"!==o&&"Default"!==o?o:r,a=this._renderService.createDisabledNodeElement(n);e.appendChild(a)}}_findEmptyNodes(){const e=this._viewer.metaScene.rootMetaObjects;for(let t in e)this._findEmptyNodes2(e[t])}_findEmptyNodes2(e,t=0){const i=this.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{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]s?1:0}_synchNodesToEntities(){const e=Object.keys(this.viewer.metaScene.metaObjects),t=this._viewer.metaScene.metaObjects,i=this._viewer.scene.objects;for(let s=0,r=e.length;sthis._createNodeElement(e))),t=this._renderService.createRootNode();e.forEach((e=>{t.appendChild(e)})),this._containerElement.appendChild(t),this._rootElement=t}_createNodeElement(e){return this._renderService.createNodeElement(e,this._switchExpandHandler,this._checkboxChangeHandler,(t=>{this.fire("contextmenu",{event:t,viewer:this._viewer,treeViewPlugin:this,treeViewNode:e}),t.preventDefault()}),(t=>{this.fire("nodeTitleClicked",{event:t,viewer:this._viewer,treeViewPlugin:this,treeViewNode:e}),t.preventDefault()}))}_expandSwitchElement(e){if(this._renderService.isExpanded(e))return;const t=this._renderService.getId(e),i=this._nodeNodes[t].children.map((e=>this._createNodeElement(e)));this._renderService.addChildren(e,i),this._renderService.expand(e,this._switchExpandHandler,this._switchCollapseHandler)}_collapseNode(e){const t=this._renderService.getSwitchElement(e);this._collapseSwitchElement(t)}_collapseSwitchElement(e){this._renderService.collapse(e,this._switchExpandHandler,this._switchCollapseHandler)}}class kC{constructor(e){this._scene=e,this._objects=[],this._objectsViewCulled=[],this._objectsDetailCulled=[],this._objectsChanged=[],this._objectsChangedList=[],this._modelInfos={},this._numObjects=0,this._lenObjectsChangedList=0,this._dirty=!0,this._onModelLoaded=e.on("modelLoaded",(t=>{const i=e.models[t];i&&this._addModel(i)})),this._onTick=e.on("tick",(()=>{this._dirty&&this._build(),this._applyChanges()}))}_addModel(e){const t={model:e,onDestroyed:e.on("destroyed",(()=>{this._removeModel(e)}))};this._modelInfos[e.id]=t,this._dirty=!0}_removeModel(e){const t=this._modelInfos[e.id];t&&(t.model.off(t.onDestroyed),delete this._modelInfos[e.id],this._dirty=!0)}_build(){if(!this._dirty)return;this._applyChanges();const e=this._scene.objects;for(let e=0;e0){for(let e=0;e{delete NC[t],i._destroy()}))),i}(e.scene),this._maxTreeDepth=t.maxTreeDepth||8,this._modelInfos={},this._frustum=new N,this._kdRoot=null,this._frustumDirty=!1,this._kdTreeDirty=!1,this._onViewMatrix=e.scene.camera.on("viewMatrix",(()=>{this._frustumDirty=!0})),this._onProjMatrix=e.scene.camera.on("projMatMatrix",(()=>{this._frustumDirty=!0})),this._onModelLoaded=e.scene.on("modelLoaded",(e=>{const t=this.viewer.scene.models[e];t&&this._addModel(t)})),this._onSceneTick=e.scene.on("tick",(()=>{this._doCull()}))}set enabled(e){this._enabled=e}get enabled(){return this._enabled}_addModel(e){const t={model:e,onDestroyed:e.on("destroyed",(()=>{this._removeModel(e)}))};this._modelInfos[e.id]=t,this._kdTreeDirty=!0}_removeModel(e){const t=this._modelInfos[e.id];t&&(t.model.off(t.onDestroyed),delete this._modelInfos[e.id],this._kdTreeDirty=!0)}_doCull(){const e=this._frustumDirty||this._kdTreeDirty;if(this._frustumDirty&&this._buildFrustum(),this._kdTreeDirty&&this._buildKDTree(),e){const e=this._kdRoot;e&&this._visitKDNode(e)}}_buildFrustum(){const e=this.viewer.scene.camera;Q(this._frustum,e.viewMatrix,e.projMatrix),this._frustumDirty=!1}_buildKDTree(){const e=this.viewer.scene;this._kdRoot,this._kdRoot={aabb:e.getAABB(),intersection:N.INTERSECT};for(let e=0,t=this._objectCullStates.numObjects;e=this._maxTreeDepth)return e.objects=e.objects||[],e.objects.push(i),void d.expandAABB3(e.aabb,r);if(e.left&&d.containsAABB3(e.left.aabb,r))return void this._insertEntityIntoKDTree(e.left,t,i,s+1);if(e.right&&d.containsAABB3(e.right.aabb,r))return void this._insertEntityIntoKDTree(e.right,t,i,s+1);const o=e.aabb;QC[0]=o[3]-o[0],QC[1]=o[4]-o[1],QC[2]=o[5]-o[2];let n=0;if(QC[1]>QC[n]&&(n=1),QC[2]>QC[n]&&(n=2),!e.left){const a=o.slice();if(a[n+3]=(o[n]+o[n+3])/2,e.left={aabb:a,intersection:N.INTERSECT},d.containsAABB3(a,r))return void this._insertEntityIntoKDTree(e.left,t,i,s+1)}if(!e.right){const a=o.slice();if(a[n]=(o[n]+o[n+3])/2,e.right={aabb:a,intersection:N.INTERSECT},d.containsAABB3(a,r))return void this._insertEntityIntoKDTree(e.right,t,i,s+1)}e.objects=e.objects||[],e.objects.push(i),d.expandAABB3(e.aabb,r)}_visitKDNode(e,t=N.INTERSECT){if(t!==N.INTERSECT&&e.intersects===t)return;t===N.INTERSECT&&(t=V(this._frustum,e.aabb),e.intersects=t);const i=t===N.OUTSIDE,s=e.objects;if(s&&s.length>0)for(let e=0,t=s.length;e-1?e+"&_="+t:e+"?_="+t}getManifest(e,t,i){y.loadJSON(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getMetaModel(e,t,i){y.loadJSON(this._cacheBusterURL(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),i=new Uint8Array(e);for(var n=0;n=0;)e[t]=0}const i=new Uint8Array([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]),s=new Uint8Array([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]),r=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),o=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),n=new Array(576);t(n);const a=new Array(60);t(a);const l=new Array(512);t(l);const A=new Array(256);t(A);const h=new Array(29);t(h);const c=new Array(30);function u(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}let d,p,f;function g(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}t(c);const m=e=>e<256?l[e]:l[256+(e>>>7)],_=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},v=(e,t,i)=>{e.bi_valid>16-i?(e.bi_buf|=t<>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<{v(e,i[2*t],i[2*t+1])},y=(e,t)=>{let i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1},x=(e,t,i)=>{const s=new Array(16);let r,o,n=0;for(r=1;r<=15;r++)n=n+i[r-1]<<1,s[r]=n;for(o=0;o<=t;o++){let t=e[2*o+1];0!==t&&(e[2*o]=y(s[t]++,t))}},B=e=>{let t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},w=e=>{e.bi_valid>8?_(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},P=(e,t,i,s)=>{const r=2*t,o=2*i;return e[r]{const s=e.heap[i];let r=i<<1;for(;r<=e.heap_len&&(r{let o,n,a,l,u=0;if(0!==e.sym_next)do{o=255&e.pending_buf[e.sym_buf+u++],o+=(255&e.pending_buf[e.sym_buf+u++])<<8,n=e.pending_buf[e.sym_buf+u++],0===o?b(e,n,t):(a=A[n],b(e,a+256+1,t),l=i[a],0!==l&&(n-=h[a],v(e,n,l)),o--,a=m(o),b(e,a,r),l=s[a],0!==l&&(o-=c[a],v(e,o,l)))}while(u{const i=t.dyn_tree,s=t.stat_desc.static_tree,r=t.stat_desc.has_stree,o=t.stat_desc.elems;let n,a,l,A=-1;for(e.heap_len=0,e.heap_max=573,n=0;n>1;n>=1;n--)C(e,i,n);l=o;do{n=e.heap[1],e.heap[1]=e.heap[e.heap_len--],C(e,i,1),a=e.heap[1],e.heap[--e.heap_max]=n,e.heap[--e.heap_max]=a,i[2*l]=i[2*n]+i[2*a],e.depth[l]=(e.depth[n]>=e.depth[a]?e.depth[n]:e.depth[a])+1,i[2*n+1]=i[2*a+1]=l,e.heap[1]=l++,C(e,i,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const i=t.dyn_tree,s=t.max_code,r=t.stat_desc.static_tree,o=t.stat_desc.has_stree,n=t.stat_desc.extra_bits,a=t.stat_desc.extra_base,l=t.stat_desc.max_length;let A,h,c,u,d,p,f=0;for(u=0;u<=15;u++)e.bl_count[u]=0;for(i[2*e.heap[e.heap_max]+1]=0,A=e.heap_max+1;A<573;A++)h=e.heap[A],u=i[2*i[2*h+1]+1]+1,u>l&&(u=l,f++),i[2*h+1]=u,h>s||(e.bl_count[u]++,d=0,h>=a&&(d=n[h-a]),p=i[2*h],e.opt_len+=p*(u+d),o&&(e.static_len+=p*(r[2*h+1]+d)));if(0!==f){do{for(u=l-1;0===e.bl_count[u];)u--;e.bl_count[u]--,e.bl_count[u+1]+=2,e.bl_count[l]--,f-=2}while(f>0);for(u=l;0!==u;u--)for(h=e.bl_count[u];0!==h;)c=e.heap[--A],c>s||(i[2*c+1]!==u&&(e.opt_len+=(u-i[2*c+1])*i[2*c],i[2*c+1]=u),h--)}})(e,t),x(i,A,e.bl_count)},F=(e,t,i)=>{let s,r,o=-1,n=t[1],a=0,l=7,A=4;for(0===n&&(l=138,A=3),t[2*(i+1)+1]=65535,s=0;s<=i;s++)r=n,n=t[2*(s+1)+1],++a{let s,r,o=-1,n=t[1],a=0,l=7,A=4;for(0===n&&(l=138,A=3),s=0;s<=i;s++)if(r=n,n=t[2*(s+1)+1],!(++a{v(e,0+(s?1:0),3),w(e),_(e,i),_(e,~i),i&&e.pending_buf.set(e.window.subarray(t,t+i),e.pending),e.pending+=i};var T={_tr_init:e=>{D||((()=>{let e,t,o,g,m;const _=new Array(16);for(o=0,g=0;g<28;g++)for(h[g]=o,e=0;e<1<>=7;g<30;g++)for(c[g]=m<<7,e=0;e<1<{let r,l,A=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0})(e)),E(e,e.l_desc),E(e,e.d_desc),A=(e=>{let t;for(F(e,e.dyn_ltree,e.l_desc.max_code),F(e,e.dyn_dtree,e.d_desc.max_code),E(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*o[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t})(e),r=e.opt_len+3+7>>>3,l=e.static_len+3+7>>>3,l<=r&&(r=l)):r=l=i+5,i+4<=r&&-1!==t?S(e,t,i,s):4===e.strategy||l===r?(v(e,2+(s?1:0),3),M(e,n,a)):(v(e,4+(s?1:0),3),((e,t,i,s)=>{let r;for(v(e,t-257,5),v(e,i-1,5),v(e,s-4,4),r=0;r(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(A[i]+256+1)]++,e.dyn_dtree[2*m(t)]++),e.sym_next===e.sym_end),_tr_align:e=>{v(e,2,3),b(e,256,n),(e=>{16===e.bi_valid?(_(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)}},R=(e,t,i,s)=>{let r=65535&e|0,o=e>>>16&65535|0,n=0;for(;0!==i;){n=i>2e3?2e3:i,i-=n;do{r=r+t[s++]|0,o=o+r|0}while(--n);r%=65521,o%=65521}return r|o<<16|0};const L=new Uint32Array((()=>{let e,t=[];for(var 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})());var U=(e,t,i,s)=>{const r=L,o=s+i;e^=-1;for(let i=s;i>>8^r[255&(e^t[i])];return-1^e},O={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"},k={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_MEM_ERROR:-4,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};const{_tr_init:N,_tr_stored_block:Q,_tr_flush_block:V,_tr_tally:H,_tr_align:j}=T,{Z_NO_FLUSH:G,Z_PARTIAL_FLUSH:z,Z_FULL_FLUSH:W,Z_FINISH:K,Z_BLOCK:X,Z_OK:J,Z_STREAM_END:Y,Z_STREAM_ERROR:Z,Z_DATA_ERROR:q,Z_BUF_ERROR:$,Z_DEFAULT_COMPRESSION:ee,Z_FILTERED:te,Z_HUFFMAN_ONLY:ie,Z_RLE:se,Z_FIXED:re,Z_DEFAULT_STRATEGY:oe,Z_UNKNOWN:ne,Z_DEFLATED:ae}=k,le=258,Ae=262,he=42,ce=113,ue=666,de=(e,t)=>(e.msg=O[t],t),pe=e=>2*e-(e>4?9:0),fe=e=>{let t=e.length;for(;--t>=0;)e[t]=0},ge=e=>{let t,i,s,r=e.w_size;t=e.hash_size,s=t;do{i=e.head[--s],e.head[s]=i>=r?i-r:0}while(--t);t=r,s=t;do{i=e.prev[--s],e.prev[s]=i>=r?i-r:0}while(--t)};let me=(e,t,i)=>(t<{const t=e.state;let i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,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))},ve=(e,t)=>{V(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,_e(e.strm)},be=(e,t)=>{e.pending_buf[e.pending++]=t},ye=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},xe=(e,t,i,s)=>{let r=e.avail_in;return r>s&&(r=s),0===r?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),i),1===e.state.wrap?e.adler=R(e.adler,t,r,i):2===e.state.wrap&&(e.adler=U(e.adler,t,r,i)),e.next_in+=r,e.total_in+=r,r)},Be=(e,t)=>{let i,s,r=e.max_chain_length,o=e.strstart,n=e.prev_length,a=e.nice_match;const l=e.strstart>e.w_size-Ae?e.strstart-(e.w_size-Ae):0,A=e.window,h=e.w_mask,c=e.prev,u=e.strstart+le;let d=A[o+n-1],p=A[o+n];e.prev_length>=e.good_match&&(r>>=2),a>e.lookahead&&(a=e.lookahead);do{if(i=t,A[i+n]===p&&A[i+n-1]===d&&A[i]===A[o]&&A[++i]===A[o+1]){o+=2,i++;do{}while(A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&A[++o]===A[++i]&&on){if(e.match_start=t,n=s,s>=a)break;d=A[o+n-1],p=A[o+n]}}}while((t=c[t&h])>l&&0!=--r);return n<=e.lookahead?n:e.lookahead},we=e=>{const t=e.w_size;let i,s,r;do{if(s=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-Ae)&&(e.window.set(e.window.subarray(t,t+t-s),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),ge(e),s+=t),0===e.strm.avail_in)break;if(i=xe(e.strm,e.window,e.strstart+e.lookahead,s),e.lookahead+=i,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=me(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=me(e,e.ins_h,e.window[r+3-1]),e.prev[r&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=r,r++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead{let i,s,r,o=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,n=0,a=e.strm.avail_in;do{if(i=65535,r=e.bi_valid+42>>3,e.strm.avail_outs+e.strm.avail_in&&(i=s+e.strm.avail_in),i>r&&(i=r),i>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,_e(e.strm),s&&(s>i&&(s=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+s),e.strm.next_out),e.strm.next_out+=s,e.strm.avail_out-=s,e.strm.total_out+=s,e.block_start+=s,i-=s),i&&(xe(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i)}while(0===n);return a-=e.strm.avail_in,a&&(a>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=a&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-a,e.strm.next_in),e.strstart),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.block_start=e.strstart),e.high_waterr&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,r+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),r>e.strm.avail_in&&(r=e.strm.avail_in),r&&(xe(e.strm,e.window,e.strstart,r),e.strstart+=r,e.insert+=r>e.w_size-e.insert?e.w_size-e.insert:r),e.high_water>3,r=e.pending_buf_size-r>65535?65535:e.pending_buf_size-r,o=r>e.w_size?e.w_size:r,s=e.strstart-e.block_start,(s>=o||(s||t===K)&&t!==G&&0===e.strm.avail_in&&s<=r)&&(i=s>r?r:s,n=t===K&&0===e.strm.avail_in&&i===s?1:0,Q(e,e.block_start,i,n),e.block_start+=i,_e(e.strm)),n?3:1)},Ce=(e,t)=>{let i,s;for(;;){if(e.lookahead=3&&(e.ins_h=me(e,e.ins_h,e.window[e.strstart+3-1]),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-Ae&&(e.match_length=Be(e,i)),e.match_length>=3)if(s=H(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=me(e,e.ins_h,e.window[e.strstart+3-1]),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=me(e,e.ins_h,e.window[e.strstart+1]);else s=H(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(s&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===K?(ve(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(ve(e,!1),0===e.strm.avail_out)?1:2},Me=(e,t)=>{let i,s,r;for(;;){if(e.lookahead=3&&(e.ins_h=me(e,e.ins_h,e.window[e.strstart+3-1]),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=2,0!==i&&e.prev_length4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,s=H(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=me(e,e.ins_h,e.window[e.strstart+3-1]),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=2,e.strstart++,s&&(ve(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(s=H(e,0,e.window[e.strstart-1]),s&&ve(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(s=H(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===K?(ve(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(ve(e,!1),0===e.strm.avail_out)?1:2};function Ee(e,t,i,s,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=s,this.func=r}const Fe=[new Ee(0,0,0,0,Pe),new Ee(4,4,8,4,Ce),new Ee(4,5,16,8,Ce),new Ee(4,6,32,32,Ce),new Ee(4,4,16,16,Me),new Ee(8,16,32,32,Me),new Ee(8,16,128,128,Me),new Ee(8,32,128,256,Me),new Ee(32,128,258,1024,Me),new Ee(32,258,258,4096,Me)];function Ie(){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=ae,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 Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),fe(this.dyn_ltree),fe(this.dyn_dtree),fe(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),fe(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),fe(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const De=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==he&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==ce&&t.status!==ue?1:0},Se=e=>{if(De(e))return de(e,Z);e.total_in=e.total_out=0,e.data_type=ne;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?he:ce,e.adler=2===t.wrap?0:1,t.last_flush=-2,N(t),J},Te=e=>{const t=Se(e);var i;return t===J&&((i=e.state).window_size=2*i.w_size,fe(i.head),i.max_lazy_match=Fe[i.level].max_lazy,i.good_match=Fe[i.level].good_length,i.nice_match=Fe[i.level].nice_length,i.max_chain_length=Fe[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),t},Re=(e,t,i,s,r,o)=>{if(!e)return Z;let n=1;if(t===ee&&(t=6),s<0?(n=0,s=-s):s>15&&(n=2,s-=16),r<1||r>9||i!==ae||s<8||s>15||t<0||t>9||o<0||o>re||8===s&&1!==n)return de(e,Z);8===s&&(s=9);const a=new Ie;return e.state=a,a.strm=e,a.status=he,a.wrap=n,a.gzhead=null,a.w_bits=s,a.w_size=1<De(e)||2!==e.state.wrap?Z:(e.state.gzhead=t,J),Oe=(e,t)=>{if(De(e)||t>X||t<0)return e?de(e,Z):Z;const i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===ue&&t!==K)return de(e,0===e.avail_out?$:Z);const s=i.last_flush;if(i.last_flush=t,0!==i.pending){if(_e(e),0===e.avail_out)return i.last_flush=-1,J}else if(0===e.avail_in&&pe(t)<=pe(s)&&t!==K)return de(e,$);if(i.status===ue&&0!==e.avail_in)return de(e,$);if(i.status===he&&0===i.wrap&&(i.status=ce),i.status===he){let t=ae+(i.w_bits-8<<4)<<8,s=-1;if(s=i.strategy>=ie||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=s<<6,0!==i.strstart&&(t|=32),t+=31-t%31,ye(i,t),0!==i.strstart&&(ye(i,e.adler>>>16),ye(i,65535&e.adler)),e.adler=1,i.status=ce,_e(e),0!==i.pending)return i.last_flush=-1,J}if(57===i.status)if(e.adler=0,be(i,31),be(i,139),be(i,8),i.gzhead)be(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),be(i,255&i.gzhead.time),be(i,i.gzhead.time>>8&255),be(i,i.gzhead.time>>16&255),be(i,i.gzhead.time>>24&255),be(i,9===i.level?2:i.strategy>=ie||i.level<2?4:0),be(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(be(i,255&i.gzhead.extra.length),be(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=U(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(be(i,0),be(i,0),be(i,0),be(i,0),be(i,0),be(i,9===i.level?2:i.strategy>=ie||i.level<2?4:0),be(i,3),i.status=ce,_e(e),0!==i.pending)return i.last_flush=-1,J;if(69===i.status){if(i.gzhead.extra){let t=i.pending,s=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+s>i.pending_buf_size;){let r=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+r),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>t&&(e.adler=U(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex+=r,_e(e),0!==i.pending)return i.last_flush=-1,J;t=0,s-=r}let r=new Uint8Array(i.gzhead.extra);i.pending_buf.set(r.subarray(i.gzindex,i.gzindex+s),i.pending),i.pending+=s,i.gzhead.hcrc&&i.pending>t&&(e.adler=U(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let t,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(e.adler=U(e.adler,i.pending_buf,i.pending-s,s)),_e(e),0!==i.pending)return i.last_flush=-1,J;s=0}t=i.gzindexs&&(e.adler=U(e.adler,i.pending_buf,i.pending-s,s)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let t,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(e.adler=U(e.adler,i.pending_buf,i.pending-s,s)),_e(e),0!==i.pending)return i.last_flush=-1,J;s=0}t=i.gzindexs&&(e.adler=U(e.adler,i.pending_buf,i.pending-s,s))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(_e(e),0!==i.pending))return i.last_flush=-1,J;be(i,255&e.adler),be(i,e.adler>>8&255),e.adler=0}if(i.status=ce,_e(e),0!==i.pending)return i.last_flush=-1,J}if(0!==e.avail_in||0!==i.lookahead||t!==G&&i.status!==ue){let s=0===i.level?Pe(i,t):i.strategy===ie?((e,t)=>{let i;for(;;){if(0===e.lookahead&&(we(e),0===e.lookahead)){if(t===G)return 1;break}if(e.match_length=0,i=H(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===K?(ve(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(ve(e,!1),0===e.strm.avail_out)?1:2})(i,t):i.strategy===se?((e,t)=>{let i,s,r,o;const n=e.window;for(;;){if(e.lookahead<=le){if(we(e),e.lookahead<=le&&t===G)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=e.strstart-1,s=n[r],s===n[++r]&&s===n[++r]&&s===n[++r])){o=e.strstart+le;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]&&re.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=H(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=H(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===K?(ve(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(ve(e,!1),0===e.strm.avail_out)?1:2})(i,t):Fe[i.level].func(i,t);if(3!==s&&4!==s||(i.status=ue),1===s||3===s)return 0===e.avail_out&&(i.last_flush=-1),J;if(2===s&&(t===z?j(i):t!==X&&(Q(i,0,0,!1),t===W&&(fe(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),_e(e),0===e.avail_out))return i.last_flush=-1,J}return t!==K?J:i.wrap<=0?Y:(2===i.wrap?(be(i,255&e.adler),be(i,e.adler>>8&255),be(i,e.adler>>16&255),be(i,e.adler>>24&255),be(i,255&e.total_in),be(i,e.total_in>>8&255),be(i,e.total_in>>16&255),be(i,e.total_in>>24&255)):(ye(i,e.adler>>>16),ye(i,65535&e.adler)),_e(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?J:Y)},ke=e=>{if(De(e))return Z;const t=e.state.status;return e.state=null,t===ce?de(e,q):J},Ne=(e,t)=>{let i=t.length;if(De(e))return Z;const s=e.state,r=s.wrap;if(2===r||1===r&&s.status!==he||s.lookahead)return Z;if(1===r&&(e.adler=R(e.adler,t,i,0)),s.wrap=0,i>=s.w_size){0===r&&(fe(s.head),s.strstart=0,s.block_start=0,s.insert=0);let e=new Uint8Array(s.w_size);e.set(t.subarray(i-s.w_size,i),0),t=e,i=s.w_size}const o=e.avail_in,n=e.next_in,a=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,we(s);s.lookahead>=3;){let e=s.strstart,t=s.lookahead-2;do{s.ins_h=me(s,s.ins_h,s.window[e+3-1]),s.prev[e&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=e,e++}while(--t);s.strstart=e,s.lookahead=2,we(s)}return s.strstart+=s.lookahead,s.block_start=s.strstart,s.insert=s.lookahead,s.lookahead=0,s.match_length=s.prev_length=2,s.match_available=0,e.next_in=n,e.input=a,e.avail_in=o,s.wrap=r,J};const Qe=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var Ve=function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const t in i)Qe(i,t)&&(e[t]=i[t])}}return e},He=e=>{let t=0;for(let i=0,s=e.length;i=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;Ge[254]=Ge[254]=1;var ze=e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,i,s,r,o,n=e.length,a=0;for(r=0;r>>6,t[o++]=128|63&i):i<65536?(t[o++]=224|i>>>12,t[o++]=128|i>>>6&63,t[o++]=128|63&i):(t[o++]=240|i>>>18,t[o++]=128|i>>>12&63,t[o++]=128|i>>>6&63,t[o++]=128|63&i);return t},We=(e,t)=>{const i=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let s,r;const o=new Array(2*i);for(r=0,s=0;s4)o[r++]=65533,s+=n-1;else{for(t&=2===n?31:3===n?15:7;n>1&&s1?o[r++]=65533:t<65536?o[r++]=t:(t-=65536,o[r++]=55296|t>>10&1023,o[r++]=56320|1023&t)}}return((e,t)=>{if(t<65534&&e.subarray&&je)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let i="";for(let s=0;s{(t=t||e.length)>e.length&&(t=e.length);let i=t-1;for(;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+Ge[e[i]]>t?i:t},Xe=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};const Je=Object.prototype.toString,{Z_NO_FLUSH:Ye,Z_SYNC_FLUSH:Ze,Z_FULL_FLUSH:qe,Z_FINISH:$e,Z_OK:et,Z_STREAM_END:tt,Z_DEFAULT_COMPRESSION:it,Z_DEFAULT_STRATEGY:st,Z_DEFLATED:rt}=k;function ot(e){this.options=Ve({level:it,method:rt,chunkSize:16384,windowBits:15,memLevel:8,strategy:st},e||{});let 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 Xe,this.strm.avail_out=0;let i=Le(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==et)throw new Error(O[i]);if(t.header&&Ue(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?ze(t.dictionary):"[object ArrayBuffer]"===Je.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,i=Ne(this.strm,e),i!==et)throw new Error(O[i]);this._dict_set=!0}}function nt(e,t){const i=new ot(t);if(i.push(e,!0),i.err)throw i.msg||O[i.err];return i.result}ot.prototype.push=function(e,t){const i=this.strm,s=this.options.chunkSize;let r,o;if(this.ended)return!1;for(o=t===~~t?t:!0===t?$e:Ye,"string"==typeof e?i.input=ze(e):"[object ArrayBuffer]"===Je.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(s),i.next_out=0,i.avail_out=s),(o===Ze||o===qe)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(r=Oe(i,o),r===tt)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),r=ke(this.strm),this.onEnd(r),this.ended=!0,r===et;if(0!==i.avail_out){if(o>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},ot.prototype.onData=function(e){this.chunks.push(e)},ot.prototype.onEnd=function(e){e===et&&(this.result=He(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var at={Deflate:ot,deflate:nt,deflateRaw:function(e,t){return(t=t||{}).raw=!0,nt(e,t)},gzip:function(e,t){return(t=t||{}).gzip=!0,nt(e,t)},constants:k};const lt=16209;var At=function(e,t){let i,s,r,o,n,a,l,A,h,c,u,d,p,f,g,m,_,v,b,y,x,B,w,P;const C=e.state;i=e.next_in,w=e.input,s=i+(e.avail_in-5),r=e.next_out,P=e.output,o=r-(t-e.avail_out),n=r+(e.avail_out-257),a=C.dmax,l=C.wsize,A=C.whave,h=C.wnext,c=C.window,u=C.hold,d=C.bits,p=C.lencode,f=C.distcode,g=(1<>>24,u>>>=v,d-=v,v=_>>>16&255,0===v)P[r++]=65535&_;else{if(!(16&v)){if(0==(64&v)){_=p[(65535&_)+(u&(1<>>=v,d-=v),d<15&&(u+=w[i++]<>>24,u>>>=v,d-=v,v=_>>>16&255,!(16&v)){if(0==(64&v)){_=f[(65535&_)+(u&(1<a){e.msg="invalid distance too far back",C.mode=lt;break e}if(u>>>=v,d-=v,v=r-o,y>v){if(v=y-v,v>A&&C.sane){e.msg="invalid distance too far back",C.mode=lt;break e}if(x=0,B=c,0===h){if(x+=l-v,v2;)P[r++]=B[x++],P[r++]=B[x++],P[r++]=B[x++],b-=3;b&&(P[r++]=B[x++],b>1&&(P[r++]=B[x++]))}else{x=r-y;do{P[r++]=P[x++],P[r++]=P[x++],P[r++]=P[x++],b-=3}while(b>2);b&&(P[r++]=P[x++],b>1&&(P[r++]=P[x++]))}break}}break}}while(i>3,i-=b,d-=b<<3,u&=(1<{const l=a.bits;let A,h,c,u,d,p,f=0,g=0,m=0,_=0,v=0,b=0,y=0,x=0,B=0,w=0,P=null;const C=new Uint16Array(16),M=new Uint16Array(16);let E,F,I,D=null;for(f=0;f<=15;f++)C[f]=0;for(g=0;g=1&&0===C[_];_--);if(v>_&&(v=_),0===_)return r[o++]=20971520,r[o++]=20971520,a.bits=1,0;for(m=1;m<_&&0===C[m];m++);for(v0&&(0===e||1!==_))return-1;for(M[1]=0,f=1;f<15;f++)M[f+1]=M[f]+C[f];for(g=0;g852||2===e&&B>592)return 1;for(;;){E=f-y,n[g]+1=p?(F=D[n[g]-p],I=P[n[g]-p]):(F=96,I=0),A=1<>y)+h]=E<<24|F<<16|I|0}while(0!==h);for(A=1<>=1;if(0!==A?(w&=A-1,w+=A):w=0,g++,0==--C[f]){if(f===_)break;f=t[i+n[g]]}if(f>v&&(w&u)!==c){for(0===y&&(y=v),d+=m,b=f-y,x=1<852||2===e&&B>592)return 1;c=w&u,r[c]=v<<24|b<<16|d-o|0}}return 0!==w&&(r[d+w]=f-y<<24|64<<16|0),a.bits=v,0};const{Z_FINISH:ft,Z_BLOCK:gt,Z_TREES:mt,Z_OK:_t,Z_STREAM_END:vt,Z_NEED_DICT:bt,Z_STREAM_ERROR:yt,Z_DATA_ERROR:xt,Z_MEM_ERROR:Bt,Z_BUF_ERROR:wt,Z_DEFLATED:Pt}=k,Ct=16180,Mt=16190,Et=16191,Ft=16192,It=16194,Dt=16199,St=16200,Tt=16206,Rt=16209,Lt=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function Ut(){this.strm=null,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 Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const Ot=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode16211?1:0},kt=e=>{if(Ot(e))return yt;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=Ct,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,_t},Nt=e=>{if(Ot(e))return yt;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,kt(e)},Qt=(e,t)=>{let i;if(Ot(e))return yt;const s=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?yt:(null!==s.window&&s.wbits!==t&&(s.window=null),s.wrap=i,s.wbits=t,Nt(e))},Vt=(e,t)=>{if(!e)return yt;const i=new Ut;e.state=i,i.strm=e,i.window=null,i.mode=Ct;const s=Qt(e,t);return s!==_t&&(e.state=null),s};let Ht,jt,Gt=!0;const zt=e=>{if(Gt){Ht=new Int32Array(512),jt=new Int32Array(32);let t=0;for(;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(pt(1,e.lens,0,288,Ht,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;pt(2,e.lens,0,32,jt,0,e.work,{bits:5}),Gt=!1}e.lencode=Ht,e.lenbits=9,e.distcode=jt,e.distbits=5},Wt=(e,t,i,s)=>{let r;const o=e.state;return null===o.window&&(o.wsize=1<=o.wsize?(o.window.set(t.subarray(i-o.wsize,i),0),o.wnext=0,o.whave=o.wsize):(r=o.wsize-o.wnext,r>s&&(r=s),o.window.set(t.subarray(i-s,i-s+r),o.wnext),(s-=r)?(o.window.set(t.subarray(i-s,i),0),o.wnext=s,o.whave=o.wsize):(o.wnext+=r,o.wnext===o.wsize&&(o.wnext=0),o.whave{let i,s,r,o,n,a,l,A,h,c,u,d,p,f,g,m,_,v,b,y,x,B,w=0;const P=new Uint8Array(4);let C,M;const E=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(Ot(e)||!e.output||!e.input&&0!==e.avail_in)return yt;i=e.state,i.mode===Et&&(i.mode=Ft),n=e.next_out,r=e.output,l=e.avail_out,o=e.next_in,s=e.input,a=e.avail_in,A=i.hold,h=i.bits,c=a,u=l,B=_t;e:for(;;)switch(i.mode){case Ct:if(0===i.wrap){i.mode=Ft;break}for(;h<16;){if(0===a)break e;a--,A+=s[o++]<>>8&255,i.check=U(i.check,P,2,0),A=0,h=0,i.mode=16181;break}if(i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&A)<<8)+(A>>8))%31){e.msg="incorrect header check",i.mode=Rt;break}if((15&A)!==Pt){e.msg="unknown compression method",i.mode=Rt;break}if(A>>>=4,h-=4,x=8+(15&A),0===i.wbits&&(i.wbits=x),x>15||x>i.wbits){e.msg="invalid window size",i.mode=Rt;break}i.dmax=1<>8&1),512&i.flags&&4&i.wrap&&(P[0]=255&A,P[1]=A>>>8&255,i.check=U(i.check,P,2,0)),A=0,h=0,i.mode=16182;case 16182:for(;h<32;){if(0===a)break e;a--,A+=s[o++]<>>8&255,P[2]=A>>>16&255,P[3]=A>>>24&255,i.check=U(i.check,P,4,0)),A=0,h=0,i.mode=16183;case 16183:for(;h<16;){if(0===a)break e;a--,A+=s[o++]<>8),512&i.flags&&4&i.wrap&&(P[0]=255&A,P[1]=A>>>8&255,i.check=U(i.check,P,2,0)),A=0,h=0,i.mode=16184;case 16184:if(1024&i.flags){for(;h<16;){if(0===a)break e;a--,A+=s[o++]<>>8&255,i.check=U(i.check,P,2,0)),A=0,h=0}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&i.flags&&(d=i.length,d>a&&(d=a),d&&(i.head&&(x=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(s.subarray(o,o+d),x)),512&i.flags&&4&i.wrap&&(i.check=U(i.check,s,d,o)),a-=d,o+=d,i.length-=d),i.length))break e;i.length=0,i.mode=16186;case 16186:if(2048&i.flags){if(0===a)break e;d=0;do{x=s[o+d++],i.head&&x&&i.length<65536&&(i.head.name+=String.fromCharCode(x))}while(x&&d>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=Et;break;case 16189:for(;h<32;){if(0===a)break e;a--,A+=s[o++]<>>=7&h,h-=7&h,i.mode=Tt;break}for(;h<3;){if(0===a)break e;a--,A+=s[o++]<>>=1,h-=1,3&A){case 0:i.mode=16193;break;case 1:if(zt(i),i.mode=Dt,t===mt){A>>>=2,h-=2;break e}break;case 2:i.mode=16196;break;case 3:e.msg="invalid block type",i.mode=Rt}A>>>=2,h-=2;break;case 16193:for(A>>>=7&h,h-=7&h;h<32;){if(0===a)break e;a--,A+=s[o++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=Rt;break}if(i.length=65535&A,A=0,h=0,i.mode=It,t===mt)break e;case It:i.mode=16195;case 16195:if(d=i.length,d){if(d>a&&(d=a),d>l&&(d=l),0===d)break e;r.set(s.subarray(o,o+d),n),a-=d,o+=d,l-=d,n+=d,i.length-=d;break}i.mode=Et;break;case 16196:for(;h<14;){if(0===a)break e;a--,A+=s[o++]<>>=5,h-=5,i.ndist=1+(31&A),A>>>=5,h-=5,i.ncode=4+(15&A),A>>>=4,h-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=Rt;break}i.have=0,i.mode=16197;case 16197:for(;i.have>>=3,h-=3}for(;i.have<19;)i.lens[E[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,C={bits:i.lenbits},B=pt(0,i.lens,0,19,i.lencode,0,i.work,C),i.lenbits=C.bits,B){e.msg="invalid code lengths set",i.mode=Rt;break}i.have=0,i.mode=16198;case 16198:for(;i.have>>24,m=w>>>16&255,_=65535&w,!(g<=h);){if(0===a)break e;a--,A+=s[o++]<>>=g,h-=g,i.lens[i.have++]=_;else{if(16===_){for(M=g+2;h>>=g,h-=g,0===i.have){e.msg="invalid bit length repeat",i.mode=Rt;break}x=i.lens[i.have-1],d=3+(3&A),A>>>=2,h-=2}else if(17===_){for(M=g+3;h>>=g,h-=g,x=0,d=3+(7&A),A>>>=3,h-=3}else{for(M=g+7;h>>=g,h-=g,x=0,d=11+(127&A),A>>>=7,h-=7}if(i.have+d>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=Rt;break}for(;d--;)i.lens[i.have++]=x}}if(i.mode===Rt)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=Rt;break}if(i.lenbits=9,C={bits:i.lenbits},B=pt(1,i.lens,0,i.nlen,i.lencode,0,i.work,C),i.lenbits=C.bits,B){e.msg="invalid literal/lengths set",i.mode=Rt;break}if(i.distbits=6,i.distcode=i.distdyn,C={bits:i.distbits},B=pt(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,C),i.distbits=C.bits,B){e.msg="invalid distances set",i.mode=Rt;break}if(i.mode=Dt,t===mt)break e;case Dt:i.mode=St;case St:if(a>=6&&l>=258){e.next_out=n,e.avail_out=l,e.next_in=o,e.avail_in=a,i.hold=A,i.bits=h,At(e,u),n=e.next_out,r=e.output,l=e.avail_out,o=e.next_in,s=e.input,a=e.avail_in,A=i.hold,h=i.bits,i.mode===Et&&(i.back=-1);break}for(i.back=0;w=i.lencode[A&(1<>>24,m=w>>>16&255,_=65535&w,!(g<=h);){if(0===a)break e;a--,A+=s[o++]<>v)],g=w>>>24,m=w>>>16&255,_=65535&w,!(v+g<=h);){if(0===a)break e;a--,A+=s[o++]<>>=v,h-=v,i.back+=v}if(A>>>=g,h-=g,i.back+=g,i.length=_,0===m){i.mode=16205;break}if(32&m){i.back=-1,i.mode=Et;break}if(64&m){e.msg="invalid literal/length code",i.mode=Rt;break}i.extra=15&m,i.mode=16201;case 16201:if(i.extra){for(M=i.extra;h>>=i.extra,h-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=16202;case 16202:for(;w=i.distcode[A&(1<>>24,m=w>>>16&255,_=65535&w,!(g<=h);){if(0===a)break e;a--,A+=s[o++]<>v)],g=w>>>24,m=w>>>16&255,_=65535&w,!(v+g<=h);){if(0===a)break e;a--,A+=s[o++]<>>=v,h-=v,i.back+=v}if(A>>>=g,h-=g,i.back+=g,64&m){e.msg="invalid distance code",i.mode=Rt;break}i.offset=_,i.extra=15&m,i.mode=16203;case 16203:if(i.extra){for(M=i.extra;h>>=i.extra,h-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=Rt;break}i.mode=16204;case 16204:if(0===l)break e;if(d=u-l,i.offset>d){if(d=i.offset-d,d>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=Rt;break}d>i.wnext?(d-=i.wnext,p=i.wsize-d):p=i.wnext-d,d>i.length&&(d=i.length),f=i.window}else f=r,p=n-i.offset,d=i.length;d>l&&(d=l),l-=d,i.length-=d;do{r[n++]=f[p++]}while(--d);0===i.length&&(i.mode=St);break;case 16205:if(0===l)break e;r[n++]=i.length,l--,i.mode=St;break;case Tt:if(i.wrap){for(;h<32;){if(0===a)break e;a--,A|=s[o++]<{if(Ot(e))return yt;let t=e.state;return t.window&&(t.window=null),e.state=null,_t},Zt=(e,t)=>{if(Ot(e))return yt;const i=e.state;return 0==(2&i.wrap)?yt:(i.head=t,t.done=!1,_t)},qt=(e,t)=>{const i=t.length;let s,r,o;return Ot(e)?yt:(s=e.state,0!==s.wrap&&s.mode!==Mt?yt:s.mode===Mt&&(r=1,r=R(r,t,i,0),r!==s.check)?xt:(o=Wt(e,t,i,i),o?(s.mode=16210,Bt):(s.havedict=1,_t)))},$t=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};const ei=Object.prototype.toString,{Z_NO_FLUSH:ti,Z_FINISH:ii,Z_OK:si,Z_STREAM_END:ri,Z_NEED_DICT:oi,Z_STREAM_ERROR:ni,Z_DATA_ERROR:ai,Z_MEM_ERROR:li}=k;function Ai(e){this.options=Ve({chunkSize:65536,windowBits:15,to:""},e||{});const 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 Xe,this.strm.avail_out=0;let i=Xt(this.strm,t.windowBits);if(i!==si)throw new Error(O[i]);if(this.header=new $t,Zt(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=ze(t.dictionary):"[object ArrayBuffer]"===ei.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=qt(this.strm,t.dictionary),i!==si)))throw new Error(O[i])}function hi(e,t){const i=new Ai(t);if(i.push(e),i.err)throw i.msg||O[i.err];return i.result}Ai.prototype.push=function(e,t){const i=this.strm,s=this.options.chunkSize,r=this.options.dictionary;let o,n,a;if(this.ended)return!1;for(n=t===~~t?t:!0===t?ii:ti,"[object ArrayBuffer]"===ei.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(s),i.next_out=0,i.avail_out=s),o=Jt(i,n),o===oi&&r&&(o=qt(i,r),o===si?o=Jt(i,n):o===ai&&(o=oi));i.avail_in>0&&o===ri&&i.state.wrap>0&&0!==e[i.next_in];)Kt(i),o=Jt(i,n);switch(o){case ni:case ai:case oi:case li:return this.onEnd(o),this.ended=!0,!1}if(a=i.avail_out,i.next_out&&(0===i.avail_out||o===ri))if("string"===this.options.to){let e=Ke(i.output,i.next_out),t=i.next_out-e,r=We(i.output,e);i.next_out=t,i.avail_out=s-t,t&&i.output.set(i.output.subarray(e,e+t),0),this.onData(r)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(o!==si||0!==a){if(o===ri)return o=Yt(this.strm),this.onEnd(o),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},Ai.prototype.onData=function(e){this.chunks.push(e)},Ai.prototype.onEnd=function(e){e===si&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=He(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var ci={Inflate:Ai,inflate:hi,inflateRaw:function(e,t){return(t=t||{}).raw=!0,hi(e,t)},ungzip:hi,constants:k};const{Deflate:ui,deflate:di,deflateRaw:pi,gzip:fi}=at,{Inflate:gi,inflate:mi,inflateRaw:_i,ungzip:vi}=ci;var bi=ui,yi=di,xi=pi,Bi=fi,wi=gi,Pi=mi,Ci=_i,Mi=vi,Ei=k,Fi={Deflate:bi,deflate:yi,deflateRaw:xi,gzip:Bi,Inflate:wi,inflate:Pi,inflateRaw:Ci,ungzip:Mi,constants:Ei};e.Deflate=bi,e.Inflate=wi,e.constants=Ei,e.default=Fi,e.deflate=yi,e.deflateRaw=xi,e.gzip=Bi,e.inflate=Pi,e.inflateRaw=Ci,e.ungzip=Mi,Object.defineProperty(e,"__esModule",{value:!0})}));var jC=Object.freeze({__proto__:null});let GC=window.pako||jC;GC.inflate||(GC=GC.default);const zC=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}}();const WC={version:1,parse:function(e,t,i,s,r,o){const n=function(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]}}(i),a=function(e){return{positions:new Uint16Array(GC.inflate(e.positions).buffer),normals:new Int8Array(GC.inflate(e.normals).buffer),indices:new Uint32Array(GC.inflate(e.indices).buffer),edgeIndices:new Uint32Array(GC.inflate(e.edgeIndices).buffer),meshPositions:new Uint32Array(GC.inflate(e.meshPositions).buffer),meshIndices:new Uint32Array(GC.inflate(e.meshIndices).buffer),meshEdgesIndices:new Uint32Array(GC.inflate(e.meshEdgesIndices).buffer),meshColors:new Uint8Array(GC.inflate(e.meshColors).buffer),entityIDs:GC.inflate(e.entityIDs,{to:"string"}),entityMeshes:new Uint32Array(GC.inflate(e.entityMeshes).buffer),entityIsObjects:new Uint8Array(GC.inflate(e.entityIsObjects).buffer),positionsDecodeMatrix:new Float32Array(GC.inflate(e.positionsDecodeMatrix).buffer)}}(n);!function(e,t,i,s,r,o){o.getNextId(),s.positionsCompression="precompressed",s.normalsCompression="precompressed";const n=i.positions,a=i.normals,l=i.indices,A=i.edgeIndices,h=i.meshPositions,c=i.meshIndices,u=i.meshEdgesIndices,p=i.meshColors,f=JSON.parse(i.entityIDs),g=i.entityMeshes,m=i.entityIsObjects,_=h.length,v=g.length;for(let r=0;rg[e]g[t]?1:0));for(let e=0;e1||(E[i]=e)}}for(let e=0;e1,o=eM(m.subarray(4*t,4*t+3)),u=m[4*t+3]/255,_=a.subarray(d[t],i?a.length:d[t+1]),b=l.subarray(d[t],i?l.length:d[t+1]),x=A.subarray(p[t],i?A.length:p[t+1]),w=h.subarray(f[t],i?h.length:f[t+1]),M=c.subarray(g[t],g[t]+16);if(r){const e=`${n}-geometry.${t}`;s.createGeometry({id:e,primitive:"triangles",positionsCompressed:_,normalsCompressed:b,indices:x,edgeIndices:w,positionsDecodeMatrix:M})}else{const e=`${n}-${t}`;v[E[t]];const i={};s.createMesh(y.apply(i,{id:e,primitive:"triangles",positionsCompressed:_,normalsCompressed:b,indices:x,edgeIndices:w,positionsDecodeMatrix:M,color:o,opacity:u}))}}let F=0;for(let e=0;e1){const t={},r=`${n}-instance.${F++}`,o=`${n}-geometry.${i}`,a=16*x[e],A=u.subarray(a,a+16);s.createMesh(y.apply(t,{id:r,geometryId:o,matrix:A})),l.push(r)}else l.push(i)}if(l.length>0){const e={};s.createEntity(y.apply(e,{id:r,isObject:!0,meshIds:l}))}}}(0,0,a,s,0,o)}};let iM=window.pako||jC;iM.inflate||(iM=iM.default);const sM=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}}();const rM={version:5,parse:function(e,t,i,s,r,o){const n=function(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]}}(i),a=function(e){return{positions:new Float32Array(iM.inflate(e.positions).buffer),normals:new Int8Array(iM.inflate(e.normals).buffer),indices:new Uint32Array(iM.inflate(e.indices).buffer),edgeIndices:new Uint32Array(iM.inflate(e.edgeIndices).buffer),matrices:new Float32Array(iM.inflate(e.matrices).buffer),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(iM.inflate(e.eachPrimitivePositionsAndNormalsPortion).buffer),eachPrimitiveIndicesPortion:new Uint32Array(iM.inflate(e.eachPrimitiveIndicesPortion).buffer),eachPrimitiveEdgeIndicesPortion:new Uint32Array(iM.inflate(e.eachPrimitiveEdgeIndicesPortion).buffer),eachPrimitiveColor:new Uint8Array(iM.inflate(e.eachPrimitiveColor).buffer),primitiveInstances:new Uint32Array(iM.inflate(e.primitiveInstances).buffer),eachEntityId:iM.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(iM.inflate(e.eachEntityPrimitiveInstancesPortion).buffer),eachEntityMatricesPortion:new Uint32Array(iM.inflate(e.eachEntityMatricesPortion).buffer)}}(n);!function(e,t,i,s,r,o){const n=o.getNextId();s.positionsCompression="disabled",s.normalsCompression="precompressed";const a=i.positions,l=i.normals,A=i.indices,h=i.edgeIndices,c=i.matrices,u=i.eachPrimitivePositionsAndNormalsPortion,d=i.eachPrimitiveIndicesPortion,p=i.eachPrimitiveEdgeIndicesPortion,f=i.eachPrimitiveColor,g=i.primitiveInstances,m=JSON.parse(i.eachEntityId),_=i.eachEntityPrimitiveInstancesPortion,v=i.eachEntityMatricesPortion,b=u.length,x=g.length,B=new Uint8Array(b),w=m.length;for(let e=0;e1||(P[i]=e)}}for(let e=0;e1,r=sM(f.subarray(4*e,4*e+3)),o=f[4*e+3]/255,c=a.subarray(u[e],t?a.length:u[e+1]),g=l.subarray(u[e],t?l.length:u[e+1]),_=A.subarray(d[e],t?A.length:d[e+1]),v=h.subarray(p[e],t?h.length:p[e+1]);if(i){const t=`${n}-geometry.${e}`;s.createGeometry({id:t,primitive:"triangles",positionsCompressed:c,normalsCompressed:g,indices:_,edgeIndices:v})}else{const t=e;m[P[e]];const i={};s.createMesh(y.apply(i,{id:t,primitive:"triangles",positionsCompressed:c,normalsCompressed:g,indices:_,edgeIndices:v,color:r,opacity:o}))}}let C=0;for(let e=0;e1){const t={},r="instance."+C++,o="geometry"+i,n=16*v[e],l=c.subarray(n,n+16);s.createMesh(y.apply(t,{id:r,geometryId:o,matrix:l})),a.push(r)}else a.push(i)}if(a.length>0){const e={};s.createEntity(y.apply(e,{id:r,isObject:!0,meshIds:a}))}}}(0,0,a,s,0,o)}};let oM=window.pako||jC;oM.inflate||(oM=oM.default);const nM=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}}();const aM={version:6,parse:function(e,t,i,s,r,o){const n=function(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],matrices:e[4],reusedPrimitivesDecodeMatrix:e[5],eachPrimitivePositionsAndNormalsPortion:e[6],eachPrimitiveIndicesPortion:e[7],eachPrimitiveEdgeIndicesPortion:e[8],eachPrimitiveColorAndOpacity:e[9],primitiveInstances:e[10],eachEntityId:e[11],eachEntityPrimitiveInstancesPortion:e[12],eachEntityMatricesPortion:e[13],eachTileAABB:e[14],eachTileEntitiesPortion:e[15]}}(i),a=function(e){function t(e,t){return 0===e.length?[]:oM.inflate(e,t).buffer}return{positions:new Uint16Array(t(e.positions)),normals:new Int8Array(t(e.normals)),indices:new Uint32Array(t(e.indices)),edgeIndices:new Uint32Array(t(e.edgeIndices)),matrices:new Float32Array(t(e.matrices)),reusedPrimitivesDecodeMatrix:new Float32Array(t(e.reusedPrimitivesDecodeMatrix)),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(t(e.eachPrimitivePositionsAndNormalsPortion)),eachPrimitiveIndicesPortion:new Uint32Array(t(e.eachPrimitiveIndicesPortion)),eachPrimitiveEdgeIndicesPortion:new Uint32Array(t(e.eachPrimitiveEdgeIndicesPortion)),eachPrimitiveColorAndOpacity:new Uint8Array(t(e.eachPrimitiveColorAndOpacity)),primitiveInstances:new Uint32Array(t(e.primitiveInstances)),eachEntityId:oM.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(t(e.eachEntityPrimitiveInstancesPortion)),eachEntityMatricesPortion:new Uint32Array(t(e.eachEntityMatricesPortion)),eachTileAABB:new Float64Array(t(e.eachTileAABB)),eachTileEntitiesPortion:new Uint32Array(t(e.eachTileEntitiesPortion))}}(n);!function(e,t,i,s,r,o){const n=o.getNextId(),a=i.positions,l=i.normals,A=i.indices,h=i.edgeIndices,c=i.matrices,u=i.reusedPrimitivesDecodeMatrix,p=i.eachPrimitivePositionsAndNormalsPortion,f=i.eachPrimitiveIndicesPortion,g=i.eachPrimitiveEdgeIndicesPortion,m=i.eachPrimitiveColorAndOpacity,_=i.primitiveInstances,v=JSON.parse(i.eachEntityId),b=i.eachEntityPrimitiveInstancesPortion,x=i.eachEntityMatricesPortion,B=i.eachTileAABB,w=i.eachTileEntitiesPortion,P=p.length,C=_.length,M=v.length,E=w.length,F=new Uint32Array(P);for(let e=0;e1,c=t===P-1,d=a.subarray(p[t],c?a.length:p[t+1]),v=l.subarray(p[t],c?l.length:p[t+1]),b=A.subarray(f[t],c?A.length:f[t+1]),x=h.subarray(g[t],c?h.length:g[t+1]),B=nM(m.subarray(4*t,4*t+3)),w=m[4*t+3]/255,C=o.getNextId();if(r){const e=`${n}-geometry.${i}.${t}`;U[e]||(s.createGeometry({id:e,primitive:"triangles",positionsCompressed:d,indices:b,edgeIndices:x,positionsDecodeMatrix:u}),U[e]=!0),s.createMesh(y.apply(N,{id:C,geometryId:e,origin:I,matrix:E,color:B,opacity:w})),R.push(C)}else s.createMesh(y.apply(N,{id:C,origin:I,primitive:"triangles",positionsCompressed:d,normalsCompressed:v,indices:b,edgeIndices:x,positionsDecodeMatrix:L,color:B,opacity:w})),R.push(C)}R.length>0&&s.createEntity(y.apply(k,{id:w,isObject:!0,meshIds:R}))}}}(e,t,a,s,0,o)}};let lM=window.pako||jC;lM.inflate||(lM=lM.default);const AM=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 hM(e){const t=[];for(let i=0,s=e.length;i1,d=t===F-1,P=AM(w.subarray(6*e,6*e+3)),C=w[6*e+3]/255,M=w[6*e+4]/255,E=w[6*e+5]/255,I=o.getNextId();if(r){const r=B[e],o=u.slice(r,r+16),x=`${n}-geometry.${i}.${t}`;if(!Q[x]){let e,i,r,o,n,u;switch(f[t]){case 0:e="solid",i=a.subarray(g[t],d?a.length:g[t+1]),r=l.subarray(m[t],d?l.length:m[t+1]),n=h.subarray(v[t],d?h.length:v[t+1]),u=c.subarray(b[t],d?c.length:b[t+1]);break;case 1:e="surface",i=a.subarray(g[t],d?a.length:g[t+1]),r=l.subarray(m[t],d?l.length:m[t+1]),n=h.subarray(v[t],d?h.length:v[t+1]),u=c.subarray(b[t],d?c.length:b[t+1]);break;case 2:e="points",i=a.subarray(g[t],d?a.length:g[t+1]),o=hM(A.subarray(_[t],d?A.length:_[t+1]));break;case 3:e="lines",i=a.subarray(g[t],d?a.length:g[t+1]),n=h.subarray(v[t],d?h.length:v[t+1]);break;default:continue}s.createGeometry({id:x,primitive:e,positionsCompressed:i,normalsCompressed:r,colors:o,indices:n,edgeIndices:u,positionsDecodeMatrix:p}),Q[x]=!0}s.createMesh(y.apply(V,{id:I,geometryId:x,origin:R,matrix:o,color:P,metallic:M,roughness:E,opacity:C})),U.push(I)}else{let e,i,r,o,n,u;switch(f[t]){case 0:e="solid",i=a.subarray(g[t],d?a.length:g[t+1]),r=l.subarray(m[t],d?l.length:m[t+1]),n=h.subarray(v[t],d?h.length:v[t+1]),u=c.subarray(b[t],d?c.length:b[t+1]);break;case 1:e="surface",i=a.subarray(g[t],d?a.length:g[t+1]),r=l.subarray(m[t],d?l.length:m[t+1]),n=h.subarray(v[t],d?h.length:v[t+1]),u=c.subarray(b[t],d?c.length:b[t+1]);break;case 2:e="points",i=a.subarray(g[t],d?a.length:g[t+1]),o=hM(A.subarray(_[t],d?A.length:_[t+1]));break;case 3:e="lines",i=a.subarray(g[t],d?a.length:g[t+1]),n=h.subarray(v[t],d?h.length:v[t+1]);break;default:continue}s.createMesh(y.apply(V,{id:I,origin:R,primitive:e,positionsCompressed:i,normalsCompressed:r,colors:o,indices:n,edgeIndices:u,positionsDecodeMatrix:N,color:P,metallic:M,roughness:E,opacity:C})),U.push(I)}}U.length>0&&s.createEntity(y.apply(k,{id:E,isObject:!0,meshIds:U}))}}}(e,t,a,s,0,o)}};let uM=window.pako||jC;uM.inflate||(uM=uM.default);const dM=d.vec4(),pM=d.vec4();const fM=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 gM(e){const t=[];for(let i=0,s=e.length;i1,l=r===L-1,A=fM(F.subarray(6*e,6*e+3)),h=F[6*e+3]/255,c=F[6*e+4]/255,I=F[6*e+5]/255,D=o.getNextId();if(a){const o=E[e],a=_.slice(o,o+16),M=`${n}-geometry.${i}.${r}`;let F=H[M];if(!F){F={batchThisMesh:!t.reuseGeometries};let e=!1;switch(b[r]){case 0:F.primitiveName="solid",F.geometryPositions=u.subarray(x[r],l?u.length:x[r+1]),F.geometryNormals=p.subarray(B[r],l?p.length:B[r+1]),F.geometryIndices=g.subarray(P[r],l?g.length:P[r+1]),F.geometryEdgeIndices=m.subarray(C[r],l?m.length:C[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 1:F.primitiveName="surface",F.geometryPositions=u.subarray(x[r],l?u.length:x[r+1]),F.geometryNormals=p.subarray(B[r],l?p.length:B[r+1]),F.geometryIndices=g.subarray(P[r],l?g.length:P[r+1]),F.geometryEdgeIndices=m.subarray(C[r],l?m.length:C[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 2:F.primitiveName="points",F.geometryPositions=u.subarray(x[r],l?u.length:x[r+1]),F.geometryColors=gM(f.subarray(w[r],l?f.length:w[r+1])),e=F.geometryPositions.length>0;break;case 3:F.primitiveName="lines",F.geometryPositions=u.subarray(x[r],l?u.length:x[r+1]),F.geometryIndices=g.subarray(P[r],l?g.length:P[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;default:continue}if(e||(F=null),F&&(F.geometryPositions.length,F.batchThisMesh)){F.decompressedPositions=new Float32Array(F.geometryPositions.length);const e=F.geometryPositions,t=F.decompressedPositions;for(let i=0,s=e.length;i0&&n.length>0;break;case 1:e="surface",t=u.subarray(x[r],l?u.length:x[r+1]),i=p.subarray(B[r],l?p.length:B[r+1]),n=g.subarray(P[r],l?g.length:P[r+1]),a=m.subarray(C[r],l?m.length:C[r+1]),d=t.length>0&&n.length>0;break;case 2:e="points",t=u.subarray(x[r],l?u.length:x[r+1]),o=gM(f.subarray(w[r],l?f.length:w[r+1])),d=t.length>0;break;case 3:e="lines",t=u.subarray(x[r],l?u.length:x[r+1]),n=g.subarray(P[r],l?g.length:P[r+1]),d=t.length>0&&n.length>0;break;default:continue}d&&(s.createMesh(y.apply(G,{id:D,origin:Q,primitive:e,positionsCompressed:t,normalsCompressed:i,colorsCompressed:o,indices:n,edgeIndices:a,positionsDecodeMatrix:R,color:A,metallic:c,roughness:I,opacity:h})),T.push(D))}}T.length>0&&s.createEntity(y.apply(j,{id:A,isObject:!0,meshIds:T}))}}}(e,t,a,s,r,o)}};let _M=window.pako||jC;_M.inflate||(_M=_M.default);const vM=d.vec4(),bM=d.vec4();const yM=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}}();const xM={version:9,parse:function(e,t,i,s,r,o){const n=function(e){return{metadata:e[0],positions:e[1],normals:e[2],colors:e[3],indices:e[4],edgeIndices:e[5],matrices:e[6],reusedGeometriesDecodeMatrix:e[7],eachGeometryPrimitiveType:e[8],eachGeometryPositionsPortion:e[9],eachGeometryNormalsPortion:e[10],eachGeometryColorsPortion:e[11],eachGeometryIndicesPortion:e[12],eachGeometryEdgeIndicesPortion:e[13],eachMeshGeometriesPortion:e[14],eachMeshMatricesPortion:e[15],eachMeshMaterial:e[16],eachEntityId:e[17],eachEntityMeshesPortion:e[18],eachTileAABB:e[19],eachTileEntitiesPortion:e[20]}}(i),a=function(e){function t(e,t){return 0===e.length?[]:_M.inflate(e,t).buffer}return{metadata:JSON.parse(_M.inflate(e.metadata,{to:"string"})),positions:new Uint16Array(t(e.positions)),normals:new Int8Array(t(e.normals)),colors:new Uint8Array(t(e.colors)),indices:new Uint32Array(t(e.indices)),edgeIndices:new Uint32Array(t(e.edgeIndices)),matrices:new Float32Array(t(e.matrices)),reusedGeometriesDecodeMatrix:new Float32Array(t(e.reusedGeometriesDecodeMatrix)),eachGeometryPrimitiveType:new Uint8Array(t(e.eachGeometryPrimitiveType)),eachGeometryPositionsPortion:new Uint32Array(t(e.eachGeometryPositionsPortion)),eachGeometryNormalsPortion:new Uint32Array(t(e.eachGeometryNormalsPortion)),eachGeometryColorsPortion:new Uint32Array(t(e.eachGeometryColorsPortion)),eachGeometryIndicesPortion:new Uint32Array(t(e.eachGeometryIndicesPortion)),eachGeometryEdgeIndicesPortion:new Uint32Array(t(e.eachGeometryEdgeIndicesPortion)),eachMeshGeometriesPortion:new Uint32Array(t(e.eachMeshGeometriesPortion)),eachMeshMatricesPortion:new Uint32Array(t(e.eachMeshMatricesPortion)),eachMeshMaterial:new Uint8Array(t(e.eachMeshMaterial)),eachEntityId:JSON.parse(_M.inflate(e.eachEntityId,{to:"string"})),eachEntityMeshesPortion:new Uint32Array(t(e.eachEntityMeshesPortion)),eachTileAABB:new Float64Array(t(e.eachTileAABB)),eachTileEntitiesPortion:new Uint32Array(t(e.eachTileEntitiesPortion))}}(n);!function(e,t,i,s,r,o){const n=o.getNextId(),a=i.metadata,l=i.positions,A=i.normals,h=i.colors,c=i.indices,u=i.edgeIndices,p=i.matrices,f=i.reusedGeometriesDecodeMatrix,g=i.eachGeometryPrimitiveType,m=i.eachGeometryPositionsPortion,_=i.eachGeometryNormalsPortion,v=i.eachGeometryColorsPortion,b=i.eachGeometryIndicesPortion,x=i.eachGeometryEdgeIndicesPortion,B=i.eachMeshGeometriesPortion,w=i.eachMeshMatricesPortion,P=i.eachMeshMaterial,C=i.eachEntityId,M=i.eachEntityMeshesPortion,E=i.eachTileAABB,F=i.eachTileEntitiesPortion,I=m.length,D=B.length,S=M.length,T=F.length;r&&r.loadData(a,{includeTypes:t.includeTypes,excludeTypes:t.excludeTypes,globalizeObjectIds:t.globalizeObjectIds});const R=new Uint32Array(I);for(let e=0;e1,C=r===I-1,M=yM(P.subarray(6*e,6*e+3)),E=P[6*e+3]/255,F=P[6*e+4]/255,D=P[6*e+5]/255,S=o.getNextId();if(a){const o=w[e],a=p.slice(o,o+16),B=`${n}-geometry.${i}.${r}`;let P=O[B];if(!P){P={batchThisMesh:!t.reuseGeometries};let e=!1;switch(g[r]){case 0:P.primitiveName="solid",P.geometryPositions=l.subarray(m[r],C?l.length:m[r+1]),P.geometryNormals=A.subarray(_[r],C?A.length:_[r+1]),P.geometryIndices=c.subarray(b[r],C?c.length:b[r+1]),P.geometryEdgeIndices=u.subarray(x[r],C?u.length:x[r+1]),e=P.geometryPositions.length>0&&P.geometryIndices.length>0;break;case 1:P.primitiveName="surface",P.geometryPositions=l.subarray(m[r],C?l.length:m[r+1]),P.geometryNormals=A.subarray(_[r],C?A.length:_[r+1]),P.geometryIndices=c.subarray(b[r],C?c.length:b[r+1]),P.geometryEdgeIndices=u.subarray(x[r],C?u.length:x[r+1]),e=P.geometryPositions.length>0&&P.geometryIndices.length>0;break;case 2:P.primitiveName="points",P.geometryPositions=l.subarray(m[r],C?l.length:m[r+1]),P.geometryColors=h.subarray(v[r],C?h.length:v[r+1]),e=P.geometryPositions.length>0;break;case 3:P.primitiveName="lines",P.geometryPositions=l.subarray(m[r],C?l.length:m[r+1]),P.geometryIndices=c.subarray(b[r],C?c.length:b[r+1]),e=P.geometryPositions.length>0&&P.geometryIndices.length>0;break;default:continue}if(e||(P=null),P&&(P.geometryPositions.length,P.batchThisMesh)){P.decompressedPositions=new Float32Array(P.geometryPositions.length),P.transformedAndRecompressedPositions=new Uint16Array(P.geometryPositions.length);const e=P.geometryPositions,t=P.decompressedPositions;for(let i=0,s=e.length;i0&&n.length>0;break;case 1:e="surface",t=l.subarray(m[r],C?l.length:m[r+1]),i=A.subarray(_[r],C?A.length:_[r+1]),n=c.subarray(b[r],C?c.length:b[r+1]),a=u.subarray(x[r],C?u.length:x[r+1]),d=t.length>0&&n.length>0;break;case 2:e="points",t=l.subarray(m[r],C?l.length:m[r+1]),o=h.subarray(v[r],C?h.length:v[r+1]),d=t.length>0;break;case 3:e="lines",t=l.subarray(m[r],C?l.length:m[r+1]),n=c.subarray(b[r],C?c.length:b[r+1]),d=t.length>0&&n.length>0;break;default:continue}d&&(s.createMesh(y.apply(j,{id:S,origin:L,primitive:e,positionsCompressed:t,normalsCompressed:i,colorsCompressed:o,indices:n,edgeIndices:a,positionsDecodeMatrix:Q,color:M,metallic:F,roughness:D,opacity:E})),k.push(S))}}k.length>0&&s.createEntity(y.apply(H,{id:E,isObject:!0,meshIds:k}))}}}(e,t,a,s,r,o)}};let BM=window.pako||jC;BM.inflate||(BM=BM.default);const wM=d.vec4(),PM=d.vec4();const CM=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 MM(e,t){const i=[];if(t.length>1)for(let e=0,s=t.length-1;e1)for(let t=0,s=e.length/3-1;t0,a=9*e,c=1===h[a+0],u=h[a+1];h[a+2],h[a+3];const d=h[a+4],p=h[a+5],f=h[a+6],g=h[a+7],m=h[a+8];if(o){const t=new Uint8Array(l.subarray(i,r)).buffer,o=`${n}-texture-${e}`;if(c)s.createTexture({id:o,buffers:[t],minFilter:d,magFilter:p,wrapS:f,wrapT:g,wrapR:m});else{const e=new Blob([t],{type:10001===u?"image/jpeg":10002===u?"image/png":"image/gif"}),i=(window.URL||window.webkitURL).createObjectURL(e),r=document.createElement("img");r.src=i,s.createTexture({id:o,image:r,minFilter:d,magFilter:p,wrapS:f,wrapT:g,wrapR:m})}}}for(let e=0;e=0?`${n}-texture-${r}`:null,normalsTextureId:a>=0?`${n}-texture-${a}`:null,metallicRoughnessTextureId:o>=0?`${n}-texture-${o}`:null,emissiveTextureId:l>=0?`${n}-texture-${l}`:null,occlusionTextureId:A>=0?`${n}-texture-${A}`:null})}const j=new Uint32Array(N);for(let e=0;e1,l=r===N-1,A=D[e],h=A>=0?`${n}-textureSet-${A}`:null,T=CM(S.subarray(6*e,6*e+3)),R=S[6*e+3]/255,L=S[6*e+4]/255,k=S[6*e+5]/255,Q=o.getNextId();if(a){const o=I[e],a=v.slice(o,o+16),A=`${n}-geometry.${i}.${r}`;let F=W[A];if(!F){F={batchThisMesh:!t.reuseGeometries};let e=!1;switch(x[r]){case 0:F.primitiveName="solid",F.geometryPositions=c.subarray(B[r],l?c.length:B[r+1]),F.geometryNormals=u.subarray(w[r],l?u.length:w[r+1]),F.geometryUVs=f.subarray(C[r],l?f.length:C[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),F.geometryEdgeIndices=m.subarray(E[r],l?m.length:E[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 1:F.primitiveName="surface",F.geometryPositions=c.subarray(B[r],l?c.length:B[r+1]),F.geometryNormals=u.subarray(w[r],l?u.length:w[r+1]),F.geometryUVs=f.subarray(C[r],l?f.length:C[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),F.geometryEdgeIndices=m.subarray(E[r],l?m.length:E[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 2:F.primitiveName="points",F.geometryPositions=c.subarray(B[r],l?c.length:B[r+1]),F.geometryColors=p.subarray(P[r],l?p.length:P[r+1]),e=F.geometryPositions.length>0;break;case 3:F.primitiveName="lines",F.geometryPositions=c.subarray(B[r],l?c.length:B[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 4:F.primitiveName="lines",F.geometryPositions=c.subarray(B[r],l?c.length:B[r+1]),F.geometryIndices=MM(F.geometryPositions,g.subarray(M[r],l?g.length:M[r+1])),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;default:continue}if(e||(F=null),F&&(F.geometryPositions.length,F.batchThisMesh)){F.decompressedPositions=new Float32Array(F.geometryPositions.length),F.transformedAndRecompressedPositions=new Uint16Array(F.geometryPositions.length);const e=F.geometryPositions,t=F.decompressedPositions;for(let i=0,s=e.length;i0&&a.length>0;break;case 1:e="surface",t=c.subarray(B[r],l?c.length:B[r+1]),i=u.subarray(w[r],l?u.length:w[r+1]),o=f.subarray(C[r],l?f.length:C[r+1]),a=g.subarray(M[r],l?g.length:M[r+1]),A=m.subarray(E[r],l?m.length:E[r+1]),d=t.length>0&&a.length>0;break;case 2:e="points",t=c.subarray(B[r],l?c.length:B[r+1]),n=p.subarray(P[r],l?p.length:P[r+1]),d=t.length>0;break;case 3:e="lines",t=c.subarray(B[r],l?c.length:B[r+1]),a=g.subarray(M[r],l?g.length:M[r+1]),d=t.length>0&&a.length>0;break;case 4:e="lines",t=c.subarray(B[r],l?c.length:B[r+1]),a=MM(t,g.subarray(M[r],l?g.length:M[r+1])),d=t.length>0&&a.length>0;break;default:continue}d&&(s.createMesh(y.apply(H,{id:Q,textureSetId:h,origin:G,primitive:e,positionsCompressed:t,normalsCompressed:i,uv:o&&o.length>0?o:null,colorsCompressed:n,indices:a,edgeIndices:A,positionsDecodeMatrix:_,color:T,metallic:L,roughness:k,opacity:R})),U.push(Q))}}U.length>0&&s.createEntity(y.apply(Q,{id:l,isObject:!0,meshIds:U}))}}}(e,t,a,s,r,o)}},FM=d.vec4(),IM=d.vec4();const DM=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 SM(e,t){const i=[];if(t.length>1)for(let e=0,s=t.length-1;e1)for(let t=0,s=e.length/3-1;t1){const t=new Uint8Array(e,n,a),i=l/2,s=t.length/l;for(let e=0;eJSON.parse(e.decode(i(Uint8Array)))}();return{metadata:s(),textureData:i(Uint8Array),eachTextureDataPortion:i(Uint32Array),eachTextureAttributes:i(Uint16Array),positions:i(Uint16Array),normals:i(Int8Array),colors:i(Uint8Array),uvs:i(Float32Array),indices:i(Uint32Array),edgeIndices:i(Uint32Array),eachTextureSetTextures:i(Int32Array),matrices:i(Float32Array),reusedGeometriesDecodeMatrix:i(Float32Array),eachGeometryPrimitiveType:i(Uint8Array),eachGeometryPositionsPortion:i(Uint32Array),eachGeometryNormalsPortion:i(Uint32Array),eachGeometryColorsPortion:i(Uint32Array),eachGeometryUVsPortion:i(Uint32Array),eachGeometryIndicesPortion:i(Uint32Array),eachGeometryEdgeIndicesPortion:i(Uint32Array),eachMeshGeometriesPortion:i(Uint32Array),eachMeshMatricesPortion:i(Uint32Array),eachMeshTextureSet:i(Int32Array),eachMeshMaterialAttributes:i(Uint8Array),eachEntityId:s(),eachEntityMeshesPortion:i(Uint32Array),eachTileAABB:i(Float64Array),eachTileEntitiesPortion:i(Uint32Array)}}(i);!function(e,t,i,s,r,o){const n=o.getNextId(),a=i.metadata,l=i.textureData,A=i.eachTextureDataPortion,h=i.eachTextureAttributes,c=i.positions,u=i.normals,p=i.colors,f=i.uvs,g=i.indices,m=i.edgeIndices,_=i.eachTextureSetTextures,v=i.matrices,b=i.reusedGeometriesDecodeMatrix,x=i.eachGeometryPrimitiveType,B=i.eachGeometryPositionsPortion,w=i.eachGeometryNormalsPortion,P=i.eachGeometryColorsPortion,C=i.eachGeometryUVsPortion,M=i.eachGeometryIndicesPortion,E=i.eachGeometryEdgeIndicesPortion,F=i.eachMeshGeometriesPortion,I=i.eachMeshMatricesPortion,D=i.eachMeshTextureSet,S=i.eachMeshMaterialAttributes,T=i.eachEntityId,R=i.eachEntityMeshesPortion,L=i.eachTileAABB,U=i.eachTileEntitiesPortion,O=A.length,k=_.length/5,N=B.length,Q=F.length,V=R.length,H=U.length;r&&r.loadData(a,{includeTypes:t.includeTypes,excludeTypes:t.excludeTypes,globalizeObjectIds:t.globalizeObjectIds});for(let e=0;e0,a=9*e,c=1===h[a+0],u=h[a+1];h[a+2],h[a+3];const d=h[a+4],p=h[a+5],f=h[a+6],g=h[a+7],m=h[a+8];if(o){const t=new Uint8Array(l.subarray(i,r)).buffer,o=`${n}-texture-${e}`;if(c)s.createTexture({id:o,buffers:[t],minFilter:d,magFilter:p,wrapS:f,wrapT:g,wrapR:m});else{const e=new Blob([t],{type:10001===u?"image/jpeg":10002===u?"image/png":"image/gif"}),i=(window.URL||window.webkitURL).createObjectURL(e),r=document.createElement("img");r.src=i,s.createTexture({id:o,image:r,minFilter:d,magFilter:p,wrapS:f,wrapT:g,wrapR:m})}}}for(let e=0;e=0?`${n}-texture-${r}`:null,normalsTextureId:a>=0?`${n}-texture-${a}`:null,metallicRoughnessTextureId:o>=0?`${n}-texture-${o}`:null,emissiveTextureId:l>=0?`${n}-texture-${l}`:null,occlusionTextureId:A>=0?`${n}-texture-${A}`:null})}const j=new Uint32Array(N);for(let e=0;e1,l=r===N-1,A=D[e],h=A>=0?`${n}-textureSet-${A}`:null,T=DM(S.subarray(6*e,6*e+3)),R=S[6*e+3]/255,L=S[6*e+4]/255,k=S[6*e+5]/255,Q=o.getNextId();if(a){const o=I[e],a=v.slice(o,o+16),A=`${n}-geometry.${i}.${r}`;let F=W[A];if(!F){F={batchThisMesh:!t.reuseGeometries};let e=!1;switch(x[r]){case 0:F.primitiveName="solid",F.geometryPositions=c.subarray(B[r],l?c.length:B[r+1]),F.geometryNormals=u.subarray(w[r],l?u.length:w[r+1]),F.geometryUVs=f.subarray(C[r],l?f.length:C[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),F.geometryEdgeIndices=m.subarray(E[r],l?m.length:E[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 1:F.primitiveName="surface",F.geometryPositions=c.subarray(B[r],l?c.length:B[r+1]),F.geometryNormals=u.subarray(w[r],l?u.length:w[r+1]),F.geometryUVs=f.subarray(C[r],l?f.length:C[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),F.geometryEdgeIndices=m.subarray(E[r],l?m.length:E[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 2:F.primitiveName="points",F.geometryPositions=c.subarray(B[r],l?c.length:B[r+1]),F.geometryColors=p.subarray(P[r],l?p.length:P[r+1]),e=F.geometryPositions.length>0;break;case 3:F.primitiveName="lines",F.geometryPositions=c.subarray(B[r],l?c.length:B[r+1]),F.geometryIndices=g.subarray(M[r],l?g.length:M[r+1]),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;case 4:F.primitiveName="lines",F.geometryPositions=c.subarray(B[r],l?c.length:B[r+1]),F.geometryIndices=SM(F.geometryPositions,g.subarray(M[r],l?g.length:M[r+1])),e=F.geometryPositions.length>0&&F.geometryIndices.length>0;break;default:continue}if(e||(F=null),F&&(F.geometryPositions.length,F.batchThisMesh)){F.decompressedPositions=new Float32Array(F.geometryPositions.length),F.transformedAndRecompressedPositions=new Uint16Array(F.geometryPositions.length);const e=F.geometryPositions,t=F.decompressedPositions;for(let i=0,s=e.length;i0&&a.length>0;break;case 1:e="surface",t=c.subarray(B[r],l?c.length:B[r+1]),i=u.subarray(w[r],l?u.length:w[r+1]),o=f.subarray(C[r],l?f.length:C[r+1]),a=g.subarray(M[r],l?g.length:M[r+1]),A=m.subarray(E[r],l?m.length:E[r+1]),d=t.length>0&&a.length>0;break;case 2:e="points",t=c.subarray(B[r],l?c.length:B[r+1]),n=p.subarray(P[r],l?p.length:P[r+1]),d=t.length>0;break;case 3:e="lines",t=c.subarray(B[r],l?c.length:B[r+1]),a=g.subarray(M[r],l?g.length:M[r+1]),d=t.length>0&&a.length>0;break;case 4:e="lines",t=c.subarray(B[r],l?c.length:B[r+1]),a=SM(t,g.subarray(M[r],l?g.length:M[r+1])),d=t.length>0&&a.length>0;break;default:continue}d&&(s.createMesh(y.apply(H,{id:Q,textureSetId:h,origin:G,primitive:e,positionsCompressed:t,normalsCompressed:i,uv:o&&o.length>0?o:null,colorsCompressed:n,indices:a,edgeIndices:A,positionsDecodeMatrix:_,color:T,metallic:L,roughness:k,opacity:R})),U.push(Q))}}U.length>0&&s.createEntity(y.apply(Q,{id:l,isObject:!0,meshIds:U}))}}}(e,t,n,s,r,o)}},RM={};RM[WC.version]=WC,RM[JC.version]=JC,RM[qC.version]=qC,RM[tM.version]=tM,RM[rM.version]=rM,RM[aM.version]=aM,RM[cM.version]=cM,RM[mM.version]=mM,RM[xM.version]=xM,RM[EM.version]=EM,RM[TM.version]=TM;class LM extends z{constructor(e,t={}){super("XKTLoader",e,t),this._maxGeometryBatchSize=t.maxGeometryBatchSize,this.textureTranscoder=t.textureTranscoder,this.dataSource=t.dataSource,this.objectDefaults=t.objectDefaults,this.includeTypes=t.includeTypes,this.excludeTypes=t.excludeTypes,this.excludeUnclassifiedObjects=t.excludeUnclassifiedObjects,this.reuseGeometries=t.reuseGeometries}get supportedVersions(){return Object.keys(RM)}get textureTranscoder(){return this._textureTranscoder}set textureTranscoder(e){this._textureTranscoder=e}get dataSource(){return this._dataSource}set dataSource(e){this._dataSource=e||new HC}get objectDefaults(){return this._objectDefaults}set objectDefaults(e){this._objectDefaults=e||HP}get includeTypes(){return this._includeTypes}set includeTypes(e){this._includeTypes=e}get excludeTypes(){return this._excludeTypes}set excludeTypes(e){this._excludeTypes=e}get excludeUnclassifiedObjects(){return this._excludeUnclassifiedObjects}set excludeUnclassifiedObjects(e){this._excludeUnclassifiedObjects=!!e}get globalizeObjectIds(){return this._globalizeObjectIds}set globalizeObjectIds(e){this._globalizeObjectIds=!!e}get reuseGeometries(){return this._reuseGeometries}set reuseGeometries(e){this._reuseGeometries=!1!==e}load(e={}){if(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),!(e.src||e.xkt||e.manifestSrc||e.manifest))return this.error("load() param expected: src, xkt, manifestSrc or manifestData"),o;const t={},i=e.includeTypes||this._includeTypes,s=e.excludeTypes||this._excludeTypes,r=e.objectDefaults||this._objectDefaults;if(t.reuseGeometries=null!==e.reuseGeometries&&void 0!==e.reuseGeometries?e.reuseGeometries:!1!==this._reuseGeometries,i){t.includeTypesMap={};for(let e=0,s=i.length;e{o.destroyed||(o.finalize(),a.finalize(),this.viewer.scene.canvas.spinner.processes--,o.once("destroyed",(()=>{this.viewer.metaScene.destroyMetaModel(a.id)})),this.scheduleTask((()=>{o.destroyed||(o.scene.fire("modelLoaded",o.id),o.fire("loaded",!0,!1))})))},A=e=>{this.viewer.scene.canvas.spinner.processes--,this.error(e),o.fire("error",e)};let h=0;const c={getNextId:()=>`${n}.${h++}`};if(e.metaModelSrc||e.metaModelData)if(e.metaModelSrc){const r=e.metaModelSrc;this._dataSource.getMetaModel(r,(r=>{o.destroyed||(a.loadData(r,{includeTypes:i,excludeTypes:s,globalizeObjectIds:t.globalizeObjectIds}),e.src?this._loadModel(e.src,e,t,o,null,c,l,A):(this._parseModel(e.xkt,e,t,o,null,c),l()))}),(e=>{A(`load(): Failed to load model metadata for model '${n} from '${r}' - ${e}`)}))}else e.metaModelData&&(a.loadData(e.metaModelData,{includeTypes:i,excludeTypes:s,globalizeObjectIds:t.globalizeObjectIds}),e.src?this._loadModel(e.src,e,t,o,null,c,l,A):(this._parseModel(e.xkt,e,t,o,null,c),l()));else if(e.src)this._loadModel(e.src,e,t,o,a,c,l,A);else if(e.xkt)this._parseModel(e.xkt,e,t,o,a,c),l();else if(e.manifestSrc||e.manifest){const r=e.manifestSrc?function(e){const t=e.split("/");return t.pop(),t.join("/")+"/"}(e.manifestSrc):"",n=(e,n,l)=>{let A=0;const h=()=>{o.destroyed||A>=e.length?n():this._dataSource.getMetaModel(`${r}${e[A]}`,(e=>{a.loadData(e,{includeTypes:i,excludeTypes:s,globalizeObjectIds:t.globalizeObjectIds}),A++,this.scheduleTask(h,200)}),l)};h()},h=(i,s,n)=>{let a=0;const l=()=>{o.destroyed||a>=i.length?s():this._dataSource.getXKT(`${r}${i[a]}`,(i=>{this._parseModel(i,e,t,o,null,c),o.preFinalize(),a++,this.scheduleTask(l,200)}),n)};l()},u=(i,s,n)=>{let l=0;const A=()=>{o.destroyed||l>=i.length?s():this._dataSource.getXKT(`${r}${i[l]}`,(i=>{this._parseModel(i,e,t,o,a,c),o.preFinalize(),l++,this.scheduleTask(A,200)}),n)};A()};if(e.manifest){const t=e.manifest,i=t.xktFiles;if(!i||0===i.length)return void A("load(): Failed to load model manifest - manifest not valid");const s=t.metaModelFiles;s?n(s,(()=>{h(i,l,A)}),A):u(i,l,A)}else this._dataSource.getManifest(e.manifestSrc,(e=>{if(o.destroyed)return;const t=e.xktFiles;if(!t||0===t.length)return void A("load(): Failed to load model manifest - manifest not valid");const i=e.metaModelFiles;i?n(i,(()=>{h(t,l,A)}),A):u(t,l,A)}),A)}return o}_loadModel(e,t,i,s,r,o,n,a){this._dataSource.getXKT(t.src,(e=>{this._parseModel(e,t,i,s,r,o),s.preFinalize(),n()}),a)}async _parseModel(e,t,i,s,r,o){if(s.destroyed)return;const n=new DataView(e),a=new Uint8Array(e),l=n.getUint32(0,!0),A=RM[l];if(!A)return void this.error("Unsupported .XKT file version: "+l+" - this XKTLoaderPlugin supports versions "+Object.keys(RM));if(A.parseArrayBuffer)return void A.parseArrayBuffer(this.viewer,i,e,s,r,o);const h=n.getUint32(4,!0),c=[];let u=4*(h+2);for(let e=0;ee.size)throw new RangeError("offset:"+t+", length:"+i+", size:"+e.size);return e.slice?e.slice(t,t+i):e.webkitSlice?e.webkitSlice(t,t+i):e.mozSlice?e.mozSlice(t,t+i):e.msSlice?e.msSlice(t,t+i):void 0}(e,t,i))}catch(e){r(e)}}}function p(){}function f(e){var i,s=this;s.init=function(e){i=new Blob([],{type:n}),e()},s.writeUint8Array=function(e,s){i=new Blob([i,t?e:e.buffer],{type:n}),s()},s.getData=function(t,s){var r=new FileReader;r.onload=function(e){t(e.target.result)},r.onerror=s,r.readAsText(i,e)}}function g(t){var i=this,s="",r="";i.init=function(e){s+="data:"+(t||"")+";base64,",e()},i.writeUint8Array=function(t,i){var o,n=r.length,a=r;for(r="",o=0;o<3*Math.floor((n+t.length)/3)-n;o++)a+=String.fromCharCode(t[o]);for(;o2?s+=e.btoa(a):r=a,i()},i.getData=function(t){t(s+e.btoa(r))}}function m(e){var i,s=this;s.init=function(t){i=new Blob([],{type:e}),t()},s.writeUint8Array=function(s,r){i=new Blob([i,t?s:s.buffer],{type:e}),r()},s.getData=function(e){e(i)}}function _(e,t,i,s,r,n,a,l,A,h){var c,u,d,p=0,f=t.sn;function g(){e.removeEventListener("message",m,!1),l(u,d)}function m(t){var i=t.data,r=i.data,o=i.error;if(o)return o.toString=function(){return"Error: "+this.message},void A(o);if(i.sn===f)switch("number"==typeof i.codecTime&&(e.codecTime+=i.codecTime),"number"==typeof i.crcTime&&(e.crcTime+=i.crcTime),i.type){case"append":r?(u+=r.length,s.writeUint8Array(r,(function(){_()}),h)):_();break;case"flush":d=i.crc,r?(u+=r.length,s.writeUint8Array(r,(function(){g()}),h)):g();break;case"progress":a&&a(c+i.loaded,n);break;case"importScripts":case"newTask":case"echo":break;default:console.warn("zip.js:launchWorkerProcess: unknown message: ",i)}}function _(){(c=p*o)<=n?i.readUint8Array(r+c,Math.min(o,n-c),(function(i){a&&a(c,n);var s=0===c?t:{sn:f};s.type="append",s.data=i;try{e.postMessage(s,[i.buffer])}catch(t){e.postMessage(s)}p++}),A):e.postMessage({sn:f,type:"flush"})}u=0,e.addEventListener("message",m,!1),_()}function v(e,t,i,s,r,n,l,A,h,c){var u,d=0,p=0,f="input"===n,g="output"===n,m=new a;!function n(){var a;if((u=d*o)127?r[i-128]:String.fromCharCode(i);return s}function x(e){return decodeURIComponent(escape(e))}function B(e){var t,i="";for(t=0;t>16,i=65535&e;try{return new Date(1980+((65024&t)>>9),((480&t)>>5)-1,31&t,(63488&i)>>11,(2016&i)>>5,2*(31&i),0)}catch(e){}}(e.lastModDateRaw),1!=(1&e.bitFlag)?((s||8!=(8&e.bitFlag))&&(e.crc32=t.view.getUint32(i+10,!0),e.compressedSize=t.view.getUint32(i+14,!0),e.uncompressedSize=t.view.getUint32(i+18,!0)),4294967295!==e.compressedSize&&4294967295!==e.uncompressedSize?(e.filenameLength=t.view.getUint16(i+22,!0),e.extraFieldLength=t.view.getUint16(i+24,!0)):r("File is using Zip64 (4gb+ file size).")):r("File contains encrypted entry.")}function P(t,o,n){var a=0;function l(){}l.prototype.getData=function(s,o,l,h){var c=this;function u(e,t){h&&!function(e){var t=A(4);return t.view.setUint32(0,e),c.crc32==t.view.getUint32(0)}(t)?n("CRC failed."):s.getData((function(e){o(e)}))}function d(e){n(e||r)}function p(e){n(e||"Error while writing file data.")}t.readUint8Array(c.offset,30,(function(r){var o,f=A(r.length,r);1347093252==f.view.getUint32(0)?(w(c,f,4,!1,n),o=c.offset+30+c.filenameLength+c.extraFieldLength,s.init((function(){0===c.compressionMethod?b(c._worker,a++,t,s,o,c.compressedSize,h,u,l,d,p):function(t,i,s,r,o,n,a,l,A,h,c){var u=a?"output":"none";e.zip.useWebWorkers?_(t,{sn:i,codecClass:"Inflater",crcType:u},s,r,o,n,A,l,h,c):v(new e.zip.Inflater,s,r,o,n,u,A,l,h,c)}(c._worker,a++,t,s,o,c.compressedSize,h,u,l,d,p)}),p)):n(i)}),d)};var h={getEntries:function(e){var r=this._worker;!function(e){t.size<22?n(i):r(22,(function(){r(Math.min(65558,t.size),(function(){n(i)}))}));function r(i,r){t.readUint8Array(t.size-i,i,(function(t){for(var i=t.length-22;i>=0;i--)if(80===t[i]&&75===t[i+1]&&5===t[i+2]&&6===t[i+3])return void e(new DataView(t.buffer,i,22));r()}),(function(){n(s)}))}}((function(o){var a,h;a=o.getUint32(16,!0),h=o.getUint16(8,!0),a<0||a>=t.size?n(i):t.readUint8Array(a,t.size-a,(function(t){var s,o,a,c,u=0,d=[],p=A(t.length,t);for(s=0;s>>8^i[255&(t^e[s])];this.crc=t},a.prototype.get=function(){return~this.crc},a.prototype.table=function(){var e,t,i,s=[];for(e=0;e<256;e++){for(i=e,t=0;t<8;t++)1&i?i=i>>>1^3988292384:i>>>=1;s[e]=i}return s}(),l.prototype.append=function(e,t){return e},l.prototype.flush=function(){},c.prototype=new h,c.prototype.constructor=c,u.prototype=new h,u.prototype.constructor=u,d.prototype=new h,d.prototype.constructor=d,p.prototype.getData=function(e){e(this.data)},f.prototype=new p,f.prototype.constructor=f,g.prototype=new p,g.prototype.constructor=g,m.prototype=new p,m.prototype.constructor=m;var F={deflater:["z-worker.js","deflate.js"],inflater:["z-worker.js","inflate.js"]};function I(t,i,s){if(null===e.zip.workerScripts||null===e.zip.workerScriptsPath){var r;if(e.zip.workerScripts){if(r=e.zip.workerScripts[t],!Array.isArray(r))return void s(new Error("zip.workerScripts."+t+" is not an array!"));r=function(e){var t=document.createElement("a");return e.map((function(e){return t.href=e,t.href}))}(r)}else(r=F[t].slice(0))[0]=(e.zip.workerScriptsPath||"")+r[0];var o=new Worker(r[0]);o.codecTime=o.crcTime=0,o.postMessage({type:"importScripts",scripts:r.slice(1)}),o.addEventListener("message",(function e(t){var r=t.data;if(r.error)return o.terminate(),void s(r.error);"importScripts"===r.type&&(o.removeEventListener("message",e),o.removeEventListener("error",n),i(o))})),o.addEventListener("error",n)}else s(new Error("Either zip.workerScripts or zip.workerScriptsPath may be set, not both."));function n(e){o.terminate(),s(e)}}function D(e){console.error(e)}e.zip={Reader:h,Writer:p,BlobReader:d,Data64URIReader:u,TextReader:c,BlobWriter:m,Data64URIWriter:g,TextWriter:f,createReader:function(e,t,i){i=i||D,e.init((function(){P(e,t,i)}),i)},createWriter:function(e,t,i,s){i=i||D,s=!!s,e.init((function(){E(e,t,i,s)}),i)},useWebWorkers:!0,workerScriptsPath:null,workerScripts:null}}(UM);const OM=UM.zip;!function(e){var t,i,s=e.Reader,r=e.Writer;try{i=0===new Blob([new DataView(new ArrayBuffer(0))]).size}catch(e){}function o(e){var t=this;function i(i,s){var r;t.data?i():((r=new XMLHttpRequest).addEventListener("load",(function(){t.size||(t.size=Number(r.getResponseHeader("Content-Length"))||Number(r.response.byteLength)),t.data=new Uint8Array(r.response),i()}),!1),r.addEventListener("error",s,!1),r.open("GET",e),r.responseType="arraybuffer",r.send())}t.size=0,t.init=function(s,r){if(function(e){var t=document.createElement("a");return t.href=e,"http:"===t.protocol||"https:"===t.protocol}(e)){var o=new XMLHttpRequest;o.addEventListener("load",(function(){t.size=Number(o.getResponseHeader("Content-Length")),t.size?s():i(s,r)}),!1),o.addEventListener("error",r,!1),o.open("HEAD",e),o.send()}else i(s,r)},t.readUint8Array=function(e,s,r,o){i((function(){r(new Uint8Array(t.data.subarray(e,e+s)))}),o)}}function n(e){var t=this;t.size=0,t.init=function(i,s){var r=new XMLHttpRequest;r.addEventListener("load",(function(){t.size=Number(r.getResponseHeader("Content-Length")),"bytes"==r.getResponseHeader("Accept-Ranges")?i():s("HTTP Range not supported.")}),!1),r.addEventListener("error",s,!1),r.open("HEAD",e),r.send()},t.readUint8Array=function(t,i,s,r){!function(t,i,s,r){var o=new XMLHttpRequest;o.open("GET",e),o.responseType="arraybuffer",o.setRequestHeader("Range","bytes="+t+"-"+(t+i-1)),o.addEventListener("load",(function(){s(o.response)}),!1),o.addEventListener("error",r,!1),o.send()}(t,i,(function(e){s(new Uint8Array(e))}),r)}}function a(e){var t=this;t.size=0,t.init=function(i,s){t.size=e.byteLength,i()},t.readUint8Array=function(t,i,s,r){s(new Uint8Array(e.slice(t,t+i)))}}function l(){var e,t=this;t.init=function(t,i){e=new Uint8Array,t()},t.writeUint8Array=function(t,i,s){var r=new Uint8Array(e.length+t.length);r.set(e),r.set(t,e.length),e=r,i()},t.getData=function(t){t(e.buffer)}}function A(e,t){var s,r=this;r.init=function(t,i){e.createWriter((function(e){s=e,t()}),i)},r.writeUint8Array=function(e,r,o){var n=new Blob([i?e:e.buffer],{type:t});s.onwrite=function(){s.onwrite=null,r()},s.onerror=o,s.write(n)},r.getData=function(t){e.file(t)}}o.prototype=new s,o.prototype.constructor=o,n.prototype=new s,n.prototype.constructor=n,a.prototype=new s,a.prototype.constructor=a,l.prototype=new r,l.prototype.constructor=l,A.prototype=new r,A.prototype.constructor=A,e.FileWriter=A,e.HttpReader=o,e.HttpRangeReader=n,e.ArrayBufferReader=a,e.ArrayBufferWriter=l,e.fs&&((t=e.fs.ZipDirectoryEntry).prototype.addHttpContent=function(i,s,r){return function(i,s,r,o){if(i.directory)return o?new t(i.fs,s,r,i):new e.fs.ZipFileEntry(i.fs,s,r,i);throw"Parent entry is not a directory."}(this,i,{data:s,Reader:r?n:o})},t.prototype.importHttpContent=function(e,t,i,s){this.importZip(t?new n(e):new o(e),i,s)},e.fs.FS.prototype.importHttpContent=function(e,i,s,r){this.entries=[],this.root=new t(this),this.root.importHttpContent(e,i,s,r)})}(OM);const kM=["4.2"];class NM{constructor(e,t={}){this.supportedSchemas=kM,this._xrayOpacity=.7,this._src=null,this._options=t,this.viewpoint=null,t.workerScriptsPath?(OM.workerScriptsPath=t.workerScriptsPath,this.src=t.src,this.xrayOpacity=.7,this.displayEffect=t.displayEffect,this.createMetaModel=t.createMetaModel):e.error("Config expected: workerScriptsPath")}load(e,t,i,s,r,o){switch(s.materialType){case"MetallicMaterial":t._defaultMaterial=new zr(t,{baseColor:[1,1,1],metallic:.6,roughness:.6});break;case"SpecularMaterial":t._defaultMaterial=new Xr(t,{diffuse:[1,1,1],specular:d.vec3([1,1,1]),glossiness:.5});break;default:t._defaultMaterial=new oi(t,{reflectivity:.75,shiness:100,diffuse:[1,1,1]})}t._wireframeMaterial=new Hr(t,{color:[0,0,0],lineWidth:2});var n=t.scene.canvas.spinner;n.processes++,QM(e,t,i,s,(function(){n.processes--,r&&r(),t.fire("loaded",!0,!1)}),(function(e){n.processes--,t.error(e),o&&o(e),t.fire("error",e)}),(function(e){console.log("Error, Will Robinson: "+e)}))}}var QM=function(e,t,i,s,r,o){!function(e,t,i){var s=new XM;s.load(e,(function(){t(s)}),(function(e){i("Error loading ZIP archive: "+e)}))}(i,(function(i){VM(e,i,s,t,r,o)}),o)},VM=function(){return function(t,i,s,r,o){var n={plugin:t,zip:i,edgeThreshold:30,materialType:s.materialType,scene:r.scene,modelNode:r,info:{references:{}},materials:{}};s.createMetaModel&&(n.metaModelData={modelId:r.id,metaObjects:[{name:r.id,type:"Default",id:r.id}]}),r.scene.loading++,function(t,i){t.zip.getFile("Manifest.xml",(function(s,r){for(var o=r.children,n=0,a=o.length;n0){for(var n=o.trim().split(" "),a=new Int16Array(n.length),l=0,A=0,h=n.length;A0){i.primitive="triangles";for(var o=[],n=0,a=r.length;n=t.length)i();else{var a=t[o].id,l=a.lastIndexOf(":");l>0&&(a=a.substring(l+1));var A=a.lastIndexOf("#");A>0&&(a=a.substring(0,A)),s[a]?r(o+1):function(e,t,i){e.zip.getFile(t,(function(t,s){!function(e,t,i){for(var s,r=t.children,o=0,n=r.length;o0)for(var s=0,r=t.length;s-1?e+"&_="+t:e+"?_="+t}getIFC(e,t,i){e=this._cacheBusterURL(e);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),i=new Uint8Array(e);for(var n=0;n{this._parseModel(e,t,i,s),r.processes--}),(e=>{r.processes--,this.error(e),s.fire("error",e)}))}_parseModel(e,t,i,s){if(s.destroyed)return;const r=t.stats||{};if(r.sourceFormat="IFC",r.schemaVersion="",r.title="",r.author="",r.created="",r.numMetaObjects=0,r.numPropertySets=0,r.numObjects=0,r.numGeometries=0,r.numTriangles=0,r.numVertices=0,!this._ifcAPI)throw"WebIFCLoaderPlugin has no WebIFC instance configured - please inject via WebIFCLoaderPlugin constructor";const o=new Uint8Array(e),n=this._ifcAPI.OpenModel(o),a=this._ifcAPI.GetModelSchema(n),l=this._ifcAPI.GetLineIDsWithType(n,this._webIFC.IFCPROJECT).get(0),A=!1!==t.loadMetadata,h={modelID:n,modelSchema:a,sceneModel:s,loadMetadata:A,metadata:A?{id:"",projectId:""+l,author:"",createdAt:"",schema:"",creatingApplication:"",metaObjects:[],propertySets:[]}:null,metaObjects:{},options:i,log:function(e){},nextId:0,stats:r};if(A){if(i.includeTypes){h.includeTypes={};for(let e=0,t=i.includeTypes.length;e{s.destroyed||(s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1))}))}_parseMetaObjects(e){const t=this._ifcAPI.GetLineIDsWithType(e.modelID,this._webIFC.IFCPROJECT).get(0),i=this._ifcAPI.GetLine(e.modelID,t);this._parseSpatialChildren(e,i)}_parseSpatialChildren(e,t,i){const s=this._ifcAPI.GetNameFromTypeCode(t.type);if(e.includeTypes&&!e.includeTypes[s])return;if(e.excludeTypes&&e.excludeTypes[s])return;this._createMetaObject(e,t,i);const r=t.GlobalId.value;this._parseRelatedItemsOfType(e,t.expressID,"RelatingObject","RelatedObjects",this._webIFC.IFCRELAGGREGATES,r),this._parseRelatedItemsOfType(e,t.expressID,"RelatingStructure","RelatedElements",this._webIFC.IFCRELCONTAINEDINSPATIALSTRUCTURE,r)}_createMetaObject(e,t,i){const s=t.GlobalId.value,r=this._ifcAPI.GetNameFromTypeCode(t.type),o={id:s,name:t.Name&&""!==t.Name.value?t.Name.value:r,type:r,parent:i};e.metadata.metaObjects.push(o),e.metaObjects[s]=o,e.stats.numMetaObjects++}_parseRelatedItemsOfType(e,t,i,s,r,o){const n=this._ifcAPI.GetLineIDsWithType(e.modelID,r);for(let r=0;re.value)).includes(t)}else h=A.value===t;if(h){const t=l[s];if(Array.isArray(t))t.forEach((t=>{const i=this._ifcAPI.GetLine(e.modelID,t.value);this._parseSpatialChildren(e,i,o)}));else{const i=this._ifcAPI.GetLine(e.modelID,t.value);this._parseSpatialChildren(e,i,o)}}}}_parsePropertySets(e){const t=this._ifcAPI.GetLineIDsWithType(e.modelID,this._webIFC.IFCRELDEFINESBYPROPERTIES);for(let i=0;i0){const o="Default",n=t.Name.value,a=[];for(let e=0,t=s.length;e{const i=t.expressID,s=t.geometries,r=[],o=this._ifcAPI.GetLine(e.modelID,i).GlobalId.value;if(e.loadMetadata){const t=o,i=e.metaObjects[t];if(e.includeTypes&&(!i||!e.includeTypes[i.type]))return;if(e.excludeTypes&&(!i||e.excludeTypes[i.type]))return}const n=d.mat4(),a=d.vec3();for(let t=0,i=s.size();t-1?e+"&_="+t:e+"?_="+t}getLAS(e,t,i){e=this._cacheBusterURL(e);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),i=new Uint8Array(e);for(var n=0;n{let t=0,i=0,s=0;const r=new DataView(e),o=new Uint8Array(6e3),n=({item:s,format:o,size:n})=>{let a,l;switch(o){case"char":return l=new Uint8Array(e,t,n),t+=n,a=oE(l),[s,a];case"uShort":return a=r.getUint16(t,!0),t+=n,[s,a];case"uLong":return a=r.getUint32(t,!0),"NumberOfVariableLengthRecords"===s&&(i=a),t+=n,[s,a];case"uChar":return a=r.getUint8(t),t+=n,[s,a];case"double":return a=r.getFloat64(t,!0),t+=n,[s,a];default:t+=n}};return(()=>{const e={};tE.forEach((t=>{const i=n({...t});if(void 0!==i){if("FileSignature"===i[0]&&"LASF"!==i[1])throw new Error("Ivalid FileSignature. Is this a LAS/LAZ file");e[i[0]]=i[1]}}));const r=[];let a=i;for(;a--;){const e={};iE.forEach((i=>{const r=n({...i});e[r[0]]=r[1],"UserId"===r[0]&&"LASF_Projection"===r[1]&&(s=t-18+54)})),r.push(e)}const l=(e=>{if(void 0===e)return;const t=s+e.RecordLengthAfterHeader,i=o.slice(s,t),r=rE(i),n=new DataView(r);let a=6,l=Number(n.getUint16(a,!0));const A=[];for(;l--;){const e={};e.key=n.getUint16(a+=2,!0),e.tiffTagLocation=n.getUint16(a+=2,!0),e.count=n.getUint16(a+=2,!0),e.valueOffset=n.getUint16(a+=2,!0),A.push(e)}const h=A.find((e=>3072===e.key));if(h&&h.hasOwnProperty("valueOffset"))return h.valueOffset})(r.find((e=>"LASF_Projection"===e.UserId)));return l&&(e.epsg=l),e})()},rE=e=>{let t=new ArrayBuffer(e.length),i=new Uint8Array(t);for(let t=0;t{let t="";return e.forEach((e=>{let i=String.fromCharCode(e);"\0"!==i&&(t+=i)})),t.trim()};class nE extends z{constructor(e,t={}){super("lasLoader",e,t),this.dataSource=t.dataSource,this.skip=t.skip,this.fp64=t.fp64,this.colorDepth=t.colorDepth}get dataSource(){return this._dataSource}set dataSource(e){this._dataSource=e||new $M}get skip(){return this._skip}set skip(e){this._skip=e||1}get fp64(){return this._fp64}set fp64(e){this._fp64=!!e}get colorDepth(){return this._colorDepth}set colorDepth(e){this._colorDepth=e||"auto"}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 Gc(this.viewer.scene,y.apply(e,{maxGeometryBatchSize:5e5,isModel:!0}));if(!e.src&&!e.las)return this.error("load() param expected: src or las"),t;const i={las:{skip:this._skip,fp64:this._fp64,colorDepth:this._colorDepth}};if(e.src)this._loadModel(e.src,e,i,t);else{const s=this.viewer.scene.canvas.spinner;s.processes++,this._parseModel(e.las,e,i,t).then((()=>{s.processes--}),(e=>{s.processes--,this.error(e),t.fire("error",e)}))}return t}_loadModel(e,t,i,s){const r=this.viewer.scene.canvas.spinner;r.processes++,this._dataSource.getLAS(t.src,(e=>{this._parseModel(e,t,i,s).then((()=>{r.processes--}),(e=>{r.processes--,this.error(e),s.fire("error",e)}))}),(e=>{r.processes--,this.error(e),s.fire("error",e)}))}_parseModel(e,t,i,s){function r(e){const i=e.value;if(t.rotateX&&i)for(let e=0,t=i.length;e{if(s.destroyed)return void l();const A=t.stats||{};A.sourceFormat="LAS",A.schemaVersion="",A.title="",A.author="",A.created="",A.numMetaObjects=0,A.numPropertySets=0,A.numObjects=0,A.numGeometries=0,A.numTriangles=0,A.numVertices=0;try{const A=sE(e);eB(e,eE,i).then((e=>{const h=e.attributes,c=e.loaderData,u=void 0!==c.pointsFormatId?c.pointsFormatId:-1;if(!h.POSITION)return s.finalize(),void l("No positions found in file");let p,f;switch(u){case 0:p=r(h.POSITION),f=n(h.intensity);break;case 1:if(!h.intensity)return s.finalize(),void l("No positions found in file");p=r(h.POSITION),f=n(h.intensity);break;case 2:case 3:if(!h.intensity)return s.finalize(),void l("No positions found in file");p=r(h.POSITION),f=o(h.COLOR_0,h.intensity)}const g=aE(p,15e5),m=aE(f,2e6),_=[];for(let e=0,t=g.length;e{s.destroyed||(s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1))})),a()}))}catch(e){s.finalize(),l(e)}}))}}function aE(e,t){if(t>=e.length)return[e];let i=[];for(let s=0;s-1?e+"&_="+t:e+"?_="+t}getCityJSON(e,t,i){y.loadJSON(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}}function AE(e,t,i){i=i||2;var s,r,o,n,a,l,A,h=t&&t.length,c=h?t[0]*i:e.length,u=hE(e,0,c,i,!0),d=[];if(!u||u.next===u.prev)return d;if(h&&(u=function(e,t,i,s){var r,o,n,a=[];for(r=0,o=t.length;r80*i){s=o=e[0],r=n=e[1];for(var p=i;po&&(o=a),l>n&&(n=l);A=0!==(A=Math.max(o-s,n-r))?1/A:0}return uE(u,d,i,s,r,A),d}function hE(e,t,i,s,r){var o,n;if(r===RE(e,t,i,s)>0)for(o=t;o=t;o-=s)n=DE(o,e[o],e[o+1],n);return n&&PE(n,n.next)&&(SE(n),n=n.next),n}function cE(e,t){if(!e)return e;t||(t=e);var i,s=e;do{if(i=!1,s.steiner||!PE(s,s.next)&&0!==wE(s.prev,s,s.next))s=s.next;else{if(SE(s),(s=t=s.prev)===s.next)break;i=!0}}while(i||s!==t);return t}function uE(e,t,i,s,r,o,n){if(e){!n&&o&&function(e,t,i,s){var r=e;do{null===r.z&&(r.z=bE(r.x,r.y,t,i,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==e);r.prevZ.nextZ=null,r.prevZ=null,function(e){var t,i,s,r,o,n,a,l,A=1;do{for(i=e,e=null,o=null,n=0;i;){for(n++,s=i,a=0,t=0;t0||l>0&&s;)0!==a&&(0===l||!s||i.z<=s.z)?(r=i,i=i.nextZ,a--):(r=s,s=s.nextZ,l--),o?o.nextZ=r:e=r,r.prevZ=o,o=r;i=s}o.nextZ=null,A*=2}while(n>1)}(r)}(e,s,r,o);for(var a,l,A=e;e.prev!==e.next;)if(a=e.prev,l=e.next,o?pE(e,s,r,o):dE(e))t.push(a.i/i),t.push(e.i/i),t.push(l.i/i),SE(e),e=l.next,A=l.next;else if((e=l)===A){n?1===n?uE(e=fE(cE(e),t,i),t,i,s,r,o,2):2===n&&gE(e,t,i,s,r,o):uE(cE(e),t,i,s,r,o,1);break}}}function dE(e){var t=e.prev,i=e,s=e.next;if(wE(t,i,s)>=0)return!1;for(var r=e.next.next;r!==e.prev;){if(xE(t.x,t.y,i.x,i.y,s.x,s.y,r.x,r.y)&&wE(r.prev,r,r.next)>=0)return!1;r=r.next}return!0}function pE(e,t,i,s){var r=e.prev,o=e,n=e.next;if(wE(r,o,n)>=0)return!1;for(var a=r.xo.x?r.x>n.x?r.x:n.x:o.x>n.x?o.x:n.x,h=r.y>o.y?r.y>n.y?r.y:n.y:o.y>n.y?o.y:n.y,c=bE(a,l,t,i,s),u=bE(A,h,t,i,s),d=e.prevZ,p=e.nextZ;d&&d.z>=c&&p&&p.z<=u;){if(d!==e.prev&&d!==e.next&&xE(r.x,r.y,o.x,o.y,n.x,n.y,d.x,d.y)&&wE(d.prev,d,d.next)>=0)return!1;if(d=d.prevZ,p!==e.prev&&p!==e.next&&xE(r.x,r.y,o.x,o.y,n.x,n.y,p.x,p.y)&&wE(p.prev,p,p.next)>=0)return!1;p=p.nextZ}for(;d&&d.z>=c;){if(d!==e.prev&&d!==e.next&&xE(r.x,r.y,o.x,o.y,n.x,n.y,d.x,d.y)&&wE(d.prev,d,d.next)>=0)return!1;d=d.prevZ}for(;p&&p.z<=u;){if(p!==e.prev&&p!==e.next&&xE(r.x,r.y,o.x,o.y,n.x,n.y,p.x,p.y)&&wE(p.prev,p,p.next)>=0)return!1;p=p.nextZ}return!0}function fE(e,t,i){var s=e;do{var r=s.prev,o=s.next.next;!PE(r,o)&&CE(r,s,s.next,o)&&FE(r,o)&&FE(o,r)&&(t.push(r.i/i),t.push(s.i/i),t.push(o.i/i),SE(s),SE(s.next),s=e=o),s=s.next}while(s!==e);return cE(s)}function gE(e,t,i,s,r,o){var n=e;do{for(var a=n.next.next;a!==n.prev;){if(n.i!==a.i&&BE(n,a)){var l=IE(n,a);return n=cE(n,n.next),l=cE(l,l.next),uE(n,t,i,s,r,o),void uE(l,t,i,s,r,o)}a=a.next}n=n.next}while(n!==e)}function mE(e,t){return e.x-t.x}function _E(e,t){if(t=function(e,t){var i,s=t,r=e.x,o=e.y,n=-1/0;do{if(o<=s.y&&o>=s.next.y&&s.next.y!==s.y){var a=s.x+(o-s.y)*(s.next.x-s.x)/(s.next.y-s.y);if(a<=r&&a>n){if(n=a,a===r){if(o===s.y)return s;if(o===s.next.y)return s.next}i=s.x=s.x&&s.x>=h&&r!==s.x&&xE(oi.x||s.x===i.x&&vE(i,s)))&&(i=s,u=l)),s=s.next}while(s!==A);return i}(e,t),t){var i=IE(t,e);cE(t,t.next),cE(i,i.next)}}function vE(e,t){return wE(e.prev,e,t.prev)<0&&wE(t.next,e,e.next)<0}function bE(e,t,i,s,r){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-i)*r)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-s)*r)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function yE(e){var t=e,i=e;do{(t.x=0&&(e-n)*(s-a)-(i-n)*(t-a)>=0&&(i-n)*(o-a)-(r-n)*(s-a)>=0}function BE(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){var i=e;do{if(i.i!==e.i&&i.next.i!==e.i&&i.i!==t.i&&i.next.i!==t.i&&CE(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}(e,t)&&(FE(e,t)&&FE(t,e)&&function(e,t){var i=e,s=!1,r=(e.x+t.x)/2,o=(e.y+t.y)/2;do{i.y>o!=i.next.y>o&&i.next.y!==i.y&&r<(i.next.x-i.x)*(o-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==e);return s}(e,t)&&(wE(e.prev,e,t.prev)||wE(e,t.prev,t))||PE(e,t)&&wE(e.prev,e,e.next)>0&&wE(t.prev,t,t.next)>0)}function wE(e,t,i){return(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y)}function PE(e,t){return e.x===t.x&&e.y===t.y}function CE(e,t,i,s){var r=EE(wE(e,t,i)),o=EE(wE(e,t,s)),n=EE(wE(i,s,e)),a=EE(wE(i,s,t));return r!==o&&n!==a||(!(0!==r||!ME(e,i,t))||(!(0!==o||!ME(e,s,t))||(!(0!==n||!ME(i,e,s))||!(0!==a||!ME(i,t,s)))))}function ME(e,t,i){return t.x<=Math.max(e.x,i.x)&&t.x>=Math.min(e.x,i.x)&&t.y<=Math.max(e.y,i.y)&&t.y>=Math.min(e.y,i.y)}function EE(e){return e>0?1:e<0?-1:0}function FE(e,t){return wE(e.prev,e,e.next)<0?wE(e,t,e.next)>=0&&wE(e,e.prev,t)>=0:wE(e,t,e.prev)<0||wE(e,e.next,t)<0}function IE(e,t){var i=new TE(e.i,e.x,e.y),s=new TE(t.i,t.x,t.y),r=e.next,o=t.prev;return e.next=t,t.prev=e,i.next=r,r.prev=i,s.next=i,i.prev=s,o.next=s,s.prev=o,s}function DE(e,t,i,s){var r=new TE(e,t,i);return s?(r.next=s.next,r.prev=s,s.next.prev=r,s.next=r):(r.prev=r,r.next=r),r}function SE(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function TE(e,t,i){this.i=e,this.x=t,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function RE(e,t,i,s){for(var r=0,o=t,n=i-s;o0&&(s+=e[r-1].length,i.holes.push(s))}return i};const LE=d.vec2(),UE=d.vec3(),OE=d.vec3(),kE=d.vec3();class NE extends z{constructor(e,t={}){super("cityJSONLoader",e,t),this.dataSource=t.dataSource}get dataSource(){return this._dataSource}set dataSource(e){this._dataSource=e||new lE}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 Gc(this.viewer.scene,y.apply(e,{isModel:!0,edges:!0}));if(!e.src&&!e.cityJSON)return this.error("load() param expected: src or cityJSON"),t;const i={};if(e.src)this._loadModel(e.src,e,i,t);else{const s=this.viewer.scene.canvas.spinner;s.processes++,this._parseModel(e.cityJSON,e,i,t),s.processes--}return t}_loadModel(e,t,i,s){const r=this.viewer.scene.canvas.spinner;r.processes++,this._dataSource.getCityJSON(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){if(s.destroyed)return;const r=e.transform?this._transformVertices(e.vertices,e.transform,i.rotateX):e.vertices,o=t.stats||{};o.sourceFormat=e.type||"CityJSON",o.schemaVersion=e.version||"",o.title="",o.author="",o.created="",o.numMetaObjects=0,o.numPropertySets=0,o.numObjects=0,o.numGeometries=0,o.numTriangles=0,o.numVertices=0;const n=!1!==t.loadMetadata,a=n?{id:d.createUUID(),name:"Model",type:"Model"}:null,l=n?{id:"",projectId:"",author:"",createdAt:"",schema:e.version||"",creatingApplication:"",metaObjects:[a],propertySets:[]}:null,A={data:e,vertices:r,sceneModel:s,loadMetadata:n,metadata:l,rootMetaObject:a,nextId:0,stats:o};if(this._parseCityJSON(A),s.finalize(),n){const e=s.id;this.viewer.metaScene.createMetaModel(e,A.metadata,i)}s.scene.once("tick",(()=>{s.destroyed||(s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1))}))}_transformVertices(e,t,i){const s=[],r=t.scale||d.vec3([1,1,1]),o=t.translate||d.vec3([0,0,0]);for(let t=0,n=0;t0))return;const o=[];for(let i=0,s=t.geometry.length;i0){const r=t[s[0]];if(void 0!==r.value)n=e[r.value];else{const t=r.values;if(t){a=[];for(let s=0,r=t.length;s0&&(s.createEntity({id:i,meshIds:o,isObject:!0}),e.stats.numObjects++)}_parseGeometrySurfacesWithOwnMaterials(e,t,i,s){switch(t.type){case"MultiPoint":case"MultiLineString":break;case"MultiSurface":case"CompositeSurface":const r=t.boundaries;this._parseSurfacesWithOwnMaterials(e,i,r,s);break;case"Solid":const o=t.boundaries;for(let t=0;t0&&h.push(A.length);const i=this._extractLocalIndices(e,a[t],c,u);A.push(...i)}if(3===A.length)u.indices.push(A[0]),u.indices.push(A[1]),u.indices.push(A[2]);else if(A.length>3){const e=[];for(let t=0;t0&&n.indices.length>0){const t=""+e.nextId++;r.createMesh({id:t,primitive:"triangles",positions:n.positions,indices:n.indices,color:i&&i.diffuseColor?i.diffuseColor:[.8,.8,.8],opacity:1}),s.push(t),e.stats.numGeometries++,e.stats.numVertices+=n.positions.length/3,e.stats.numTriangles+=n.indices.length/3}}_parseSurfacesWithSharedMaterial(e,t,i,s){const r=e.vertices;for(let o=0;o0&&a.push(n.length);const l=this._extractLocalIndices(e,t[o][r],i,s);n.push(...l)}if(3===n.length)s.indices.push(n[0]),s.indices.push(n[1]),s.indices.push(n[2]);else if(n.length>3){let e=[];for(let t=0;t-1?e+"&_="+t:e+"?_="+t}getDotBIM(e,t,i){y.loadJSON(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}}class VE extends z{constructor(e,t={}){super("DotBIMLoader",e,t),this.dataSource=t.dataSource,this.objectDefaults=t.objectDefaults}set dataSource(e){this._dataSource=e||new QE}get dataSource(){return this._dataSource}set objectDefaults(e){this._objectDefaults=e||HP}get objectDefaults(){return this._objectDefaults}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 Gc(this.viewer.scene,y.apply(e,{isModel:!0,backfaces:e.backfaces,dtxEnabled:e.dtxEnabled,rotation:e.rotation,origin:e.origin})),i=t.id;if(!e.src&&!e.dotBIM)return this.error("load() param expected: src or dotBIM"),t;const s=e.objectDefaults||this._objectDefaults||HP;let r,o;if(e.includeTypes){r={};for(let t=0,i=e.includeTypes.length;t{const t=e.fileData,n=e.sceneModel,a={},l=d.createUUID(),A=d.createUUID(),h=d.createUUID(),c=d.createUUID(),u={metaObjects:[{id:l,name:"Project",type:"Project",parent:null},{id:A,name:"Site",type:"Site",parent:l},{id:h,name:"Building",type:"Building",parent:A},{id:c,name:"BuildingStorey",type:"BuildingStorey",parent:h}],propertySets:[]},p=(e,i)=>{if(a[e])return;const s=t.meshes.find((e=>e.mesh_id===i.mesh_id));n.createGeometry({id:e,primitive:"triangles",positions:s.coordinates,indices:s.indices}),a[e]=!0},f=t.elements;for(let e=0,i=f.length;ee.mesh_id===i.mesh_id));for(let t=0,i=e.length;t{n.destroyed||(n.scene.fire("modelLoaded",n.id),n.fire("loaded",!0,!1))}))};if(e.src){const i=e.src;this.viewer.scene.canvas.spinner.processes++,this._dataSource.getDotBIM(i,(e=>{n({fileData:e,sceneModel:t,nextId:0,error:function(e){}}),this.viewer.scene.canvas.spinner.processes--}),(e=>{this.viewer.scene.canvas.spinner.processes--,this.error(e)}))}else if(e.dotBIM){const i={fileData:e.dotBIM,sceneModel:t,nextId:0,error:function(e){}};n(i)}return t.once("destroyed",(()=>{this.viewer.metaScene.destroyMetaModel(i)})),t}destroy(){super.destroy()}}const HE=function(e){const t=t=>parseInt(e.substr(t+1,2),16)/255;return[t(0),t(2),t(4)]},jE=function(e){const t=[];for(let i=0;i=0?h:2*Math.PI-h}return r(e[0]-i[0])*(t[1]-i[1])-(t[0]-i[0])*(e[1]-i[1]);return(t,i,s,r)=>{const o=e(t,i,s),n=e(t,s,r),a=e(t,r,i);return!((o<0||n<0||a<0)&&(o>0||n>0||a>0))}}(),r=[],o=(i?t:t.slice(0).reverse()).map((e=>({idx:e})));o.forEach(((e,t)=>{e.prev=o[(t-1+o.length)%o.length],e.next=o[(t+1)%o.length]}));const n=d.vec2(),a=d.vec2();for(;o.length>2;){let t=0;for(;;){if(t>=o.length)throw`isCCW = ${i}; earIdx = ${t}; len = ${o.length}`;const r=o[t],l=e[r.prev.idx],A=e[r.idx],h=e[r.next.idx];if(d.subVec2(l,A,n),d.subVec2(h,A,a),n[0]*a[1]-n[1]*a[0]>=0&&o.every((t=>t===r||t===r.prev||t===r.next||!s(e[t.idx],l,A,h))))break;++t}const l=o[t];o.splice(t,1),r.push([l.idx,l.next.idx,l.prev.idx]);l.prev.next=l.next;l.next.prev=l.prev}return[e,r,i]},GE=function(e,t){const i=e.canvas.canvas,s=i.parentNode,r=document.createElement("div");s.insertBefore(r,i);let o=5;r.style.background=t,r.style.border="2px solid white",r.style.margin="0 0",r.style.zIndex="100",r.style.position="absolute",r.style.pointerEvents="none",r.style.display="none";const n=new pe(e,{}),a=e=>e+"px",l=function(){const e=n.canvasPos.slice();ge(i,s,e),r.style.left=a(e[0]-3-o/2),r.style.top=a(e[1]-3-o/2),r.style.borderRadius=a(2*o),r.style.width=a(o),r.style.height=a(o)},A=e.camera.on("viewMatrix",l),h=e.camera.on("projMatrix",l);return{update:function(e){e&&(n.worldPos=e,l()),r.style.display=e?"":"none"},setHighlighted:function(e){o=e?10:5,l()},getCanvasPos:()=>n.canvasPos,getWorldPos:()=>n.worldPos,destroy:function(){r.parentNode.removeChild(r),e.camera.off(A),e.camera.off(h),n.destroy()}}},zE=function(e,t,i){let s=null;const r=r=>{if(r){s&&s.destroy();try{const[o,n]=jE(r.map((e=>[e[0],e[2]]))),a=[].concat(...o.map((e=>[e[0],r[0][1],e[1]]))),l=[].concat(...n);s=new wr(e,{pickable:!1,geometry:new ei(e,{positions:a,indices:l,normals:d.buildNormals(a,l)}),material:new oi(e,{alpha:void 0!==i?i:.5,backfaces:!0,diffuse:HE(t)})})}catch(e){s=null}}s&&(s.visible=!!r)};return r(null),{updateBase:r,destroy:()=>s&&s.destroy()}},WE=function(e,t){return function(i,s,r){const o=e.scene,n=o.canvas.canvas,a=(e,t)=>(t[0]=e.clientX,t[1]=e.clientY,ge(n.ownerDocument.documentElement,n,t),t),l=e=>{const i=d.vec3(),s=d.vec3();return d.canvasPosToWorldRay(n,o.camera.viewMatrix,o.camera.projMatrix,o.camera.projection,e,i,s),t(i,s)};let A=!1;const h=function(){A=!1},c=function(){h(),n.removeEventListener("mousedown",p),n.removeEventListener("mousemove",f),e.cameraControl.off(g),n.removeEventListener("mouseup",m)},u=d.vec2(),p=function(e){1===e.which&&(a(e,u),A=!0)};n.addEventListener("mousedown",p);const f=function(e){const t=a(e,d.vec2());A&&d.distVec2(u,t)>20&&(h(),i())};n.addEventListener("mousemove",f);const g=e.cameraControl.on("rayMove",(e=>{const t=e.canvasPos;s(t,l(t))})),m=function(e){if(1===e.which&&A){c();const t=a(e,d.vec2());r(t,l(t))}};return n.addEventListener("mouseup",m),c}},KE=function(e,t,i,s){const r=-(d.dotVec3(i,t)-e)/d.dotVec3(s,t);{const e=d.vec3();return d.mulVec3Scalar(s,r,e),d.addVec3(i,e,e),e}};class XE extends R{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={},this.plugin.viewer.scene,this._geometry=t.geometry,t.onMouseOver,t.onMouseLeave,t.onContextMenu,this._alpha="alpha"in t&&void 0!==t.alpha?t.alpha:.5,this.color=t.color,this._visible=!0,this._rebuildMesh()}_rebuildMesh(){const e=this.plugin.viewer.scene,t=this._geometry.planeCoordinates.slice(),i=this._geometry.height<0,s=this._geometry.altitude+(i?this._geometry.height:0),r=this._geometry.height*(i?-1:1),[o,n,a]=jE(t),l=[],A=[],h=e=>{const t=l.length;for(let t of o)l.push([t[0],s+(e?r:0),t[1]]);for(let i of n)A.push(...(e?i:i.slice(0).reverse()).map((e=>e+t)))};h(!1),h(!0);for(let e=0;ee+c)))}this._zoneMesh&&this._zoneMesh.destroy();const c=[].concat(...l);this._zoneMesh=new wr(e,{edges:this._edges,geometry:new ei(e,{positions:c,indices:A,normals:d.buildNormals(c,A)}),material:new oi(e,{alpha:this._alpha,backfaces:!0,diffuse:HE(this._color)}),visible:this._visible}),this._zoneMesh.highlighted=this._highlighted,this._zoneMesh.zone=this;{const e=d.vec2(),t=d.vec2();let i=0;for(let s of n){const r=o[s[0]],n=o[s[1]],a=o[s[2]];d.subVec2(n,r,e),d.subVec2(a,r,t),i+=Math.abs(e[0]*t[1]-e[1]*t[0])}this._baseArea=i/2}this._metrics=null;const u=e=>Math.min(...l.map((t=>t[e]))),p=e=>Math.max(...l.map((t=>t[e]))),f=u(0),g=u(1),m=u(2),_=p(0),v=p(1),b=p(2);this._center=d.vec3([(f+_)/2,(g+v)/2,(m+b)/2])}get baseArea(){return this._baseArea}get area(){return this._getMetrics().area}get volume(){return this._getMetrics().volume}_getMetrics(){if(null===this._metrics){let e=0,t=0;const i=this._zoneMesh.geometry,s=[d.vec3(),d.vec3(),d.vec3()],r=d.vec3();for(let o=0;o{const s=t.map((t=>[t[0],e?r:o,t[1]]));i.push(e?s:s.slice(0).reverse())};n(!0),n(!1);const a=(e,i)=>[t[e][0],i,t[e][1]];for(let e=0;ei?a:n;h|=A,c.push(A)}switch(h){case n:case a:o.push(t);break;case l:break;case A:const i=[];for(let o=0;o=3&&o.push(i)}}i=o}if(0===i.length)return null;{const e=d.vec3([0,0,0]),t=new Set;for(const s of i)for(const i of s){const s=i.map((e=>e.toFixed(3))).join(":");t.has(s)||(t.add(s),d.addVec3(e,i,e))}return d.mulVec3Scalar(e,1/t.size,e),e}}get center(){return this._center}get altitude(){return this._geometry.altitude}set altitude(e){this._geometry.altitude=e,this._rebuildMesh()}get height(){return this._geometry.height}set height(e){this._geometry.height=e,this._rebuildMesh()}get highlighted(){return this._highlighted}set highlighted(e){this._highlighted=e,this._zoneMesh&&(this._zoneMesh.highlighted=e)}set color(e){this._color=e,this._zoneMesh&&(this._zoneMesh.material.diffuse=HE(this._color))}get color(){return this._color}set alpha(e){this._alpha=e,this._zoneMesh&&(this._zoneMesh.material.alpha=this._alpha)}get alpha(){return this._alpha}get edges(){return this._edges}set edges(e){this._edges=e,this._zoneMesh&&(this._zoneMesh.edges=this._edges)}set visible(e){this._visible=!!e,this._zoneMesh.visible=this._visible,this._needUpdate()}get visible(){return this._visible}getJSON(){return{id:this.id,geometry:this._geometry,alpha:this._alpha,color:this._color}}duplicate(){return this.plugin.createZone({id:d.createUUID(),geometry:{planeCoordinates:this._geometry.planeCoordinates.map((e=>e.slice())),altitude:this._geometry.altitude,height:this._geometry.height},alpha:this._alpha,color:this._color})}destroy(){this._zoneMesh.destroy(),super.destroy()}}class JE extends R{constructor(e,t,i){super(e.viewer.scene),this.zonesPlugin=e,this.pointerLens=t.pointerLens,this.createSelect3dPoint=i,this._deactivate=null}get active(){return!!this._deactivate}activate(e,t,i,s){if(this._deactivate)return;if("object"==typeof e&&null!==e){const r=e,o=(e,t)=>{if(e in r)return r[e];if(void 0!==t)return t;throw"config missing: "+e};e=o("altitude"),t=o("height"),i=o("color","#008000"),s=o("alpha",.5)}const r=this.zonesPlugin,o=r.viewer,n=o.scene,a=this,l=this.createSelect3dPoint(o,((t,i)=>KE(e,d.vec3([0,1,0]),t,i)));!function o(){const A=zE(n,i,s),h=function(e,t,i,s,r,o){const n=GE(e,t),a=GE(e,t),l=i?function(e){i.visible=!!e,e&&(i.canvasPos=e)}:()=>{};let A=s((()=>{l(null),n.update(null)}),((e,t)=>{l(e),n.update(t)}),(function(e,t){n.update(t),A=s((function(){l(null),a.update(null),r(null)}),(function(e,i){l(e),a.update(i),r(d.distVec3(t,i)>.01&&[t,i])}),(function(e,i){a.update(i),n.destroy(),a.destroy(),l(null),o([t,i])}))}));return{deactivate:function(){A(),n.destroy(),a.destroy(),l(null)}}}(n,i,a.pointerLens,l,(e=>{if(e){const t=e[0],i=e[1],s=e=>Math.min(t[e],i[e]),r=e=>Math.max(t[e],i[e]),o=s(0),n=s(1),a=s(2),l=r(0);r(1);const h=r(2);A.updateBase([[o,n,h],[l,n,h],[l,n,a],[o,n,a]])}else A.updateBase(null)}),(n=>{A.destroy();const l=function(e,t,i,s,r,o,n){const a=i=>Math.min(e[i],t[i]),l=i=>Math.max(e[i],t[i]),A=a(0),h=a(2),c=l(0),u=l(2);return n.createZone({id:d.createUUID(),geometry:{planeCoordinates:[[A,u],[c,u],[c,h],[A,h]],altitude:i,height:s},alpha:o,color:r})}(n[0],n[1],e,t,i,s,r);let h=!0;a._deactivate=()=>{h=!1},a.fire("zoneEnd",l),h&&o()})).deactivate;a._deactivate=()=>{h(),A.destroy()}}()}deactivate(){this._deactivate&&(this._deactivate(),this._deactivate=null)}destroy(){this.deactivate(),super.destroy()}}class YE extends JE{constructor(e,t={}){super(e,t,((e,t)=>WE(e,t)))}}class ZE extends JE{constructor(e,t={}){const i=new G(e.viewer);super(e,t,((e,t)=>be(e,i,t))),this.pointerCircle=i}destroy(){this.pointerCircle.destroy(),super.destroy()}}class qE extends z{constructor(e,t={}){super("Zones",e),this._pointerLens=t.pointerLens,this._container=t.container||document.body,this._zones=[],this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.zIndex=t.zIndex||1e4,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,zone:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,zone:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,zone:t,event:e})}}createZone(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=new XE(this,{id:e.id,plugin:this,container:this._container,geometry:e.geometry,alpha:e.alpha,color:e.color,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._zones.push(t),t.on("destroyed",(()=>{const e=this._zones.indexOf(t);e>=0&&this._zones.splice(e,1)})),this.fire("zoneCreated",t),t}get zones(){return this._zones}destroy(){super.destroy()}}const $E=function(e,t,i,s,r,o,n,a,l){const A=o?function(e){o.visible=!!e,e&&(o.canvasPos=e)}:()=>{};let h;const c=[()=>A(null)],u=zE(e,s,r);return c.push((()=>u.destroy())),function o(p){const f=GE(e,s),g=p.length>0&&function(e,t,i){const s=e.canvas.canvas,r=new pe(e,{});r.worldPos=i;const o=new pe(e,{}),n=s.ownerDocument.body,a=new ye(n,{color:t,thickness:1,thicknessClickable:6});a.setVisible(!1);const l=function(){const e=r.canvasPos.slice(),t=o.canvasPos.slice();ge(s,n,e),ge(s,n,t),a.setStartAndEnd(e[0],e[1],t[0],t[1])},A=e.camera.on("viewMatrix",l),h=e.camera.on("projMatrix",l);return{update:function(e){e&&(o.worldPos=e,l()),a.setVisible(!!e)},destroy:function(){e.camera.off(A),e.camera.off(h),r.destroy(),o.destroy(),a.destroy()}}}(e,s,p[p.length-1].getWorldPos());c.push((()=>{f.destroy(),g&&g.destroy()}));const m=p.length>0&&p[0],_=function(e){const t=m&&m.getCanvasPos();return t&&d.distVec2(t,e)<10&&{canvasPos:t,worldPos:m.getWorldPos()}},v=function(){const e=(e,t,i)=>t[0]<=Math.max(e[0],i[0])&&t[0]>=Math.min(e[0],i[0])&&t[1]<=Math.max(e[1],i[1])&&t[1]>=Math.min(e[1],i[1]),t=(e,t,i)=>{const s=(t[1]-e[1])*(i[0]-t[0])-(t[0]-e[0])*(i[1]-t[1]);return 0===s?0:s>0?1:2};return function(i,s){const r=i[i.length-2],o=i[i.length-1];for(let n=s?1:0;n{A(null),f.update(null),g&&g.update(null),u.updateBase(p.length>2?p.map((e=>e.getWorldPos())):null)}),((e,t)=>{const i=p.length>2&&_(e);if(m&&m.setHighlighted(!!i),A(i?i.canvasPos:e),f.update(!i&&t),g&&g.update(i?i.worldPos:t),p.length>=2){const e=p.map((e=>e.getWorldPos())).concat(i?[]:[t]),s=v(e.map((e=>[e[0],e[2]])),i);u.updateBase(s?null:e)}else u.updateBase(null)}),(function(e,a){const A=p.length>2&&_(e),h=p.map((e=>e.getWorldPos())).concat(A?[]:[a]);u.updateBase(h);const m=h.map((e=>[e[0],e[2]]));p.length>2&&v(m,A)?(c.pop()(),o(p)):A?(f.update(a),c.forEach((e=>e())),l(n.createZone({id:d.createUUID(),geometry:{planeCoordinates:m,altitude:t,height:i},alpha:r,color:s}))):(f.update(a),g&&g.update(a),o(p.concat(f)))}))}([]),{closeSurface:function(){throw"TODO"},deactivate:function(){h(),c.forEach((e=>e()))}}};class eF extends R{constructor(e,t={}){super(e.viewer.scene),this.zonesPlugin=e,this.pointerLens=t.pointerLens,this._action=null}get active(){return!!this._action}activate(e,t,i,s){if("object"==typeof e&&null!==e){const r=e,o=(e,t)=>{if(e in r)return r[e];if(void 0!==t)return t;throw"config missing: "+e};e=o("altitude"),t=o("height"),i=o("color","#008000"),s=o("alpha",.5)}if(this._action)return;const r=this.zonesPlugin,o=r.viewer,n=o.scene,a=this,l=WE(o,(function(t,i){return KE(e,d.vec3([0,1,0]),t,i)}));!function o(){a._action=$E(n,e,t,i,s,a.pointerLens,r,l,(e=>{let t=!0;a._action={deactivate:()=>{t=!1}},a.fire("zoneEnd",e),t&&o()}))}()}deactivate(){this._action&&(this._action.deactivate(),this._action=null)}destroy(){this.deactivate(),super.destroy()}}class tF extends R{constructor(e,t={}){super(e.viewer.scene),this.zonesPlugin=e,this.pointerLens=t.pointerLens,this.pointerCircle=new G(e.viewer),this._action=null}get active(){return!!this._action}activate(e,t,i,s){if("object"==typeof e&&null!==e){const r=e,o=(e,t)=>{if(e in r)return r[e];if(void 0!==t)return t;throw"config missing: "+e};e=o("altitude"),t=o("height"),i=o("color","#008000"),s=o("alpha",.5)}if(this._action)return;const r=this.zonesPlugin,o=r.viewer,n=o.scene,a=this,l=be(o,this.pointerCircle,(function(t,i){return KE(e,d.vec3([0,1,0]),t,i)}));!function o(){a._action=$E(n,e,t,i,s,a.pointerLens,r,l,(e=>{let t=!0;a._action={deactivate:()=>{t=!1}},a.fire("zoneEnd",e),t&&o()}))}()}deactivate(){this._action&&(this._action.deactivate(),this._action=null)}destroy(){this.deactivate(),super.destroy()}}class iF extends R{constructor(e,t,i,s){const r=e.plugin.viewer,o=r.scene;super(o);const n=e._geometry.altitude,a=e._geometry.planeCoordinates.map((t=>{const i=o.canvas.canvas.ownerDocument.body,s=new me(o,{},i,{fillColor:e._color});return s.worldPos=d.vec3([t[0],n,t[1]]),s.on("worldPos",(function(){t[0]=s.worldPos[0],t[1]=s.worldPos[2];try{e._rebuildMesh()}catch(t){e._zoneMesh&&(e._zoneMesh.destroy(),e._zoneMesh=null)}})),s})),l=ve({viewer:r,handleMouseEvents:i,handleTouchEvents:s,pointerLens:t&&t.pointerLens,dots:a,ray2WorldPos:(e,t)=>KE(n,d.vec3([0,1,0]),e,t),onEnd:(t,i)=>(e._zoneMesh&&this.fire("edited"),!!e._zoneMesh)}),A=function(){l(),a.forEach((e=>e.destroy()))},h=e.on("destroyed",A);this._deactivate=function(){e.off("destroyed",h),A()}}deactivate(){this._deactivate(),super.destroy()}}class sF extends iF{constructor(e,t){super(e,t,!0,!1)}}class rF extends iF{constructor(e,t){super(e,t,!1,!0)}}class oF extends R{constructor(e,t,i,s){const r=e.plugin.viewer,o=r.scene,n=o.canvas.canvas;super(o);const a=this,l=e._geometry.altitude,A=t&&t.pointerLens,h=A?function(e){A.visible=!!e,e&&(A.canvasPos=e)}:()=>{},c=e=>{const t=d.vec3(),i=d.vec3();return d.canvasPosToWorldRay(n,o.camera.viewMatrix,o.camera.projMatrix,o.camera.projection,e,t,i),s=t,r=i,KE(l,d.vec3([0,1,0]),s,r);var s,r},u=(e,t)=>(t[0]=e.clientX,t[1]=e.clientY,ge(n.ownerDocument.documentElement,n,t),t),p=function(e,t){const i=e=>{e.preventDefault(),t(e)};return n.addEventListener(e,i),()=>n.removeEventListener(e,i)};let f=()=>{};const g=function(t,i,s,o){const l=o(t),A=u(l,d.vec2()),g=r.scene.pick({canvasPos:A,includeEntities:[e._zoneMesh.id]});if((g&&g.entity&&g.entity.zone)===e){f(),n.style.cursor="move",r.cameraControl.active=!1;const t=function(){const t=e._geometry.planeCoordinates.map((e=>e.slice())),i=c(A),s=d.vec2([i[0],i[2]]),r=d.vec2();return function(i){const o=c(i);r[0]=o[0],r[1]=o[2],d.subVec2(s,r,r),e._geometry.planeCoordinates.forEach(((e,i)=>{d.subVec2(t[i],r,e)}));try{e._rebuildMesh()}catch(t){e._zoneMesh&&(e._zoneMesh.destroy(),e._zoneMesh=null)}}}(),l=p(i,(function(e){const i=o(e);if(i){const e=u(i,d.vec2());t(e),h(e)}})),g=p(s,(function(e){const i=o(e);if(i){const e=u(i,d.vec2());t(e),h(null),f(),a.fire("translated")}}));f=function(){f=()=>{},n.style.cursor="default",r.cameraControl.active=!0,l(),g()}}},m=[];i&&m.push(p("mousedown",(e=>{1===e.which&&g(e,"mousemove","mouseup",(e=>1===e.which&&e))}))),s&&m.push(p("touchstart",(e=>{if(1===e.touches.length){const t=e.touches[0].identifier;g(e,"touchmove","touchend",(e=>[...e.changedTouches].find((e=>e.identifier===t))))}})));const _=function(){f(),m.forEach((e=>e())),h(null)},v=e.on("destroyed",_);this._deactivate=function(){e.off("destroyed",v),_()}}deactivate(){this._deactivate(),super.destroy()}}class nF extends oF{constructor(e,t){super(e,t,!0,!1)}}class aF extends oF{constructor(e,t){super(e,t,!1,!0)}}export{Gi as AlphaFormat,Ht as AmbientLight,De as AngleMeasurementEditMouseControl,Se as AngleMeasurementEditTouchControl,Ce as AngleMeasurementsControl,Me as AngleMeasurementsMouseControl,Ee as AngleMeasurementsPlugin,Fe as AngleMeasurementsTouchControl,Oe as AnnotationsPlugin,Ir as AxisGizmoPlugin,Zc as BCFViewpointsPlugin,bo as Bitmap,Ri as ByteType,Hu as CameraMemento,yu as CameraPath,Eu as CameraPathAnimation,NE as CityJSONLoaderPlugin,yi as ClampToEdgeWrapping,R as Component,Ts as CompressedMediaType,Fn as Configs,o as ContextMenu,Ku as CubicBezierCurve,_u as Curve,hc as DefaultLoadingManager,Ji as DepthFormat,Yi as DepthStencilFormat,Vt as DirLight,hu as DistanceMeasurementEditControl,cu as DistanceMeasurementEditMouseControl,uu as DistanceMeasurementEditTouchControl,nu as DistanceMeasurementsControl,au as DistanceMeasurementsMouseControl,lu as DistanceMeasurementsPlugin,Au as DistanceMeasurementsTouchControl,me as Dot3D,QE as DotBIMDefaultDataSource,VE as DotBIMLoaderPlugin,Ai as EdgeMaterial,ai as EmphasisMaterial,BC as FaceAlignedSectionPlanesPlugin,du as FastNavPlugin,Ni as FloatType,ro as Fresnel,N as Frustum,k as FrustumPlane,Is as GIFMediaType,pu as GLTFDefaultDataSource,jP as GLTFLoaderPlugin,Qi as HalfFloatType,Tu as ImagePlane,Oi as IntType,Ds as JPEGMediaType,gc as KTX2TextureTranscoder,nE as LASLoaderPlugin,Hr as LambertMaterial,Qu as LightMap,Wc as LineSet,Es as LinearEncoding,Ei as LinearFilter,Si as LinearMipMapLinearFilter,Ii as LinearMipMapNearestFilter,Di as LinearMipmapLinearFilter,Fi as LinearMipmapNearestFilter,cc as Loader,Ac as LoadingManager,fu as LocaleService,Xi as LuminanceAlphaFormat,Ki as LuminanceFormat,e as Map,pe as Marker,H as MarqueePicker,j as MarqueePickerMouseControl,wr as Mesh,To as MeshSurfaceArea,Po as MeshVolume,zr as MetallicMaterial,xi as MirroredRepeatWrapping,Gu as ModelMemento,KP as NavCubePlugin,Bi as NearestFilter,Mi as NearestMipMapLinearFilter,wi as NearestMipMapNearestFilter,Ci as NearestMipmapLinearFilter,Pi as NearestMipmapNearestFilter,Vr as Node,iC as OBJLoaderPlugin,f as ObjectsKdTree3,Wu as ObjectsMemento,Ss as PNGMediaType,Xu as Path,Yu as PerformanceModel,oi as PhongMaterial,Ge as PickResult,z as Plugin,Ru as PointLight,G as PointerCircle,n as PointerLens,Ju as QuadraticBezierCurve,g as Queue,Wi as RGBAFormat,ts as RGBAIntegerFormat,ws as RGBA_ASTC_10x10_Format,ys as RGBA_ASTC_10x5_Format,xs as RGBA_ASTC_10x6_Format,Bs as RGBA_ASTC_10x8_Format,Ps as RGBA_ASTC_12x10_Format,Cs as RGBA_ASTC_12x12_Format,ds as RGBA_ASTC_4x4_Format,ps as RGBA_ASTC_5x4_Format,fs as RGBA_ASTC_5x5_Format,gs as RGBA_ASTC_6x5_Format,ms as RGBA_ASTC_6x6_Format,_s as RGBA_ASTC_8x5_Format,vs as RGBA_ASTC_8x6_Format,bs as RGBA_ASTC_8x8_Format,Ms as RGBA_BPTC_Format,us as RGBA_ETC2_EAC_Format,As as RGBA_PVRTC_2BPPV1_Format,ls as RGBA_PVRTC_4BPPV1_Format,ss as RGBA_S3TC_DXT1_Format,rs as RGBA_S3TC_DXT3_Format,os as RGBA_S3TC_DXT5_Format,zi as RGBFormat,hs as RGB_ETC1_Format,cs as RGB_ETC2_Format,as as RGB_PVRTC_2BPPV1_Format,ns as RGB_PVRTC_4BPPV1_Format,is as RGB_S3TC_DXT1_Format,$i as RGFormat,es as RGIntegerFormat,ei as ReadableGeometry,Zi as RedFormat,qi as RedIntegerFormat,Nu as ReflectionMap,bi as RepeatWrapping,PC as STLDefaultDataSource,RC as STLLoaderPlugin,Gc as SceneModel,ko as SceneModelMesh,Lc as SceneModelTransform,Dr as SectionPlane,hC as SectionPlanesPlugin,Li as ShortType,Zu as Skybox,wC as SkyboxesPlugin,Xr as SpecularMaterial,vu as SplineCurve,Vu as SpriteMarker,fC as StoreyViewsPlugin,so as Texture,qu as TextureTranscoder,OC as TreeViewPlugin,Ti as UnsignedByteType,ji as UnsignedInt248Type,ki as UnsignedIntType,Vi as UnsignedShort4444Type,Hi as UnsignedShort5551Type,Ui as UnsignedShortType,ao as VBOGeometry,VC as ViewCullPlugin,Qb as Viewer,qM as WebIFCLoaderPlugin,pc as WorkerPool,HC as XKTDefaultDataSource,LM as XKTLoaderPlugin,YM as XML3DLoaderPlugin,iF as ZoneEditControl,sF as ZoneEditMouseControl,rF as ZoneEditTouchControl,oF as ZoneTranslateControl,nF as ZoneTranslateMouseControl,aF as ZoneTranslateTouchControl,YE as ZonesMouseControl,qE as ZonesPlugin,eF as ZonesPolysurfaceMouseControl,tF as ZonesPolysurfaceTouchControl,ZE as ZonesTouchControl,_e as activateDraggableDot,ve as activateDraggableDots,ti as buildBoxGeometry,co as buildBoxLinesGeometry,uo as buildBoxLinesGeometryFromAABB,Cr as buildCylinderGeometry,po as buildGridGeometry,vo as buildLineGeometry,fo as buildPlaneGeometry,mo as buildPolylineGeometry,_o as buildPolylineGeometryFromCurve,Mr as buildSphereGeometry,go as buildTorusGeometry,Fr as buildVectorTextGeometry,J as createRTCViewMat,V as frustumIntersectsAABB3,_c as getKTX2TextureTranscoder,$ as getPlaneRTCPos,yo as isTriangleMeshSolid,Ao as load3DSGeometry,ho as loadOBJGeometry,d as math,Ro as meshSurfaceArea,Co as meshVolume,q as rtcToWorldPos,Fs as sRGBEncoding,Q as setFrustum,m as stats,be as touchPointSelector,ge as transformToNode,y as utils,Y as worldToRTCPos,Z as worldToRTCPositions}; diff --git a/dist/xeokit-sdk.min.es5.js b/dist/xeokit-sdk.min.es5.js index fdbc73ab1..e1d1235c6 100644 --- a/dist/xeokit-sdk.min.es5.js +++ b/dist/xeokit-sdk.min.es5.js @@ -33,4 +33,4 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */var Op=function(e,t){return Op=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},Op(e,t)};function Np(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}Op(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}var Qp=function(){return Qp=Object.assign||function(e){for(var t,i=1,r=arguments.length;i0&&s[s.length-1])||6!==n[0]&&2!==n[0])){o=0;continue}if(3===n[0]&&(!s||n[1]>s[0]&&n[1]=55296&&s<=56319&&i>10),o%1024+56320)),(s+1===i||r.length>16384)&&(n+=String.fromCharCode.apply(String,r),r.length=0)}return n},Xp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Jp="undefined"==typeof Uint8Array?[]:new Uint8Array(256),Yp=0;Yp=0){if(e<55296||e>56319&&e<=65535)return t=((t=this.index[e>>5])<<2)+(31&e),this.data[t];if(e<=65535)return t=((t=this.index[2048+(e-55296>>5)])<<2)+(31&e),this.data[t];if(e>11),t=this.index[t],t+=e>>5&63,t=((t=this.index[t])<<2)+(31&e),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},e}(),rf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",sf="undefined"==typeof Uint8Array?[]:new Uint8Array(256),nf=0;nf>4,c[l++]=(15&r)<<4|s>>2,c[l++]=(3&s)<<6|63&n;return u}(e),o=Array.isArray(n)?function(e){for(var t=e.length,i=[],r=0;r0;){var o=r[--n];if(Array.isArray(e)?-1!==e.indexOf(o):e===o)for(var a=i;a<=r.length;){var l;if((l=r[++a])===t)return!0;if(l!==of)break}if(o!==of)break}return!1},Qf=function(e,t){for(var i=e;i>=0;){var r=t[i];if(r!==of)return r;i--}return 0},Vf=function(e,t,i,r,s){if(0===i[r])return"×";var n=r-1;if(Array.isArray(s)&&!0===s[n])return"×";var o=n-1,a=n+1,l=t[n],u=o>=0?t[o]:0,c=t[a];if(2===l&&3===c)return"×";if(-1!==Sf.indexOf(l))return"!";if(-1!==Sf.indexOf(c))return"×";if(-1!==Tf.indexOf(c))return"×";if(8===Qf(n,t))return"÷";if(11===If.get(e[n]))return"×";if((l===bf||l===xf)&&11===If.get(e[a]))return"×";if(7===l||7===c)return"×";if(9===l)return"×";if(-1===[of,af,lf].indexOf(l)&&9===c)return"×";if(-1!==[uf,cf,Af,ff,_f].indexOf(c))return"×";if(Qf(n,t)===pf)return"×";if(Nf(23,pf,n,t))return"×";if(Nf([uf,cf],df,n,t))return"×";if(Nf(12,12,n,t))return"×";if(l===of)return"÷";if(23===l||23===c)return"×";if(16===c||16===l)return"÷";if(-1!==[af,lf,df].indexOf(c)||14===l)return"×";if(36===u&&-1!==Of.indexOf(l))return"×";if(l===_f&&36===c)return"×";if(c===hf)return"×";if(-1!==Df.indexOf(c)&&l===vf||-1!==Df.indexOf(l)&&c===vf)return"×";if(l===mf&&-1!==[Pf,bf,xf].indexOf(c)||-1!==[Pf,bf,xf].indexOf(l)&&c===gf)return"×";if(-1!==Df.indexOf(l)&&-1!==Lf.indexOf(c)||-1!==Lf.indexOf(l)&&-1!==Df.indexOf(c))return"×";if(-1!==[mf,gf].indexOf(l)&&(c===vf||-1!==[pf,lf].indexOf(c)&&t[a+1]===vf)||-1!==[pf,lf].indexOf(l)&&c===vf||l===vf&&-1!==[vf,_f,ff].indexOf(c))return"×";if(-1!==[vf,_f,ff,uf,cf].indexOf(c))for(var A=n;A>=0;){if((h=t[A])===vf)return"×";if(-1===[_f,ff].indexOf(h))break;A--}if(-1!==[mf,gf].indexOf(c))for(A=-1!==[uf,cf].indexOf(l)?o:n;A>=0;){var h;if((h=t[A])===vf)return"×";if(-1===[_f,ff].indexOf(h))break;A--}if(Cf===l&&-1!==[Cf,Mf,wf,Bf].indexOf(c)||-1!==[Mf,wf].indexOf(l)&&-1!==[Mf,Ef].indexOf(c)||-1!==[Ef,Bf].indexOf(l)&&c===Ef)return"×";if(-1!==Uf.indexOf(l)&&-1!==[hf,gf].indexOf(c)||-1!==Uf.indexOf(c)&&l===mf)return"×";if(-1!==Df.indexOf(l)&&-1!==Df.indexOf(c))return"×";if(l===ff&&-1!==Df.indexOf(c))return"×";if(-1!==Df.concat(vf).indexOf(l)&&c===pf&&-1===kf.indexOf(e[a])||-1!==Df.concat(vf).indexOf(c)&&l===cf)return"×";if(41===l&&41===c){for(var d=i[n],p=1;d>0&&41===t[--d];)p++;if(p%2!=0)return"×"}return l===bf&&c===xf?"×":"÷"},Hf=function(e,t){t||(t={lineBreak:"normal",wordBreak:"normal"});var i=function(e,t){void 0===t&&(t="strict");var i=[],r=[],s=[];return e.forEach((function(e,n){var o=If.get(e);if(o>50?(s.push(!0),o-=50):s.push(!1),-1!==["normal","auto","loose"].indexOf(t)&&-1!==[8208,8211,12316,12448].indexOf(e))return r.push(n),i.push(16);if(4===o||11===o){if(0===n)return r.push(n),i.push(yf);var a=i[n-1];return-1===Rf.indexOf(a)?(r.push(r[n-1]),i.push(a)):(r.push(n),i.push(yf))}return r.push(n),31===o?i.push("strict"===t?df:Pf):o===Ff||29===o?i.push(yf):43===o?e>=131072&&e<=196605||e>=196608&&e<=262141?i.push(Pf):i.push(yf):void i.push(o)})),[r,i,s]}(e,t.lineBreak),r=i[0],s=i[1],n=i[2];"break-all"!==t.wordBreak&&"break-word"!==t.wordBreak||(s=s.map((function(e){return-1!==[vf,yf,Ff].indexOf(e)?Pf:e})));var o="keep-all"===t.wordBreak?n.map((function(t,i){return t&&e[i]>=19968&&e[i]<=40959})):void 0;return[r,s,o]},jf=function(){function e(e,t,i,r){this.codePoints=e,this.required="!"===t,this.start=i,this.end=r}return e.prototype.slice=function(){return Kp.apply(void 0,this.codePoints.slice(this.start,this.end))},e}(),Gf=function(e){return e>=48&&e<=57},zf=function(e){return Gf(e)||e>=65&&e<=70||e>=97&&e<=102},Wf=function(e){return 10===e||9===e||32===e},Kf=function(e){return function(e){return function(e){return e>=97&&e<=122}(e)||function(e){return e>=65&&e<=90}(e)}(e)||function(e){return e>=128}(e)||95===e},Xf=function(e){return Kf(e)||Gf(e)||45===e},Jf=function(e){return e>=0&&e<=8||11===e||e>=14&&e<=31||127===e},Yf=function(e,t){return 92===e&&10!==t},Zf=function(e,t,i){return 45===e?Kf(t)||Yf(t,i):!!Kf(e)||!(92!==e||!Yf(e,t))},qf=function(e,t,i){return 43===e||45===e?!!Gf(t)||46===t&&Gf(i):Gf(46===e?t:e)},$f=function(e){var t=0,i=1;43!==e[t]&&45!==e[t]||(45===e[t]&&(i=-1),t++);for(var r=[];Gf(e[t]);)r.push(e[t++]);var s=r.length?parseInt(Kp.apply(void 0,r),10):0;46===e[t]&&t++;for(var n=[];Gf(e[t]);)n.push(e[t++]);var o=n.length,a=o?parseInt(Kp.apply(void 0,n),10):0;69!==e[t]&&101!==e[t]||t++;var l=1;43!==e[t]&&45!==e[t]||(45===e[t]&&(l=-1),t++);for(var u=[];Gf(e[t]);)u.push(e[t++]);var c=u.length?parseInt(Kp.apply(void 0,u),10):0;return i*(s+a*Math.pow(10,-o))*Math.pow(10,l*c)},ev={type:2},tv={type:3},iv={type:4},rv={type:13},sv={type:8},nv={type:21},ov={type:9},av={type:10},lv={type:11},uv={type:12},cv={type:14},Av={type:23},hv={type:1},dv={type:25},pv={type:24},fv={type:26},vv={type:27},gv={type:28},mv={type:29},_v={type:31},yv={type:32},bv=function(){function e(){this._value=[]}return e.prototype.write=function(e){this._value=this._value.concat(Wp(e))},e.prototype.read=function(){for(var e=[],t=this.consumeToken();t!==yv;)e.push(t),t=this.consumeToken();return e},e.prototype.consumeToken=function(){var e=this.consumeCodePoint();switch(e){case 34:return this.consumeStringToken(34);case 35:var t=this.peekCodePoint(0),i=this.peekCodePoint(1),r=this.peekCodePoint(2);if(Xf(t)||Yf(i,r)){var s=Zf(t,i,r)?2:1;return{type:5,value:this.consumeName(),flags:s}}break;case 36:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),rv;break;case 39:return this.consumeStringToken(39);case 40:return ev;case 41:return tv;case 42:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),cv;break;case 43:if(qf(e,this.peekCodePoint(0),this.peekCodePoint(1)))return this.reconsumeCodePoint(e),this.consumeNumericToken();break;case 44:return iv;case 45:var n=e,o=this.peekCodePoint(0),a=this.peekCodePoint(1);if(qf(n,o,a))return this.reconsumeCodePoint(e),this.consumeNumericToken();if(Zf(n,o,a))return this.reconsumeCodePoint(e),this.consumeIdentLikeToken();if(45===o&&62===a)return this.consumeCodePoint(),this.consumeCodePoint(),pv;break;case 46:if(qf(e,this.peekCodePoint(0),this.peekCodePoint(1)))return this.reconsumeCodePoint(e),this.consumeNumericToken();break;case 47:if(42===this.peekCodePoint(0))for(this.consumeCodePoint();;){var l=this.consumeCodePoint();if(42===l&&47===(l=this.consumeCodePoint()))return this.consumeToken();if(-1===l)return this.consumeToken()}break;case 58:return fv;case 59:return vv;case 60:if(33===this.peekCodePoint(0)&&45===this.peekCodePoint(1)&&45===this.peekCodePoint(2))return this.consumeCodePoint(),this.consumeCodePoint(),dv;break;case 64:var u=this.peekCodePoint(0),c=this.peekCodePoint(1),A=this.peekCodePoint(2);if(Zf(u,c,A))return{type:7,value:this.consumeName()};break;case 91:return gv;case 92:if(Yf(e,this.peekCodePoint(0)))return this.reconsumeCodePoint(e),this.consumeIdentLikeToken();break;case 93:return mv;case 61:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),sv;break;case 123:return lv;case 125:return uv;case 117:case 85:var h=this.peekCodePoint(0),d=this.peekCodePoint(1);return 43!==h||!zf(d)&&63!==d||(this.consumeCodePoint(),this.consumeUnicodeRangeToken()),this.reconsumeCodePoint(e),this.consumeIdentLikeToken();case 124:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),ov;if(124===this.peekCodePoint(0))return this.consumeCodePoint(),nv;break;case 126:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),av;break;case-1:return yv}return Wf(e)?(this.consumeWhiteSpace(),_v):Gf(e)?(this.reconsumeCodePoint(e),this.consumeNumericToken()):Kf(e)?(this.reconsumeCodePoint(e),this.consumeIdentLikeToken()):{type:6,value:Kp(e)}},e.prototype.consumeCodePoint=function(){var e=this._value.shift();return void 0===e?-1:e},e.prototype.reconsumeCodePoint=function(e){this._value.unshift(e)},e.prototype.peekCodePoint=function(e){return e>=this._value.length?-1:this._value[e]},e.prototype.consumeUnicodeRangeToken=function(){for(var e=[],t=this.consumeCodePoint();zf(t)&&e.length<6;)e.push(t),t=this.consumeCodePoint();for(var i=!1;63===t&&e.length<6;)e.push(t),t=this.consumeCodePoint(),i=!0;if(i)return{type:30,start:parseInt(Kp.apply(void 0,e.map((function(e){return 63===e?48:e}))),16),end:parseInt(Kp.apply(void 0,e.map((function(e){return 63===e?70:e}))),16)};var r=parseInt(Kp.apply(void 0,e),16);if(45===this.peekCodePoint(0)&&zf(this.peekCodePoint(1))){this.consumeCodePoint(),t=this.consumeCodePoint();for(var s=[];zf(t)&&s.length<6;)s.push(t),t=this.consumeCodePoint();return{type:30,start:r,end:parseInt(Kp.apply(void 0,s),16)}}return{type:30,start:r,end:r}},e.prototype.consumeIdentLikeToken=function(){var e=this.consumeName();return"url"===e.toLowerCase()&&40===this.peekCodePoint(0)?(this.consumeCodePoint(),this.consumeUrlToken()):40===this.peekCodePoint(0)?(this.consumeCodePoint(),{type:19,value:e}):{type:20,value:e}},e.prototype.consumeUrlToken=function(){var e=[];if(this.consumeWhiteSpace(),-1===this.peekCodePoint(0))return{type:22,value:""};var t=this.peekCodePoint(0);if(39===t||34===t){var i=this.consumeStringToken(this.consumeCodePoint());return 0===i.type&&(this.consumeWhiteSpace(),-1===this.peekCodePoint(0)||41===this.peekCodePoint(0))?(this.consumeCodePoint(),{type:22,value:i.value}):(this.consumeBadUrlRemnants(),Av)}for(;;){var r=this.consumeCodePoint();if(-1===r||41===r)return{type:22,value:Kp.apply(void 0,e)};if(Wf(r))return this.consumeWhiteSpace(),-1===this.peekCodePoint(0)||41===this.peekCodePoint(0)?(this.consumeCodePoint(),{type:22,value:Kp.apply(void 0,e)}):(this.consumeBadUrlRemnants(),Av);if(34===r||39===r||40===r||Jf(r))return this.consumeBadUrlRemnants(),Av;if(92===r){if(!Yf(r,this.peekCodePoint(0)))return this.consumeBadUrlRemnants(),Av;e.push(this.consumeEscapedCodePoint())}else e.push(r)}},e.prototype.consumeWhiteSpace=function(){for(;Wf(this.peekCodePoint(0));)this.consumeCodePoint()},e.prototype.consumeBadUrlRemnants=function(){for(;;){var e=this.consumeCodePoint();if(41===e||-1===e)return;Yf(e,this.peekCodePoint(0))&&this.consumeEscapedCodePoint()}},e.prototype.consumeStringSlice=function(e){for(var t="";e>0;){var i=Math.min(5e4,e);t+=Kp.apply(void 0,this._value.splice(0,i)),e-=i}return this._value.shift(),t},e.prototype.consumeStringToken=function(e){for(var t="",i=0;;){var r=this._value[i];if(-1===r||void 0===r||r===e)return{type:0,value:t+=this.consumeStringSlice(i)};if(10===r)return this._value.splice(0,i),hv;if(92===r){var s=this._value[i+1];-1!==s&&void 0!==s&&(10===s?(t+=this.consumeStringSlice(i),i=-1,this._value.shift()):Yf(r,s)&&(t+=this.consumeStringSlice(i),t+=Kp(this.consumeEscapedCodePoint()),i=-1))}i++}},e.prototype.consumeNumber=function(){var e=[],t=4,i=this.peekCodePoint(0);for(43!==i&&45!==i||e.push(this.consumeCodePoint());Gf(this.peekCodePoint(0));)e.push(this.consumeCodePoint());i=this.peekCodePoint(0);var r=this.peekCodePoint(1);if(46===i&&Gf(r))for(e.push(this.consumeCodePoint(),this.consumeCodePoint()),t=8;Gf(this.peekCodePoint(0));)e.push(this.consumeCodePoint());i=this.peekCodePoint(0),r=this.peekCodePoint(1);var s=this.peekCodePoint(2);if((69===i||101===i)&&((43===r||45===r)&&Gf(s)||Gf(r)))for(e.push(this.consumeCodePoint(),this.consumeCodePoint()),t=8;Gf(this.peekCodePoint(0));)e.push(this.consumeCodePoint());return[$f(e),t]},e.prototype.consumeNumericToken=function(){var e=this.consumeNumber(),t=e[0],i=e[1],r=this.peekCodePoint(0),s=this.peekCodePoint(1),n=this.peekCodePoint(2);return Zf(r,s,n)?{type:15,number:t,flags:i,unit:this.consumeName()}:37===r?(this.consumeCodePoint(),{type:16,number:t,flags:i}):{type:17,number:t,flags:i}},e.prototype.consumeEscapedCodePoint=function(){var e=this.consumeCodePoint();if(zf(e)){for(var t=Kp(e);zf(this.peekCodePoint(0))&&t.length<6;)t+=Kp(this.consumeCodePoint());Wf(this.peekCodePoint(0))&&this.consumeCodePoint();var i=parseInt(t,16);return 0===i||function(e){return e>=55296&&e<=57343}(i)||i>1114111?65533:i}return-1===e?65533:e},e.prototype.consumeName=function(){for(var e="";;){var t=this.consumeCodePoint();if(Xf(t))e+=Kp(t);else{if(!Yf(t,this.peekCodePoint(0)))return this.reconsumeCodePoint(t),e;e+=Kp(this.consumeEscapedCodePoint())}}},e}(),xv=function(){function e(e){this._tokens=e}return e.create=function(t){var i=new bv;return i.write(t),new e(i.read())},e.parseValue=function(t){return e.create(t).parseComponentValue()},e.parseValues=function(t){return e.create(t).parseComponentValues()},e.prototype.parseComponentValue=function(){for(var e=this.consumeToken();31===e.type;)e=this.consumeToken();if(32===e.type)throw new SyntaxError("Error parsing CSS component value, unexpected EOF");this.reconsumeToken(e);var t=this.consumeComponentValue();do{e=this.consumeToken()}while(31===e.type);if(32===e.type)return t;throw new SyntaxError("Error parsing CSS component value, multiple values found when expecting only one")},e.prototype.parseComponentValues=function(){for(var e=[];;){var t=this.consumeComponentValue();if(32===t.type)return e;e.push(t),e.push()}},e.prototype.consumeComponentValue=function(){var e=this.consumeToken();switch(e.type){case 11:case 28:case 2:return this.consumeSimpleBlock(e.type);case 19:return this.consumeFunction(e)}return e},e.prototype.consumeSimpleBlock=function(e){for(var t={type:e,values:[]},i=this.consumeToken();;){if(32===i.type||Iv(i,e))return t;this.reconsumeToken(i),t.values.push(this.consumeComponentValue()),i=this.consumeToken()}},e.prototype.consumeFunction=function(e){for(var t={name:e.value,values:[],type:18};;){var i=this.consumeToken();if(32===i.type||3===i.type)return t;this.reconsumeToken(i),t.values.push(this.consumeComponentValue())}},e.prototype.consumeToken=function(){var e=this._tokens.shift();return void 0===e?yv:e},e.prototype.reconsumeToken=function(e){this._tokens.unshift(e)},e}(),wv=function(e){return 15===e.type},Bv=function(e){return 17===e.type},Pv=function(e){return 20===e.type},Cv=function(e){return 0===e.type},Mv=function(e,t){return Pv(e)&&e.value===t},Ev=function(e){return 31!==e.type},Fv=function(e){return 31!==e.type&&4!==e.type},kv=function(e){var t=[],i=[];return e.forEach((function(e){if(4===e.type){if(0===i.length)throw new Error("Error parsing function args, zero tokens for arg");return t.push(i),void(i=[])}31!==e.type&&i.push(e)})),i.length&&t.push(i),t},Iv=function(e,t){return 11===t&&12===e.type||(28===t&&29===e.type||2===t&&3===e.type)},Dv=function(e){return 17===e.type||15===e.type},Sv=function(e){return 16===e.type||Dv(e)},Tv=function(e){return e.length>1?[e[0],e[1]]:[e[0]]},Lv={type:17,number:0,flags:4},Rv={type:16,number:50,flags:4},Uv={type:16,number:100,flags:4},Ov=function(e,t,i){var r=e[0],s=e[1];return[Nv(r,t),Nv(void 0!==s?s:r,i)]},Nv=function(e,t){if(16===e.type)return e.number/100*t;if(wv(e))switch(e.unit){case"rem":case"em":return 16*e.number;default:return e.number}return e.number},Qv=function(e,t){if(15===t.type)switch(t.unit){case"deg":return Math.PI*t.number/180;case"grad":return Math.PI/200*t.number;case"rad":return t.number;case"turn":return 2*Math.PI*t.number}throw new Error("Unsupported angle type")},Vv=function(e){return 15===e.type&&("deg"===e.unit||"grad"===e.unit||"rad"===e.unit||"turn"===e.unit)},Hv=function(e){switch(e.filter(Pv).map((function(e){return e.value})).join(" ")){case"to bottom right":case"to right bottom":case"left top":case"top left":return[Lv,Lv];case"to top":case"bottom":return jv(0);case"to bottom left":case"to left bottom":case"right top":case"top right":return[Lv,Uv];case"to right":case"left":return jv(90);case"to top left":case"to left top":case"right bottom":case"bottom right":return[Uv,Uv];case"to bottom":case"top":return jv(180);case"to top right":case"to right top":case"left bottom":case"bottom left":return[Uv,Lv];case"to left":case"right":return jv(270)}return 0},jv=function(e){return Math.PI*e/180},Gv=function(e,t){if(18===t.type){var i=qv[t.name];if(void 0===i)throw new Error('Attempting to parse an unsupported color function "'+t.name+'"');return i(e,t.values)}if(5===t.type){if(3===t.value.length){var r=t.value.substring(0,1),s=t.value.substring(1,2),n=t.value.substring(2,3);return Kv(parseInt(r+r,16),parseInt(s+s,16),parseInt(n+n,16),1)}if(4===t.value.length){r=t.value.substring(0,1),s=t.value.substring(1,2),n=t.value.substring(2,3);var o=t.value.substring(3,4);return Kv(parseInt(r+r,16),parseInt(s+s,16),parseInt(n+n,16),parseInt(o+o,16)/255)}if(6===t.value.length){r=t.value.substring(0,2),s=t.value.substring(2,4),n=t.value.substring(4,6);return Kv(parseInt(r,16),parseInt(s,16),parseInt(n,16),1)}if(8===t.value.length){r=t.value.substring(0,2),s=t.value.substring(2,4),n=t.value.substring(4,6),o=t.value.substring(6,8);return Kv(parseInt(r,16),parseInt(s,16),parseInt(n,16),parseInt(o,16)/255)}}if(20===t.type){var a=eg[t.value.toUpperCase()];if(void 0!==a)return a}return eg.TRANSPARENT},zv=function(e){return 0==(255&e)},Wv=function(e){var t=255&e,i=255&e>>8,r=255&e>>16,s=255&e>>24;return t<255?"rgba("+s+","+r+","+i+","+t/255+")":"rgb("+s+","+r+","+i+")"},Kv=function(e,t,i,r){return(e<<24|t<<16|i<<8|Math.round(255*r)<<0)>>>0},Xv=function(e,t){if(17===e.type)return e.number;if(16===e.type){var i=3===t?1:255;return 3===t?e.number/100*i:Math.round(e.number/100*i)}return 0},Jv=function(e,t){var i=t.filter(Fv);if(3===i.length){var r=i.map(Xv),s=r[0],n=r[1],o=r[2];return Kv(s,n,o,1)}if(4===i.length){var a=i.map(Xv),l=(s=a[0],n=a[1],o=a[2],a[3]);return Kv(s,n,o,l)}return 0};function Yv(e,t,i){return i<0&&(i+=1),i>=1&&(i-=1),i<1/6?(t-e)*i*6+e:i<.5?t:i<2/3?6*(t-e)*(2/3-i)+e:e}var Zv=function(e,t){var i=t.filter(Fv),r=i[0],s=i[1],n=i[2],o=i[3],a=(17===r.type?jv(r.number):Qv(e,r))/(2*Math.PI),l=Sv(s)?s.number/100:0,u=Sv(n)?n.number/100:0,c=void 0!==o&&Sv(o)?Nv(o,1):1;if(0===l)return Kv(255*u,255*u,255*u,1);var A=u<=.5?u*(l+1):u+l-u*l,h=2*u-A,d=Yv(h,A,a+1/3),p=Yv(h,A,a),f=Yv(h,A,a-1/3);return Kv(255*d,255*p,255*f,c)},qv={hsl:Zv,hsla:Zv,rgb:Jv,rgba:Jv},$v=function(e,t){return Gv(e,xv.create(t).parseComponentValue())},eg={ALICEBLUE:4042850303,ANTIQUEWHITE:4209760255,AQUA:16777215,AQUAMARINE:2147472639,AZURE:4043309055,BEIGE:4126530815,BISQUE:4293182719,BLACK:255,BLANCHEDALMOND:4293643775,BLUE:65535,BLUEVIOLET:2318131967,BROWN:2771004159,BURLYWOOD:3736635391,CADETBLUE:1604231423,CHARTREUSE:2147418367,CHOCOLATE:3530104575,CORAL:4286533887,CORNFLOWERBLUE:1687547391,CORNSILK:4294499583,CRIMSON:3692313855,CYAN:16777215,DARKBLUE:35839,DARKCYAN:9145343,DARKGOLDENROD:3095837695,DARKGRAY:2846468607,DARKGREEN:6553855,DARKGREY:2846468607,DARKKHAKI:3182914559,DARKMAGENTA:2332068863,DARKOLIVEGREEN:1433087999,DARKORANGE:4287365375,DARKORCHID:2570243327,DARKRED:2332033279,DARKSALMON:3918953215,DARKSEAGREEN:2411499519,DARKSLATEBLUE:1211993087,DARKSLATEGRAY:793726975,DARKSLATEGREY:793726975,DARKTURQUOISE:13554175,DARKVIOLET:2483082239,DEEPPINK:4279538687,DEEPSKYBLUE:12582911,DIMGRAY:1768516095,DIMGREY:1768516095,DODGERBLUE:512819199,FIREBRICK:2988581631,FLORALWHITE:4294635775,FORESTGREEN:579543807,FUCHSIA:4278255615,GAINSBORO:3705462015,GHOSTWHITE:4177068031,GOLD:4292280575,GOLDENROD:3668254975,GRAY:2155905279,GREEN:8388863,GREENYELLOW:2919182335,GREY:2155905279,HONEYDEW:4043305215,HOTPINK:4285117695,INDIANRED:3445382399,INDIGO:1258324735,IVORY:4294963455,KHAKI:4041641215,LAVENDER:3873897215,LAVENDERBLUSH:4293981695,LAWNGREEN:2096890111,LEMONCHIFFON:4294626815,LIGHTBLUE:2916673279,LIGHTCORAL:4034953471,LIGHTCYAN:3774873599,LIGHTGOLDENRODYELLOW:4210742015,LIGHTGRAY:3553874943,LIGHTGREEN:2431553791,LIGHTGREY:3553874943,LIGHTPINK:4290167295,LIGHTSALMON:4288707327,LIGHTSEAGREEN:548580095,LIGHTSKYBLUE:2278488831,LIGHTSLATEGRAY:2005441023,LIGHTSLATEGREY:2005441023,LIGHTSTEELBLUE:2965692159,LIGHTYELLOW:4294959359,LIME:16711935,LIMEGREEN:852308735,LINEN:4210091775,MAGENTA:4278255615,MAROON:2147483903,MEDIUMAQUAMARINE:1724754687,MEDIUMBLUE:52735,MEDIUMORCHID:3126187007,MEDIUMPURPLE:2473647103,MEDIUMSEAGREEN:1018393087,MEDIUMSLATEBLUE:2070474495,MEDIUMSPRINGGREEN:16423679,MEDIUMTURQUOISE:1221709055,MEDIUMVIOLETRED:3340076543,MIDNIGHTBLUE:421097727,MINTCREAM:4127193855,MISTYROSE:4293190143,MOCCASIN:4293178879,NAVAJOWHITE:4292783615,NAVY:33023,OLDLACE:4260751103,OLIVE:2155872511,OLIVEDRAB:1804477439,ORANGE:4289003775,ORANGERED:4282712319,ORCHID:3664828159,PALEGOLDENROD:4008225535,PALEGREEN:2566625535,PALETURQUOISE:2951671551,PALEVIOLETRED:3681588223,PAPAYAWHIP:4293907967,PEACHPUFF:4292524543,PERU:3448061951,PINK:4290825215,PLUM:3718307327,POWDERBLUE:2967529215,PURPLE:2147516671,REBECCAPURPLE:1714657791,RED:4278190335,ROSYBROWN:3163525119,ROYALBLUE:1097458175,SADDLEBROWN:2336560127,SALMON:4202722047,SANDYBROWN:4104413439,SEAGREEN:780883967,SEASHELL:4294307583,SIENNA:2689740287,SILVER:3233857791,SKYBLUE:2278484991,SLATEBLUE:1784335871,SLATEGRAY:1887473919,SLATEGREY:1887473919,SNOW:4294638335,SPRINGGREEN:16744447,STEELBLUE:1182971135,TAN:3535047935,TEAL:8421631,THISTLE:3636451583,TOMATO:4284696575,TRANSPARENT:0,TURQUOISE:1088475391,VIOLET:4001558271,WHEAT:4125012991,WHITE:4294967295,WHITESMOKE:4126537215,YELLOW:4294902015,YELLOWGREEN:2597139199},tg={name:"background-clip",initialValue:"border-box",prefix:!1,type:1,parse:function(e,t){return t.map((function(e){if(Pv(e))switch(e.value){case"padding-box":return 1;case"content-box":return 2}return 0}))}},ig={name:"background-color",initialValue:"transparent",prefix:!1,type:3,format:"color"},rg=function(e,t){var i=Gv(e,t[0]),r=t[1];return r&&Sv(r)?{color:i,stop:r}:{color:i,stop:null}},sg=function(e,t){var i=e[0],r=e[e.length-1];null===i.stop&&(i.stop=Lv),null===r.stop&&(r.stop=Uv);for(var s=[],n=0,o=0;on?s.push(l):s.push(n),n=l}else s.push(null)}var u=null;for(o=0;oe.optimumDistance)?{optimumCorner:t,optimumDistance:a}:e}),{optimumDistance:s?1/0:-1/0,optimumCorner:null}).optimumCorner},lg=function(e,t){var i=jv(180),r=[];return kv(t).forEach((function(t,s){if(0===s){var n=t[0];if(20===n.type&&-1!==["top","left","right","bottom"].indexOf(n.value))return void(i=Hv(t));if(Vv(n))return void(i=(Qv(e,n)+jv(270))%jv(360))}var o=rg(e,t);r.push(o)})),{angle:i,stops:r,type:1}},ug=function(e,t){var i=0,r=3,s=[],n=[];return kv(t).forEach((function(t,o){var a=!0;if(0===o?a=t.reduce((function(e,t){if(Pv(t))switch(t.value){case"center":return n.push(Rv),!1;case"top":case"left":return n.push(Lv),!1;case"right":case"bottom":return n.push(Uv),!1}else if(Sv(t)||Dv(t))return n.push(t),!1;return e}),a):1===o&&(a=t.reduce((function(e,t){if(Pv(t))switch(t.value){case"circle":return i=0,!1;case"ellipse":return i=1,!1;case"contain":case"closest-side":return r=0,!1;case"farthest-side":return r=1,!1;case"closest-corner":return r=2,!1;case"cover":case"farthest-corner":return r=3,!1}else if(Dv(t)||Sv(t))return Array.isArray(r)||(r=[]),r.push(t),!1;return e}),a)),a){var l=rg(e,t);s.push(l)}})),{size:r,shape:i,stops:s,position:n,type:2}},cg=function(e,t){if(22===t.type){var i={url:t.value,type:0};return e.cache.addImage(t.value),i}if(18===t.type){var r=hg[t.name];if(void 0===r)throw new Error('Attempting to parse an unsupported image function "'+t.name+'"');return r(e,t.values)}throw new Error("Unsupported image type "+t.type)};var Ag,hg={"linear-gradient":function(e,t){var i=jv(180),r=[];return kv(t).forEach((function(t,s){if(0===s){var n=t[0];if(20===n.type&&"to"===n.value)return void(i=Hv(t));if(Vv(n))return void(i=Qv(e,n))}var o=rg(e,t);r.push(o)})),{angle:i,stops:r,type:1}},"-moz-linear-gradient":lg,"-ms-linear-gradient":lg,"-o-linear-gradient":lg,"-webkit-linear-gradient":lg,"radial-gradient":function(e,t){var i=0,r=3,s=[],n=[];return kv(t).forEach((function(t,o){var a=!0;if(0===o){var l=!1;a=t.reduce((function(e,t){if(l)if(Pv(t))switch(t.value){case"center":return n.push(Rv),e;case"top":case"left":return n.push(Lv),e;case"right":case"bottom":return n.push(Uv),e}else(Sv(t)||Dv(t))&&n.push(t);else if(Pv(t))switch(t.value){case"circle":return i=0,!1;case"ellipse":return i=1,!1;case"at":return l=!0,!1;case"closest-side":return r=0,!1;case"cover":case"farthest-side":return r=1,!1;case"contain":case"closest-corner":return r=2,!1;case"farthest-corner":return r=3,!1}else if(Dv(t)||Sv(t))return Array.isArray(r)||(r=[]),r.push(t),!1;return e}),a)}if(a){var u=rg(e,t);s.push(u)}})),{size:r,shape:i,stops:s,position:n,type:2}},"-moz-radial-gradient":ug,"-ms-radial-gradient":ug,"-o-radial-gradient":ug,"-webkit-radial-gradient":ug,"-webkit-gradient":function(e,t){var i=jv(180),r=[],s=1;return kv(t).forEach((function(t,i){var n=t[0];if(0===i){if(Pv(n)&&"linear"===n.value)return void(s=1);if(Pv(n)&&"radial"===n.value)return void(s=2)}if(18===n.type)if("from"===n.name){var o=Gv(e,n.values[0]);r.push({stop:Lv,color:o})}else if("to"===n.name){o=Gv(e,n.values[0]);r.push({stop:Uv,color:o})}else if("color-stop"===n.name){var a=n.values.filter(Fv);if(2===a.length){o=Gv(e,a[1]);var l=a[0];Bv(l)&&r.push({stop:{type:16,number:100*l.number,flags:l.flags},color:o})}}})),1===s?{angle:(i+jv(180))%jv(360),stops:r,type:s}:{size:3,shape:0,stops:r,position:[],type:s}}},dg={name:"background-image",initialValue:"none",type:1,prefix:!1,parse:function(e,t){if(0===t.length)return[];var i=t[0];return 20===i.type&&"none"===i.value?[]:t.filter((function(e){return Fv(e)&&function(e){return!(20===e.type&&"none"===e.value||18===e.type&&!hg[e.name])}(e)})).map((function(t){return cg(e,t)}))}},pg={name:"background-origin",initialValue:"border-box",prefix:!1,type:1,parse:function(e,t){return t.map((function(e){if(Pv(e))switch(e.value){case"padding-box":return 1;case"content-box":return 2}return 0}))}},fg={name:"background-position",initialValue:"0% 0%",type:1,prefix:!1,parse:function(e,t){return kv(t).map((function(e){return e.filter(Sv)})).map(Tv)}},vg={name:"background-repeat",initialValue:"repeat",prefix:!1,type:1,parse:function(e,t){return kv(t).map((function(e){return e.filter(Pv).map((function(e){return e.value})).join(" ")})).map(gg)}},gg=function(e){switch(e){case"no-repeat":return 1;case"repeat-x":case"repeat no-repeat":return 2;case"repeat-y":case"no-repeat repeat":return 3;default:return 0}};!function(e){e.AUTO="auto",e.CONTAIN="contain",e.COVER="cover"}(Ag||(Ag={}));var mg,_g={name:"background-size",initialValue:"0",prefix:!1,type:1,parse:function(e,t){return kv(t).map((function(e){return e.filter(yg)}))}},yg=function(e){return Pv(e)||Sv(e)},bg=function(e){return{name:"border-"+e+"-color",initialValue:"transparent",prefix:!1,type:3,format:"color"}},xg=bg("top"),wg=bg("right"),Bg=bg("bottom"),Pg=bg("left"),Cg=function(e){return{name:"border-radius-"+e,initialValue:"0 0",prefix:!1,type:1,parse:function(e,t){return Tv(t.filter(Sv))}}},Mg=Cg("top-left"),Eg=Cg("top-right"),Fg=Cg("bottom-right"),kg=Cg("bottom-left"),Ig=function(e){return{name:"border-"+e+"-style",initialValue:"solid",prefix:!1,type:2,parse:function(e,t){switch(t){case"none":return 0;case"dashed":return 2;case"dotted":return 3;case"double":return 4}return 1}}},Dg=Ig("top"),Sg=Ig("right"),Tg=Ig("bottom"),Lg=Ig("left"),Rg=function(e){return{name:"border-"+e+"-width",initialValue:"0",type:0,prefix:!1,parse:function(e,t){return wv(t)?t.number:0}}},Ug=Rg("top"),Og=Rg("right"),Ng=Rg("bottom"),Qg=Rg("left"),Vg={name:"color",initialValue:"transparent",prefix:!1,type:3,format:"color"},Hg={name:"direction",initialValue:"ltr",prefix:!1,type:2,parse:function(e,t){return"rtl"===t?1:0}},jg={name:"display",initialValue:"inline-block",prefix:!1,type:1,parse:function(e,t){return t.filter(Pv).reduce((function(e,t){return e|Gg(t.value)}),0)}},Gg=function(e){switch(e){case"block":case"-webkit-box":return 2;case"inline":return 4;case"run-in":return 8;case"flow":return 16;case"flow-root":return 32;case"table":return 64;case"flex":case"-webkit-flex":return 128;case"grid":case"-ms-grid":return 256;case"ruby":return 512;case"subgrid":return 1024;case"list-item":return 2048;case"table-row-group":return 4096;case"table-header-group":return 8192;case"table-footer-group":return 16384;case"table-row":return 32768;case"table-cell":return 65536;case"table-column-group":return 131072;case"table-column":return 262144;case"table-caption":return 524288;case"ruby-base":return 1048576;case"ruby-text":return 2097152;case"ruby-base-container":return 4194304;case"ruby-text-container":return 8388608;case"contents":return 16777216;case"inline-block":return 33554432;case"inline-list-item":return 67108864;case"inline-table":return 134217728;case"inline-flex":return 268435456;case"inline-grid":return 536870912}return 0},zg={name:"float",initialValue:"none",prefix:!1,type:2,parse:function(e,t){switch(t){case"left":return 1;case"right":return 2;case"inline-start":return 3;case"inline-end":return 4}return 0}},Wg={name:"letter-spacing",initialValue:"0",prefix:!1,type:0,parse:function(e,t){return 20===t.type&&"normal"===t.value?0:17===t.type||15===t.type?t.number:0}};!function(e){e.NORMAL="normal",e.STRICT="strict"}(mg||(mg={}));var Kg,Xg={name:"line-break",initialValue:"normal",prefix:!1,type:2,parse:function(e,t){return"strict"===t?mg.STRICT:mg.NORMAL}},Jg={name:"line-height",initialValue:"normal",prefix:!1,type:4},Yg=function(e,t){return Pv(e)&&"normal"===e.value?1.2*t:17===e.type?t*e.number:Sv(e)?Nv(e,t):t},Zg={name:"list-style-image",initialValue:"none",type:0,prefix:!1,parse:function(e,t){return 20===t.type&&"none"===t.value?null:cg(e,t)}},qg={name:"list-style-position",initialValue:"outside",prefix:!1,type:2,parse:function(e,t){return"inside"===t?0:1}},$g={name:"list-style-type",initialValue:"none",prefix:!1,type:2,parse:function(e,t){switch(t){case"disc":return 0;case"circle":return 1;case"square":return 2;case"decimal":return 3;case"cjk-decimal":return 4;case"decimal-leading-zero":return 5;case"lower-roman":return 6;case"upper-roman":return 7;case"lower-greek":return 8;case"lower-alpha":return 9;case"upper-alpha":return 10;case"arabic-indic":return 11;case"armenian":return 12;case"bengali":return 13;case"cambodian":return 14;case"cjk-earthly-branch":return 15;case"cjk-heavenly-stem":return 16;case"cjk-ideographic":return 17;case"devanagari":return 18;case"ethiopic-numeric":return 19;case"georgian":return 20;case"gujarati":return 21;case"gurmukhi":case"hebrew":return 22;case"hiragana":return 23;case"hiragana-iroha":return 24;case"japanese-formal":return 25;case"japanese-informal":return 26;case"kannada":return 27;case"katakana":return 28;case"katakana-iroha":return 29;case"khmer":return 30;case"korean-hangul-formal":return 31;case"korean-hanja-formal":return 32;case"korean-hanja-informal":return 33;case"lao":return 34;case"lower-armenian":return 35;case"malayalam":return 36;case"mongolian":return 37;case"myanmar":return 38;case"oriya":return 39;case"persian":return 40;case"simp-chinese-formal":return 41;case"simp-chinese-informal":return 42;case"tamil":return 43;case"telugu":return 44;case"thai":return 45;case"tibetan":return 46;case"trad-chinese-formal":return 47;case"trad-chinese-informal":return 48;case"upper-armenian":return 49;case"disclosure-open":return 50;case"disclosure-closed":return 51;default:return-1}}},em=function(e){return{name:"margin-"+e,initialValue:"0",prefix:!1,type:4}},tm=em("top"),im=em("right"),rm=em("bottom"),sm=em("left"),nm={name:"overflow",initialValue:"visible",prefix:!1,type:1,parse:function(e,t){return t.filter(Pv).map((function(e){switch(e.value){case"hidden":return 1;case"scroll":return 2;case"clip":return 3;case"auto":return 4;default:return 0}}))}},om={name:"overflow-wrap",initialValue:"normal",prefix:!1,type:2,parse:function(e,t){return"break-word"===t?"break-word":"normal"}},am=function(e){return{name:"padding-"+e,initialValue:"0",prefix:!1,type:3,format:"length-percentage"}},lm=am("top"),um=am("right"),cm=am("bottom"),Am=am("left"),hm={name:"text-align",initialValue:"left",prefix:!1,type:2,parse:function(e,t){switch(t){case"right":return 2;case"center":case"justify":return 1;default:return 0}}},dm={name:"position",initialValue:"static",prefix:!1,type:2,parse:function(e,t){switch(t){case"relative":return 1;case"absolute":return 2;case"fixed":return 3;case"sticky":return 4}return 0}},pm={name:"text-shadow",initialValue:"none",type:1,prefix:!1,parse:function(e,t){return 1===t.length&&Mv(t[0],"none")?[]:kv(t).map((function(t){for(var i={color:eg.TRANSPARENT,offsetX:Lv,offsetY:Lv,blur:Lv},r=0,s=0;s1?1:0],this.overflowWrap=Km(e,om,t.overflowWrap),this.paddingTop=Km(e,lm,t.paddingTop),this.paddingRight=Km(e,um,t.paddingRight),this.paddingBottom=Km(e,cm,t.paddingBottom),this.paddingLeft=Km(e,Am,t.paddingLeft),this.paintOrder=Km(e,Vm,t.paintOrder),this.position=Km(e,dm,t.position),this.textAlign=Km(e,hm,t.textAlign),this.textDecorationColor=Km(e,Cm,null!==(i=t.textDecorationColor)&&void 0!==i?i:t.color),this.textDecorationLine=Km(e,Mm,null!==(r=t.textDecorationLine)&&void 0!==r?r:t.textDecoration),this.textShadow=Km(e,pm,t.textShadow),this.textTransform=Km(e,fm,t.textTransform),this.transform=Km(e,vm,t.transform),this.transformOrigin=Km(e,ym,t.transformOrigin),this.visibility=Km(e,bm,t.visibility),this.webkitTextStrokeColor=Km(e,Hm,t.webkitTextStrokeColor),this.webkitTextStrokeWidth=Km(e,jm,t.webkitTextStrokeWidth),this.wordBreak=Km(e,xm,t.wordBreak),this.zIndex=Km(e,wm,t.zIndex)}return e.prototype.isVisible=function(){return this.display>0&&this.opacity>0&&0===this.visibility},e.prototype.isTransparent=function(){return zv(this.backgroundColor)},e.prototype.isTransformed=function(){return null!==this.transform},e.prototype.isPositioned=function(){return 0!==this.position},e.prototype.isPositionedWithZIndex=function(){return this.isPositioned()&&!this.zIndex.auto},e.prototype.isFloating=function(){return 0!==this.float},e.prototype.isInlineLevel=function(){return Sm(this.display,4)||Sm(this.display,33554432)||Sm(this.display,268435456)||Sm(this.display,536870912)||Sm(this.display,67108864)||Sm(this.display,134217728)},e}(),zm=function(e,t){this.content=Km(e,Tm,t.content),this.quotes=Km(e,Om,t.quotes)},Wm=function(e,t){this.counterIncrement=Km(e,Lm,t.counterIncrement),this.counterReset=Km(e,Rm,t.counterReset)},Km=function(e,t,i){var r=new bv,s=null!=i?i.toString():t.initialValue;r.write(s);var n=new xv(r.read());switch(t.type){case 2:var o=n.parseComponentValue();return t.parse(e,Pv(o)?o.value:t.initialValue);case 0:return t.parse(e,n.parseComponentValue());case 1:return t.parse(e,n.parseComponentValues());case 4:return n.parseComponentValue();case 3:switch(t.format){case"angle":return Qv(e,n.parseComponentValue());case"color":return Gv(e,n.parseComponentValue());case"image":return cg(e,n.parseComponentValue());case"length":var a=n.parseComponentValue();return Dv(a)?a:Lv;case"length-percentage":var l=n.parseComponentValue();return Sv(l)?l:Lv;case"time":return Bm(e,n.parseComponentValue())}}},Xm=function(e,t){var i=function(e){switch(e.getAttribute("data-html2canvas-debug")){case"all":return 1;case"clone":return 2;case"parse":return 3;case"render":return 4;default:return 0}}(e);return 1===i||t===i},Jm=function(e,t){this.context=e,this.textNodes=[],this.elements=[],this.flags=0,Xm(t,3),this.styles=new Gm(e,window.getComputedStyle(t,null)),J_(t)&&(this.styles.animationDuration.some((function(e){return e>0}))&&(t.style.animationDuration="0s"),null!==this.styles.transform&&(t.style.transform="none")),this.bounds=zp(this.context,t),Xm(t,4)&&(this.flags|=16)},Ym="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Zm="undefined"==typeof Uint8Array?[]:new Uint8Array(256),qm=0;qm=0){if(e<55296||e>56319&&e<=65535)return t=((t=this.index[e>>5])<<2)+(31&e),this.data[t];if(e<=65535)return t=((t=this.index[2048+(e-55296>>5)])<<2)+(31&e),this.data[t];if(e>11),t=this.index[t],t+=e>>5&63,t=((t=this.index[t])<<2)+(31&e),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},e}(),t_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i_="undefined"==typeof Uint8Array?[]:new Uint8Array(256),r_=0;r_>10),o%1024+56320)),(s+1===i||r.length>16384)&&(n+=String.fromCharCode.apply(String,r),r.length=0)}return n},c_=function(e,t){var i,r,s,n=function(e){var t,i,r,s,n,o=.75*e.length,a=e.length,l=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);var u="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&void 0!==Uint8Array.prototype.slice?new ArrayBuffer(o):new Array(o),c=Array.isArray(u)?u:new Uint8Array(u);for(t=0;t>4,c[l++]=(15&r)<<4|s>>2,c[l++]=(3&s)<<6|63&n;return u}(e),o=Array.isArray(n)?function(e){for(var t=e.length,i=[],r=0;r=55296&&s<=56319&&i=i)return{done:!0,value:null};for(var e="×";ro.x||s.y>o.y;return o=s,0===t||a}));return e.body.removeChild(t),a}(document);return Object.defineProperty(g_,"SUPPORT_WORD_BREAKING",{value:e}),e},get SUPPORT_SVG_DRAWING(){var e=function(e){var t=new Image,i=e.createElement("canvas"),r=i.getContext("2d");if(!r)return!1;t.src="data:image/svg+xml,";try{r.drawImage(t,0,0),i.toDataURL()}catch(e){return!1}return!0}(document);return Object.defineProperty(g_,"SUPPORT_SVG_DRAWING",{value:e}),e},get SUPPORT_FOREIGNOBJECT_DRAWING(){var e="function"==typeof Array.from&&"function"==typeof window.fetch?function(e){var t=e.createElement("canvas"),i=100;t.width=i,t.height=i;var r=t.getContext("2d");if(!r)return Promise.reject(!1);r.fillStyle="rgb(0, 255, 0)",r.fillRect(0,0,i,i);var s=new Image,n=t.toDataURL();s.src=n;var o=f_(i,i,0,0,s);return r.fillStyle="red",r.fillRect(0,0,i,i),v_(o).then((function(t){r.drawImage(t,0,0);var s=r.getImageData(0,0,i,i).data;r.fillStyle="red",r.fillRect(0,0,i,i);var o=e.createElement("div");return o.style.backgroundImage="url("+n+")",o.style.height="100px",p_(s)?v_(f_(i,i,0,0,o)):Promise.reject(!1)})).then((function(e){return r.drawImage(e,0,0),p_(r.getImageData(0,0,i,i).data)})).catch((function(){return!1}))}(document):Promise.resolve(!1);return Object.defineProperty(g_,"SUPPORT_FOREIGNOBJECT_DRAWING",{value:e}),e},get SUPPORT_CORS_IMAGES(){var e=void 0!==(new Image).crossOrigin;return Object.defineProperty(g_,"SUPPORT_CORS_IMAGES",{value:e}),e},get SUPPORT_RESPONSE_TYPE(){var e="string"==typeof(new XMLHttpRequest).responseType;return Object.defineProperty(g_,"SUPPORT_RESPONSE_TYPE",{value:e}),e},get SUPPORT_CORS_XHR(){var e="withCredentials"in new XMLHttpRequest;return Object.defineProperty(g_,"SUPPORT_CORS_XHR",{value:e}),e},get SUPPORT_NATIVE_TEXT_SEGMENTATION(){var e=!("undefined"==typeof Intl||!Intl.Segmenter);return Object.defineProperty(g_,"SUPPORT_NATIVE_TEXT_SEGMENTATION",{value:e}),e}},m_=function(e,t){this.text=e,this.bounds=t},__=function(e,t){var i=t.ownerDocument;if(i){var r=i.createElement("html2canvaswrapper");r.appendChild(t.cloneNode(!0));var s=t.parentNode;if(s){s.replaceChild(r,t);var n=zp(e,r);return r.firstChild&&s.replaceChild(r.firstChild,r),n}}return Gp.EMPTY},y_=function(e,t,i){var r=e.ownerDocument;if(!r)throw new Error("Node has no owner document");var s=r.createRange();return s.setStart(e,t),s.setEnd(e,t+i),s},b_=function(e){if(g_.SUPPORT_NATIVE_TEXT_SEGMENTATION){var t=new Intl.Segmenter(void 0,{granularity:"grapheme"});return Array.from(t.segment(e)).map((function(e){return e.segment}))}return function(e){for(var t,i=d_(e),r=[];!(t=i.next()).done;)t.value&&r.push(t.value.slice());return r}(e)},x_=function(e,t){return 0!==t.letterSpacing?b_(e):function(e,t){if(g_.SUPPORT_NATIVE_TEXT_SEGMENTATION){var i=new Intl.Segmenter(void 0,{granularity:"word"});return Array.from(i.segment(e)).map((function(e){return e.segment}))}return B_(e,t)}(e,t)},w_=[32,160,4961,65792,65793,4153,4241],B_=function(e,t){for(var i,r=function(e,t){var i=Wp(e),r=Hf(i,t),s=r[0],n=r[1],o=r[2],a=i.length,l=0,u=0;return{next:function(){if(u>=a)return{done:!0,value:null};for(var e="×";u0)if(g_.SUPPORT_RANGE_BOUNDS){var s=y_(r,o,t.length).getClientRects();if(s.length>1){var a=b_(t),l=0;a.forEach((function(t){n.push(new m_(t,Gp.fromDOMRectList(e,y_(r,l+o,t.length).getClientRects()))),l+=t.length}))}else n.push(new m_(t,Gp.fromDOMRectList(e,s)))}else{var u=r.splitText(t.length);n.push(new m_(t,__(e,r))),r=u}else g_.SUPPORT_RANGE_BOUNDS||(r=r.splitText(t.length));o+=t.length})),n}(e,this.text,i,t)},C_=function(e,t){switch(t){case 1:return e.toLowerCase();case 3:return e.replace(M_,E_);case 2:return e.toUpperCase();default:return e}},M_=/(^|\s|:|-|\(|\))([a-z])/g,E_=function(e,t,i){return e.length>0?t+i.toUpperCase():e},F_=function(e){function t(t,i){var r=e.call(this,t,i)||this;return r.src=i.currentSrc||i.src,r.intrinsicWidth=i.naturalWidth,r.intrinsicHeight=i.naturalHeight,r.context.cache.addImage(r.src),r}return Np(t,e),t}(Jm),k_=function(e){function t(t,i){var r=e.call(this,t,i)||this;return r.canvas=i,r.intrinsicWidth=i.width,r.intrinsicHeight=i.height,r}return Np(t,e),t}(Jm),I_=function(e){function t(t,i){var r=e.call(this,t,i)||this,s=new XMLSerializer,n=zp(t,i);return i.setAttribute("width",n.width+"px"),i.setAttribute("height",n.height+"px"),r.svg="data:image/svg+xml,"+encodeURIComponent(s.serializeToString(i)),r.intrinsicWidth=i.width.baseVal.value,r.intrinsicHeight=i.height.baseVal.value,r.context.cache.addImage(r.svg),r}return Np(t,e),t}(Jm),D_=function(e){function t(t,i){var r=e.call(this,t,i)||this;return r.value=i.value,r}return Np(t,e),t}(Jm),S_=function(e){function t(t,i){var r=e.call(this,t,i)||this;return r.start=i.start,r.reversed="boolean"==typeof i.reversed&&!0===i.reversed,r}return Np(t,e),t}(Jm),T_=[{type:15,flags:0,unit:"px",number:3}],L_=[{type:16,flags:0,number:50}],R_="password",U_=function(e){function t(t,i){var r,s=e.call(this,t,i)||this;switch(s.type=i.type.toLowerCase(),s.checked=i.checked,s.value=function(e){var t=e.type===R_?new Array(e.value.length+1).join("•"):e.value;return 0===t.length?e.placeholder||"":t}(i),"checkbox"!==s.type&&"radio"!==s.type||(s.styles.backgroundColor=3739148031,s.styles.borderTopColor=s.styles.borderRightColor=s.styles.borderBottomColor=s.styles.borderLeftColor=2779096575,s.styles.borderTopWidth=s.styles.borderRightWidth=s.styles.borderBottomWidth=s.styles.borderLeftWidth=1,s.styles.borderTopStyle=s.styles.borderRightStyle=s.styles.borderBottomStyle=s.styles.borderLeftStyle=1,s.styles.backgroundClip=[0],s.styles.backgroundOrigin=[0],s.bounds=(r=s.bounds).width>r.height?new Gp(r.left+(r.width-r.height)/2,r.top,r.height,r.height):r.width0)r.textNodes.push(new P_(t,n,r.styles));else if(X_(n))if(uy(n)&&n.assignedNodes)n.assignedNodes().forEach((function(i){return e(t,i,r,s)}));else{var a=j_(t,n);a.styles.isVisible()&&(z_(n,a,s)?a.flags|=4:W_(a.styles)&&(a.flags|=2),-1!==V_.indexOf(n.tagName)&&(a.flags|=8),r.elements.push(a),n.slot,n.shadowRoot?e(t,n.shadowRoot,a,s):ay(n)||ey(n)||ly(n)||e(t,n,a,s))}},j_=function(e,t){return sy(t)?new F_(e,t):iy(t)?new k_(e,t):ey(t)?new I_(e,t):Z_(t)?new D_(e,t):q_(t)?new S_(e,t):$_(t)?new U_(e,t):ly(t)?new O_(e,t):ay(t)?new N_(e,t):ny(t)?new Q_(e,t):new Jm(e,t)},G_=function(e,t){var i=j_(e,t);return i.flags|=4,H_(e,t,i,i),i},z_=function(e,t,i){return t.styles.isPositionedWithZIndex()||t.styles.opacity<1||t.styles.isTransformed()||ty(e)&&i.styles.isTransparent()},W_=function(e){return e.isPositioned()||e.isFloating()},K_=function(e){return e.nodeType===Node.TEXT_NODE},X_=function(e){return e.nodeType===Node.ELEMENT_NODE},J_=function(e){return X_(e)&&void 0!==e.style&&!Y_(e)},Y_=function(e){return"object"===w(e.className)},Z_=function(e){return"LI"===e.tagName},q_=function(e){return"OL"===e.tagName},$_=function(e){return"INPUT"===e.tagName},ey=function(e){return"svg"===e.tagName},ty=function(e){return"BODY"===e.tagName},iy=function(e){return"CANVAS"===e.tagName},ry=function(e){return"VIDEO"===e.tagName},sy=function(e){return"IMG"===e.tagName},ny=function(e){return"IFRAME"===e.tagName},oy=function(e){return"STYLE"===e.tagName},ay=function(e){return"TEXTAREA"===e.tagName},ly=function(e){return"SELECT"===e.tagName},uy=function(e){return"SLOT"===e.tagName},cy=function(e){return e.tagName.indexOf("-")>0},Ay=function(){function e(){this.counters={}}return e.prototype.getCounterValue=function(e){var t=this.counters[e];return t&&t.length?t[t.length-1]:1},e.prototype.getCounterValues=function(e){var t=this.counters[e];return t||[]},e.prototype.pop=function(e){var t=this;e.forEach((function(e){return t.counters[e].pop()}))},e.prototype.parse=function(e){var t=this,i=e.counterIncrement,r=e.counterReset,s=!0;null!==i&&i.forEach((function(e){var i=t.counters[e.counter];i&&0!==e.increment&&(s=!1,i.length||i.push(1),i[Math.max(0,i.length-1)]+=e.increment)}));var n=[];return s&&r.forEach((function(e){var i=t.counters[e.counter];n.push(e.counter),i||(i=t.counters[e.counter]=[]),i.push(e.reset)})),n},e}(),hy={integers:[1e3,900,500,400,100,90,50,40,10,9,5,4,1],values:["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]},dy={integers:[9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],values:["Ք","Փ","Ւ","Ց","Ր","Տ","Վ","Ս","Ռ","Ջ","Պ","Չ","Ո","Շ","Ն","Յ","Մ","Ճ","Ղ","Ձ","Հ","Կ","Ծ","Խ","Լ","Ի","Ժ","Թ","Ը","Է","Զ","Ե","Դ","Գ","Բ","Ա"]},py={integers:[1e4,9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,400,300,200,100,90,80,70,60,50,40,30,20,19,18,17,16,15,10,9,8,7,6,5,4,3,2,1],values:["י׳","ט׳","ח׳","ז׳","ו׳","ה׳","ד׳","ג׳","ב׳","א׳","ת","ש","ר","ק","צ","פ","ע","ס","נ","מ","ל","כ","יט","יח","יז","טז","טו","י","ט","ח","ז","ו","ה","ד","ג","ב","א"]},fy={integers:[1e4,9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],values:["ჵ","ჰ","ჯ","ჴ","ხ","ჭ","წ","ძ","ც","ჩ","შ","ყ","ღ","ქ","ფ","ჳ","ტ","ს","რ","ჟ","პ","ო","ჲ","ნ","მ","ლ","კ","ი","თ","ჱ","ზ","ვ","ე","დ","გ","ბ","ა"]},vy=function(e,t,i,r,s,n){return ei?by(e,s,n.length>0):r.integers.reduce((function(t,i,s){for(;e>=i;)e-=i,t+=r.values[s];return t}),"")+n},gy=function(e,t,i,r){var s="";do{i||e--,s=r(e)+s,e/=t}while(e*t>=t);return s},my=function(e,t,i,r,s){var n=i-t+1;return(e<0?"-":"")+(gy(Math.abs(e),n,r,(function(e){return Kp(Math.floor(e%n)+t)}))+s)},_y=function(e,t,i){void 0===i&&(i=". ");var r=t.length;return gy(Math.abs(e),r,!1,(function(e){return t[Math.floor(e%r)]}))+i},yy=function(e,t,i,r,s,n){if(e<-9999||e>9999)return by(e,4,s.length>0);var o=Math.abs(e),a=s;if(0===o)return t[0]+a;for(var l=0;o>0&&l<=4;l++){var u=o%10;0===u&&Sm(n,1)&&""!==a?a=t[u]+a:u>1||1===u&&0===l||1===u&&1===l&&Sm(n,2)||1===u&&1===l&&Sm(n,4)&&e>100||1===u&&l>1&&Sm(n,8)?a=t[u]+(l>0?i[l-1]:"")+a:1===u&&l>0&&(a=i[l-1]+a),o=Math.floor(o/10)}return(e<0?r:"")+a},by=function(e,t,i){var r=i?". ":"",s=i?"、":"",n=i?", ":"",o=i?" ":"";switch(t){case 0:return"•"+o;case 1:return"◦"+o;case 2:return"◾"+o;case 5:var a=my(e,48,57,!0,r);return a.length<4?"0"+a:a;case 4:return _y(e,"〇一二三四五六七八九",s);case 6:return vy(e,1,3999,hy,3,r).toLowerCase();case 7:return vy(e,1,3999,hy,3,r);case 8:return my(e,945,969,!1,r);case 9:return my(e,97,122,!1,r);case 10:return my(e,65,90,!1,r);case 11:return my(e,1632,1641,!0,r);case 12:case 49:return vy(e,1,9999,dy,3,r);case 35:return vy(e,1,9999,dy,3,r).toLowerCase();case 13:return my(e,2534,2543,!0,r);case 14:case 30:return my(e,6112,6121,!0,r);case 15:return _y(e,"子丑寅卯辰巳午未申酉戌亥",s);case 16:return _y(e,"甲乙丙丁戊己庚辛壬癸",s);case 17:case 48:return yy(e,"零一二三四五六七八九","十百千萬","負",s,14);case 47:return yy(e,"零壹貳參肆伍陸柒捌玖","拾佰仟萬","負",s,15);case 42:return yy(e,"零一二三四五六七八九","十百千萬","负",s,14);case 41:return yy(e,"零壹贰叁肆伍陆柒捌玖","拾佰仟萬","负",s,15);case 26:return yy(e,"〇一二三四五六七八九","十百千万","マイナス",s,0);case 25:return yy(e,"零壱弐参四伍六七八九","拾百千万","マイナス",s,7);case 31:return yy(e,"영일이삼사오육칠팔구","십백천만","마이너스",n,7);case 33:return yy(e,"零一二三四五六七八九","十百千萬","마이너스",n,0);case 32:return yy(e,"零壹貳參四五六七八九","拾百千","마이너스",n,7);case 18:return my(e,2406,2415,!0,r);case 20:return vy(e,1,19999,fy,3,r);case 21:return my(e,2790,2799,!0,r);case 22:return my(e,2662,2671,!0,r);case 22:return vy(e,1,10999,py,3,r);case 23:return _y(e,"あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわゐゑをん");case 24:return _y(e,"いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす");case 27:return my(e,3302,3311,!0,r);case 28:return _y(e,"アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヰヱヲン",s);case 29:return _y(e,"イロハニホヘトチリヌルヲワカヨタレソツネナラムウヰノオクヤマケフコエテアサキユメミシヱヒモセス",s);case 34:return my(e,3792,3801,!0,r);case 37:return my(e,6160,6169,!0,r);case 38:return my(e,4160,4169,!0,r);case 39:return my(e,2918,2927,!0,r);case 40:return my(e,1776,1785,!0,r);case 43:return my(e,3046,3055,!0,r);case 44:return my(e,3174,3183,!0,r);case 45:return my(e,3664,3673,!0,r);case 46:return my(e,3872,3881,!0,r);default:return my(e,48,57,!0,r)}},xy=function(){function e(e,t,i){if(this.context=e,this.options=i,this.scrolledElements=[],this.referenceElement=t,this.counters=new Ay,this.quoteDepth=0,!t.ownerDocument)throw new Error("Cloned element does not have an owner document");this.documentElement=this.cloneNode(t.ownerDocument.documentElement,!1)}return e.prototype.toIFrame=function(e,t){var i=this,r=By(e,t);if(!r.contentWindow)return Promise.reject("Unable to find iframe window");var s=e.defaultView.pageXOffset,n=e.defaultView.pageYOffset,o=r.contentWindow,a=o.document,l=My(r).then((function(){return Vp(i,void 0,void 0,(function(){var e,i;return Hp(this,(function(s){switch(s.label){case 0:return this.scrolledElements.forEach(Dy),o&&(o.scrollTo(t.left,t.top),!/(iPad|iPhone|iPod)/g.test(navigator.userAgent)||o.scrollY===t.top&&o.scrollX===t.left||(this.context.logger.warn("Unable to restore scroll position for cloned document"),this.context.windowBounds=this.context.windowBounds.add(o.scrollX-t.left,o.scrollY-t.top,0,0))),e=this.options.onclone,void 0===(i=this.clonedReferenceElement)?[2,Promise.reject("Error finding the "+this.referenceElement.nodeName+" in the cloned document")]:a.fonts&&a.fonts.ready?[4,a.fonts.ready]:[3,2];case 1:s.sent(),s.label=2;case 2:return/(AppleWebKit)/g.test(navigator.userAgent)?[4,Cy(a)]:[3,4];case 3:s.sent(),s.label=4;case 4:return"function"==typeof e?[2,Promise.resolve().then((function(){return e(a,i)})).then((function(){return r}))]:[2,r]}}))}))}));return a.open(),a.write(ky(document.doctype)+""),Iy(this.referenceElement.ownerDocument,s,n),a.replaceChild(a.adoptNode(this.documentElement),a.documentElement),a.close(),l},e.prototype.createElementClone=function(e){if(Xm(e,2),iy(e))return this.createCanvasClone(e);if(ry(e))return this.createVideoClone(e);if(oy(e))return this.createStyleClone(e);var t=e.cloneNode(!1);return sy(t)&&(sy(e)&&e.currentSrc&&e.currentSrc!==e.src&&(t.src=e.currentSrc,t.srcset=""),"lazy"===t.loading&&(t.loading="eager")),cy(t)?this.createCustomElementClone(t):t},e.prototype.createCustomElementClone=function(e){var t=document.createElement("html2canvascustomelement");return Fy(e.style,t),t},e.prototype.createStyleClone=function(e){try{var t=e.sheet;if(t&&t.cssRules){var i=[].slice.call(t.cssRules,0).reduce((function(e,t){return t&&"string"==typeof t.cssText?e+t.cssText:e}),""),r=e.cloneNode(!1);return r.textContent=i,r}}catch(e){if(this.context.logger.error("Unable to access cssRules property",e),"SecurityError"!==e.name)throw e}return e.cloneNode(!1)},e.prototype.createCanvasClone=function(e){var t;if(this.options.inlineImages&&e.ownerDocument){var i=e.ownerDocument.createElement("img");try{return i.src=e.toDataURL(),i}catch(t){this.context.logger.info("Unable to inline canvas contents, canvas is tainted",e)}}var r=e.cloneNode(!1);try{r.width=e.width,r.height=e.height;var s=e.getContext("2d"),n=r.getContext("2d");if(n)if(!this.options.allowTaint&&s)n.putImageData(s.getImageData(0,0,e.width,e.height),0,0);else{var o=null!==(t=e.getContext("webgl2"))&&void 0!==t?t:e.getContext("webgl");if(o){var a=o.getContextAttributes();!1===(null==a?void 0:a.preserveDrawingBuffer)&&this.context.logger.warn("Unable to clone WebGL context as it has preserveDrawingBuffer=false",e)}n.drawImage(e,0,0)}return r}catch(t){this.context.logger.info("Unable to clone canvas as it is tainted",e)}return r},e.prototype.createVideoClone=function(e){var t=e.ownerDocument.createElement("canvas");t.width=e.offsetWidth,t.height=e.offsetHeight;var i=t.getContext("2d");try{return i&&(i.drawImage(e,0,0,t.width,t.height),this.options.allowTaint||i.getImageData(0,0,t.width,t.height)),t}catch(t){this.context.logger.info("Unable to clone video as it is tainted",e)}var r=e.ownerDocument.createElement("canvas");return r.width=e.offsetWidth,r.height=e.offsetHeight,r},e.prototype.appendChildNode=function(e,t,i){X_(t)&&(function(e){return"SCRIPT"===e.tagName}(t)||t.hasAttribute("data-html2canvas-ignore")||"function"==typeof this.options.ignoreElements&&this.options.ignoreElements(t))||this.options.copyStyles&&X_(t)&&oy(t)||e.appendChild(this.cloneNode(t,i))},e.prototype.cloneChildNodes=function(e,t,i){for(var r=this,s=e.shadowRoot?e.shadowRoot.firstChild:e.firstChild;s;s=s.nextSibling)if(X_(s)&&uy(s)&&"function"==typeof s.assignedNodes){var n=s.assignedNodes();n.length&&n.forEach((function(e){return r.appendChildNode(t,e,i)}))}else this.appendChildNode(t,s,i)},e.prototype.cloneNode=function(e,t){if(K_(e))return document.createTextNode(e.data);if(!e.ownerDocument)return e.cloneNode(!1);var i=e.ownerDocument.defaultView;if(i&&X_(e)&&(J_(e)||Y_(e))){var r=this.createElementClone(e);r.style.transitionProperty="none";var s=i.getComputedStyle(e),n=i.getComputedStyle(e,":before"),o=i.getComputedStyle(e,":after");this.referenceElement===e&&J_(r)&&(this.clonedReferenceElement=r),ty(r)&&Ly(r);var a=this.counters.parse(new Wm(this.context,s)),l=this.resolvePseudoContent(e,r,n,s_.BEFORE);cy(e)&&(t=!0),ry(e)||this.cloneChildNodes(e,r,t),l&&r.insertBefore(l,r.firstChild);var u=this.resolvePseudoContent(e,r,o,s_.AFTER);return u&&r.appendChild(u),this.counters.pop(a),(s&&(this.options.copyStyles||Y_(e))&&!ny(e)||t)&&Fy(s,r),0===e.scrollTop&&0===e.scrollLeft||this.scrolledElements.push([r,e.scrollLeft,e.scrollTop]),(ay(e)||ly(e))&&(ay(r)||ly(r))&&(r.value=e.value),r}return e.cloneNode(!1)},e.prototype.resolvePseudoContent=function(e,t,i,r){var s=this;if(i){var n=i.content,o=t.ownerDocument;if(o&&n&&"none"!==n&&"-moz-alt-content"!==n&&"none"!==i.display){this.counters.parse(new Wm(this.context,i));var a=new zm(this.context,i),l=o.createElement("html2canvaspseudoelement");Fy(i,l),a.content.forEach((function(t){if(0===t.type)l.appendChild(o.createTextNode(t.value));else if(22===t.type){var i=o.createElement("img");i.src=t.value,i.style.opacity="1",l.appendChild(i)}else if(18===t.type){if("attr"===t.name){var r=t.values.filter(Pv);r.length&&l.appendChild(o.createTextNode(e.getAttribute(r[0].value)||""))}else if("counter"===t.name){var n=t.values.filter(Fv),u=n[0],c=n[1];if(u&&Pv(u)){var A=s.counters.getCounterValue(u.value),h=c&&Pv(c)?$g.parse(s.context,c.value):3;l.appendChild(o.createTextNode(by(A,h,!1)))}}else if("counters"===t.name){var d=t.values.filter(Fv),p=(u=d[0],d[1]);c=d[2];if(u&&Pv(u)){var f=s.counters.getCounterValues(u.value),v=c&&Pv(c)?$g.parse(s.context,c.value):3,g=p&&0===p.type?p.value:"",m=f.map((function(e){return by(e,v,!1)})).join(g);l.appendChild(o.createTextNode(m))}}}else if(20===t.type)switch(t.value){case"open-quote":l.appendChild(o.createTextNode(Nm(a.quotes,s.quoteDepth++,!0)));break;case"close-quote":l.appendChild(o.createTextNode(Nm(a.quotes,--s.quoteDepth,!1)));break;default:l.appendChild(o.createTextNode(t.value))}})),l.className=Sy+" "+Ty;var u=r===s_.BEFORE?" "+Sy:" "+Ty;return Y_(t)?t.className.baseValue+=u:t.className+=u,l}}},e.destroy=function(e){return!!e.parentNode&&(e.parentNode.removeChild(e),!0)},e}();!function(e){e[e.BEFORE=0]="BEFORE",e[e.AFTER=1]="AFTER"}(s_||(s_={}));var wy,By=function(e,t){var i=e.createElement("iframe");return i.className="html2canvas-container",i.style.visibility="hidden",i.style.position="fixed",i.style.left="-10000px",i.style.top="0px",i.style.border="0",i.width=t.width.toString(),i.height=t.height.toString(),i.scrolling="no",i.setAttribute("data-html2canvas-ignore","true"),e.body.appendChild(i),i},Py=function(e){return new Promise((function(t){e.complete?t():e.src?(e.onload=t,e.onerror=t):t()}))},Cy=function(e){return Promise.all([].slice.call(e.images,0).map(Py))},My=function(e){return new Promise((function(t,i){var r=e.contentWindow;if(!r)return i("No window assigned for iframe");var s=r.document;r.onload=e.onload=function(){r.onload=e.onload=null;var i=setInterval((function(){s.body.childNodes.length>0&&"complete"===s.readyState&&(clearInterval(i),t(e))}),50)}}))},Ey=["all","d","content"],Fy=function(e,t){for(var i=e.length-1;i>=0;i--){var r=e.item(i);-1===Ey.indexOf(r)&&t.style.setProperty(r,e.getPropertyValue(r))}return t},ky=function(e){var t="";return e&&(t+=""),t},Iy=function(e,t,i){e&&e.defaultView&&(t!==e.defaultView.pageXOffset||i!==e.defaultView.pageYOffset)&&e.defaultView.scrollTo(t,i)},Dy=function(e){var t=e[0],i=e[1],r=e[2];t.scrollLeft=i,t.scrollTop=r},Sy="___html2canvas___pseudoelement_before",Ty="___html2canvas___pseudoelement_after",Ly=function(e){Ry(e,"."+Sy+':before{\n content: "" !important;\n display: none !important;\n}\n .'+Ty+':after{\n content: "" !important;\n display: none !important;\n}')},Ry=function(e,t){var i=e.ownerDocument;if(i){var r=i.createElement("style");r.textContent=t,e.appendChild(r)}},Uy=function(){function e(){}return e.getOrigin=function(t){var i=e._link;return i?(i.href=t,i.href=i.href,i.protocol+i.hostname+i.port):"about:blank"},e.isSameOrigin=function(t){return e.getOrigin(t)===e._origin},e.setContext=function(t){e._link=t.document.createElement("a"),e._origin=e.getOrigin(t.location.href)},e._origin="about:blank",e}(),Oy=function(){function e(e,t){this.context=e,this._options=t,this._cache={}}return e.prototype.addImage=function(e){var t=Promise.resolve();return this.has(e)?t:zy(e)||Hy(e)?((this._cache[e]=this.loadImage(e)).catch((function(){})),t):t},e.prototype.match=function(e){return this._cache[e]},e.prototype.loadImage=function(e){return Vp(this,void 0,void 0,(function(){var t,i,r,s,n=this;return Hp(this,(function(o){switch(o.label){case 0:return t=Uy.isSameOrigin(e),i=!jy(e)&&!0===this._options.useCORS&&g_.SUPPORT_CORS_IMAGES&&!t,r=!jy(e)&&!t&&!zy(e)&&"string"==typeof this._options.proxy&&g_.SUPPORT_CORS_XHR&&!i,t||!1!==this._options.allowTaint||jy(e)||zy(e)||r||i?(s=e,r?[4,this.proxy(s)]:[3,2]):[2];case 1:s=o.sent(),o.label=2;case 2:return this.context.logger.debug("Added image "+e.substring(0,256)),[4,new Promise((function(e,t){var r=new Image;r.onload=function(){return e(r)},r.onerror=t,(Gy(s)||i)&&(r.crossOrigin="anonymous"),r.src=s,!0===r.complete&&setTimeout((function(){return e(r)}),500),n._options.imageTimeout>0&&setTimeout((function(){return t("Timed out ("+n._options.imageTimeout+"ms) loading image")}),n._options.imageTimeout)}))];case 3:return[2,o.sent()]}}))}))},e.prototype.has=function(e){return void 0!==this._cache[e]},e.prototype.keys=function(){return Promise.resolve(Object.keys(this._cache))},e.prototype.proxy=function(e){var t=this,i=this._options.proxy;if(!i)throw new Error("No proxy defined");var r=e.substring(0,256);return new Promise((function(s,n){var o=g_.SUPPORT_RESPONSE_TYPE?"blob":"text",a=new XMLHttpRequest;a.onload=function(){if(200===a.status)if("text"===o)s(a.response);else{var e=new FileReader;e.addEventListener("load",(function(){return s(e.result)}),!1),e.addEventListener("error",(function(e){return n(e)}),!1),e.readAsDataURL(a.response)}else n("Failed to proxy resource "+r+" with status code "+a.status)},a.onerror=n;var l=i.indexOf("?")>-1?"&":"?";if(a.open("GET",""+i+l+"url="+encodeURIComponent(e)+"&responseType="+o),"text"!==o&&a instanceof XMLHttpRequest&&(a.responseType=o),t._options.imageTimeout){var u=t._options.imageTimeout;a.timeout=u,a.ontimeout=function(){return n("Timed out ("+u+"ms) proxying "+r)}}a.send()}))},e}(),Ny=/^data:image\/svg\+xml/i,Qy=/^data:image\/.*;base64,/i,Vy=/^data:image\/.*/i,Hy=function(e){return g_.SUPPORT_SVG_DRAWING||!Wy(e)},jy=function(e){return Vy.test(e)},Gy=function(e){return Qy.test(e)},zy=function(e){return"blob"===e.substr(0,4)},Wy=function(e){return"svg"===e.substr(-3).toLowerCase()||Ny.test(e)},Ky=function(){function e(e,t){this.type=0,this.x=e,this.y=t}return e.prototype.add=function(t,i){return new e(this.x+t,this.y+i)},e}(),Xy=function(e,t,i){return new Ky(e.x+(t.x-e.x)*i,e.y+(t.y-e.y)*i)},Jy=function(){function e(e,t,i,r){this.type=1,this.start=e,this.startControl=t,this.endControl=i,this.end=r}return e.prototype.subdivide=function(t,i){var r=Xy(this.start,this.startControl,t),s=Xy(this.startControl,this.endControl,t),n=Xy(this.endControl,this.end,t),o=Xy(r,s,t),a=Xy(s,n,t),l=Xy(o,a,t);return i?new e(this.start,r,o,l):new e(l,a,n,this.end)},e.prototype.add=function(t,i){return new e(this.start.add(t,i),this.startControl.add(t,i),this.endControl.add(t,i),this.end.add(t,i))},e.prototype.reverse=function(){return new e(this.end,this.endControl,this.startControl,this.start)},e}(),Yy=function(e){return 1===e.type},Zy=function(e){var t=e.styles,i=e.bounds,r=Ov(t.borderTopLeftRadius,i.width,i.height),s=r[0],n=r[1],o=Ov(t.borderTopRightRadius,i.width,i.height),a=o[0],l=o[1],u=Ov(t.borderBottomRightRadius,i.width,i.height),c=u[0],A=u[1],h=Ov(t.borderBottomLeftRadius,i.width,i.height),d=h[0],p=h[1],f=[];f.push((s+a)/i.width),f.push((d+c)/i.width),f.push((n+p)/i.height),f.push((l+A)/i.height);var v=Math.max.apply(Math,f);v>1&&(s/=v,n/=v,a/=v,l/=v,c/=v,A/=v,d/=v,p/=v);var g=i.width-a,m=i.height-A,_=i.width-c,y=i.height-p,b=t.borderTopWidth,x=t.borderRightWidth,w=t.borderBottomWidth,B=t.borderLeftWidth,P=Nv(t.paddingTop,e.bounds.width),C=Nv(t.paddingRight,e.bounds.width),M=Nv(t.paddingBottom,e.bounds.width),E=Nv(t.paddingLeft,e.bounds.width);this.topLeftBorderDoubleOuterBox=s>0||n>0?qy(i.left+B/3,i.top+b/3,s-B/3,n-b/3,wy.TOP_LEFT):new Ky(i.left+B/3,i.top+b/3),this.topRightBorderDoubleOuterBox=s>0||n>0?qy(i.left+g,i.top+b/3,a-x/3,l-b/3,wy.TOP_RIGHT):new Ky(i.left+i.width-x/3,i.top+b/3),this.bottomRightBorderDoubleOuterBox=c>0||A>0?qy(i.left+_,i.top+m,c-x/3,A-w/3,wy.BOTTOM_RIGHT):new Ky(i.left+i.width-x/3,i.top+i.height-w/3),this.bottomLeftBorderDoubleOuterBox=d>0||p>0?qy(i.left+B/3,i.top+y,d-B/3,p-w/3,wy.BOTTOM_LEFT):new Ky(i.left+B/3,i.top+i.height-w/3),this.topLeftBorderDoubleInnerBox=s>0||n>0?qy(i.left+2*B/3,i.top+2*b/3,s-2*B/3,n-2*b/3,wy.TOP_LEFT):new Ky(i.left+2*B/3,i.top+2*b/3),this.topRightBorderDoubleInnerBox=s>0||n>0?qy(i.left+g,i.top+2*b/3,a-2*x/3,l-2*b/3,wy.TOP_RIGHT):new Ky(i.left+i.width-2*x/3,i.top+2*b/3),this.bottomRightBorderDoubleInnerBox=c>0||A>0?qy(i.left+_,i.top+m,c-2*x/3,A-2*w/3,wy.BOTTOM_RIGHT):new Ky(i.left+i.width-2*x/3,i.top+i.height-2*w/3),this.bottomLeftBorderDoubleInnerBox=d>0||p>0?qy(i.left+2*B/3,i.top+y,d-2*B/3,p-2*w/3,wy.BOTTOM_LEFT):new Ky(i.left+2*B/3,i.top+i.height-2*w/3),this.topLeftBorderStroke=s>0||n>0?qy(i.left+B/2,i.top+b/2,s-B/2,n-b/2,wy.TOP_LEFT):new Ky(i.left+B/2,i.top+b/2),this.topRightBorderStroke=s>0||n>0?qy(i.left+g,i.top+b/2,a-x/2,l-b/2,wy.TOP_RIGHT):new Ky(i.left+i.width-x/2,i.top+b/2),this.bottomRightBorderStroke=c>0||A>0?qy(i.left+_,i.top+m,c-x/2,A-w/2,wy.BOTTOM_RIGHT):new Ky(i.left+i.width-x/2,i.top+i.height-w/2),this.bottomLeftBorderStroke=d>0||p>0?qy(i.left+B/2,i.top+y,d-B/2,p-w/2,wy.BOTTOM_LEFT):new Ky(i.left+B/2,i.top+i.height-w/2),this.topLeftBorderBox=s>0||n>0?qy(i.left,i.top,s,n,wy.TOP_LEFT):new Ky(i.left,i.top),this.topRightBorderBox=a>0||l>0?qy(i.left+g,i.top,a,l,wy.TOP_RIGHT):new Ky(i.left+i.width,i.top),this.bottomRightBorderBox=c>0||A>0?qy(i.left+_,i.top+m,c,A,wy.BOTTOM_RIGHT):new Ky(i.left+i.width,i.top+i.height),this.bottomLeftBorderBox=d>0||p>0?qy(i.left,i.top+y,d,p,wy.BOTTOM_LEFT):new Ky(i.left,i.top+i.height),this.topLeftPaddingBox=s>0||n>0?qy(i.left+B,i.top+b,Math.max(0,s-B),Math.max(0,n-b),wy.TOP_LEFT):new Ky(i.left+B,i.top+b),this.topRightPaddingBox=a>0||l>0?qy(i.left+Math.min(g,i.width-x),i.top+b,g>i.width+x?0:Math.max(0,a-x),Math.max(0,l-b),wy.TOP_RIGHT):new Ky(i.left+i.width-x,i.top+b),this.bottomRightPaddingBox=c>0||A>0?qy(i.left+Math.min(_,i.width-B),i.top+Math.min(m,i.height-w),Math.max(0,c-x),Math.max(0,A-w),wy.BOTTOM_RIGHT):new Ky(i.left+i.width-x,i.top+i.height-w),this.bottomLeftPaddingBox=d>0||p>0?qy(i.left+B,i.top+Math.min(y,i.height-w),Math.max(0,d-B),Math.max(0,p-w),wy.BOTTOM_LEFT):new Ky(i.left+B,i.top+i.height-w),this.topLeftContentBox=s>0||n>0?qy(i.left+B+E,i.top+b+P,Math.max(0,s-(B+E)),Math.max(0,n-(b+P)),wy.TOP_LEFT):new Ky(i.left+B+E,i.top+b+P),this.topRightContentBox=a>0||l>0?qy(i.left+Math.min(g,i.width+B+E),i.top+b+P,g>i.width+B+E?0:a-B+E,l-(b+P),wy.TOP_RIGHT):new Ky(i.left+i.width-(x+C),i.top+b+P),this.bottomRightContentBox=c>0||A>0?qy(i.left+Math.min(_,i.width-(B+E)),i.top+Math.min(m,i.height+b+P),Math.max(0,c-(x+C)),A-(w+M),wy.BOTTOM_RIGHT):new Ky(i.left+i.width-(x+C),i.top+i.height-(w+M)),this.bottomLeftContentBox=d>0||p>0?qy(i.left+B+E,i.top+y,Math.max(0,d-(B+E)),p-(w+M),wy.BOTTOM_LEFT):new Ky(i.left+B+E,i.top+i.height-(w+M))};!function(e){e[e.TOP_LEFT=0]="TOP_LEFT",e[e.TOP_RIGHT=1]="TOP_RIGHT",e[e.BOTTOM_RIGHT=2]="BOTTOM_RIGHT",e[e.BOTTOM_LEFT=3]="BOTTOM_LEFT"}(wy||(wy={}));var qy=function(e,t,i,r,s){var n=(Math.sqrt(2)-1)/3*4,o=i*n,a=r*n,l=e+i,u=t+r;switch(s){case wy.TOP_LEFT:return new Jy(new Ky(e,u),new Ky(e,u-a),new Ky(l-o,t),new Ky(l,t));case wy.TOP_RIGHT:return new Jy(new Ky(e,t),new Ky(e+o,t),new Ky(l,u-a),new Ky(l,u));case wy.BOTTOM_RIGHT:return new Jy(new Ky(l,t),new Ky(l,t+a),new Ky(e+o,u),new Ky(e,u));case wy.BOTTOM_LEFT:default:return new Jy(new Ky(l,u),new Ky(l-o,u),new Ky(e,t+a),new Ky(e,t))}},$y=function(e){return[e.topLeftBorderBox,e.topRightBorderBox,e.bottomRightBorderBox,e.bottomLeftBorderBox]},eb=function(e){return[e.topLeftPaddingBox,e.topRightPaddingBox,e.bottomRightPaddingBox,e.bottomLeftPaddingBox]},tb=function(e,t,i){this.offsetX=e,this.offsetY=t,this.matrix=i,this.type=0,this.target=6},ib=function(e,t){this.path=e,this.target=t,this.type=1},rb=function(e){this.opacity=e,this.type=2,this.target=6},sb=function(e){return 1===e.type},nb=function(e,t){return e.length===t.length&&e.some((function(e,i){return e===t[i]}))},ob=function(e){this.element=e,this.inlineLevel=[],this.nonInlineLevel=[],this.negativeZIndex=[],this.zeroOrAutoZIndexOrTransformedOrOpacity=[],this.positiveZIndex=[],this.nonPositionedFloats=[],this.nonPositionedInlineLevel=[]},ab=function(){function e(e,t){if(this.container=e,this.parent=t,this.effects=[],this.curves=new Zy(this.container),this.container.styles.opacity<1&&this.effects.push(new rb(this.container.styles.opacity)),null!==this.container.styles.transform){var i=this.container.bounds.left+this.container.styles.transformOrigin[0].number,r=this.container.bounds.top+this.container.styles.transformOrigin[1].number,s=this.container.styles.transform;this.effects.push(new tb(i,r,s))}if(0!==this.container.styles.overflowX){var n=$y(this.curves),o=eb(this.curves);nb(n,o)?this.effects.push(new ib(n,6)):(this.effects.push(new ib(n,2)),this.effects.push(new ib(o,4)))}}return e.prototype.getEffects=function(e){for(var t=-1===[2,3].indexOf(this.container.styles.position),i=this.parent,r=this.effects.slice(0);i;){var s=i.effects.filter((function(e){return!sb(e)}));if(t||0!==i.container.styles.position||!i.parent){if(r.unshift.apply(r,s),t=-1===[2,3].indexOf(i.container.styles.position),0!==i.container.styles.overflowX){var n=$y(i.curves),o=eb(i.curves);nb(n,o)||r.unshift(new ib(o,6))}}else r.unshift.apply(r,s);i=i.parent}return r.filter((function(t){return Sm(t.target,e)}))},e}(),lb=function e(t,i,r,s){t.container.elements.forEach((function(n){var o=Sm(n.flags,4),a=Sm(n.flags,2),l=new ab(n,t);Sm(n.styles.display,2048)&&s.push(l);var u=Sm(n.flags,8)?[]:s;if(o||a){var c=o||n.styles.isPositioned()?r:i,A=new ob(l);if(n.styles.isPositioned()||n.styles.opacity<1||n.styles.isTransformed()){var h=n.styles.zIndex.order;if(h<0){var d=0;c.negativeZIndex.some((function(e,t){return h>e.element.container.styles.zIndex.order?(d=t,!1):d>0})),c.negativeZIndex.splice(d,0,A)}else if(h>0){var p=0;c.positiveZIndex.some((function(e,t){return h>=e.element.container.styles.zIndex.order?(p=t+1,!1):p>0})),c.positiveZIndex.splice(p,0,A)}else c.zeroOrAutoZIndexOrTransformedOrOpacity.push(A)}else n.styles.isFloating()?c.nonPositionedFloats.push(A):c.nonPositionedInlineLevel.push(A);e(l,A,o?A:r,u)}else n.styles.isInlineLevel()?i.inlineLevel.push(l):i.nonInlineLevel.push(l),e(l,i,r,u);Sm(n.flags,8)&&ub(n,u)}))},ub=function(e,t){for(var i=e instanceof S_?e.start:1,r=e instanceof S_&&e.reversed,s=0;s0&&e.intrinsicHeight>0){var r=fb(e),s=eb(t);this.path(s),this.ctx.save(),this.ctx.clip(),this.ctx.drawImage(i,0,0,e.intrinsicWidth,e.intrinsicHeight,r.left,r.top,r.width,r.height),this.ctx.restore()}},t.prototype.renderNodeContent=function(e){return Vp(this,void 0,void 0,(function(){var i,r,s,n,o,a,l,u,c,A,h,d,p,f,v,g,m,_;return Hp(this,(function(y){switch(y.label){case 0:this.applyEffects(e.getEffects(4)),i=e.container,r=e.curves,s=i.styles,n=0,o=i.textNodes,y.label=1;case 1:return n0&&w>0&&(g=r.ctx.createPattern(p,"repeat"),r.renderRepeat(_,g,P,C))):function(e){return 2===e.type}(i)&&(m=vb(e,t,[null,null,null]),_=m[0],y=m[1],b=m[2],x=m[3],w=m[4],B=0===i.position.length?[Rv]:i.position,P=Nv(B[0],x),C=Nv(B[B.length-1],w),M=function(e,t,i,r,s){var n=0,o=0;switch(e.size){case 0:0===e.shape?n=o=Math.min(Math.abs(t),Math.abs(t-r),Math.abs(i),Math.abs(i-s)):1===e.shape&&(n=Math.min(Math.abs(t),Math.abs(t-r)),o=Math.min(Math.abs(i),Math.abs(i-s)));break;case 2:if(0===e.shape)n=o=Math.min(og(t,i),og(t,i-s),og(t-r,i),og(t-r,i-s));else if(1===e.shape){var a=Math.min(Math.abs(i),Math.abs(i-s))/Math.min(Math.abs(t),Math.abs(t-r)),l=ag(r,s,t,i,!0),u=l[0],c=l[1];o=a*(n=og(u-t,(c-i)/a))}break;case 1:0===e.shape?n=o=Math.max(Math.abs(t),Math.abs(t-r),Math.abs(i),Math.abs(i-s)):1===e.shape&&(n=Math.max(Math.abs(t),Math.abs(t-r)),o=Math.max(Math.abs(i),Math.abs(i-s)));break;case 3:if(0===e.shape)n=o=Math.max(og(t,i),og(t,i-s),og(t-r,i),og(t-r,i-s));else if(1===e.shape){a=Math.max(Math.abs(i),Math.abs(i-s))/Math.max(Math.abs(t),Math.abs(t-r));var A=ag(r,s,t,i,!1);u=A[0],c=A[1],o=a*(n=og(u-t,(c-i)/a))}}return Array.isArray(e.size)&&(n=Nv(e.size[0],r),o=2===e.size.length?Nv(e.size[1],s):n),[n,o]}(i,P,C,x,w),E=M[0],F=M[1],E>0&&F>0&&(k=r.ctx.createRadialGradient(y+P,b+C,0,y+P,b+C,E),sg(i.stops,2*E).forEach((function(e){return k.addColorStop(e.stop,Wv(e.color))})),r.path(_),r.ctx.fillStyle=k,E!==F?(I=e.bounds.left+.5*e.bounds.width,D=e.bounds.top+.5*e.bounds.height,T=1/(S=F/E),r.ctx.save(),r.ctx.translate(I,D),r.ctx.transform(1,0,0,S,0,0),r.ctx.translate(-I,-D),r.ctx.fillRect(y,T*(b-D)+D,x,w*T),r.ctx.restore()):r.ctx.fill())),L.label=6;case 6:return t--,[2]}}))},r=this,s=0,n=e.styles.backgroundImage.slice(0).reverse(),a.label=1;case 1:return s0?2!==l.style?[3,5]:[4,this.renderDashedDottedBorder(l.color,l.width,n,e.curves,2)]:[3,11]:[3,13];case 4:return c.sent(),[3,11];case 5:return 3!==l.style?[3,7]:[4,this.renderDashedDottedBorder(l.color,l.width,n,e.curves,3)];case 6:return c.sent(),[3,11];case 7:return 4!==l.style?[3,9]:[4,this.renderDoubleBorder(l.color,l.width,n,e.curves)];case 8:return c.sent(),[3,11];case 9:return[4,this.renderSolidBorder(l.color,n,e.curves)];case 10:c.sent(),c.label=11;case 11:n++,c.label=12;case 12:return o++,[3,3];case 13:return[2]}}))}))},t.prototype.renderDashedDottedBorder=function(e,t,i,r,s){return Vp(this,void 0,void 0,(function(){var n,o,a,l,u,c,A,h,d,p,f,v,g,m,_,y;return Hp(this,(function(b){return this.ctx.save(),n=function(e,t){switch(t){case 0:return hb(e.topLeftBorderStroke,e.topRightBorderStroke);case 1:return hb(e.topRightBorderStroke,e.bottomRightBorderStroke);case 2:return hb(e.bottomRightBorderStroke,e.bottomLeftBorderStroke);default:return hb(e.bottomLeftBorderStroke,e.topLeftBorderStroke)}}(r,i),o=Ab(r,i),2===s&&(this.path(o),this.ctx.clip()),Yy(o[0])?(a=o[0].start.x,l=o[0].start.y):(a=o[0].x,l=o[0].y),Yy(o[1])?(u=o[1].end.x,c=o[1].end.y):(u=o[1].x,c=o[1].y),A=0===i||2===i?Math.abs(a-u):Math.abs(l-c),this.ctx.beginPath(),3===s?this.formatPath(n):this.formatPath(o.slice(0,2)),h=t<3?3*t:2*t,d=t<3?2*t:t,3===s&&(h=t,d=t),p=!0,A<=2*h?p=!1:A<=2*h+d?(h*=f=A/(2*h+d),d*=f):(v=Math.floor((A+d)/(h+d)),g=(A-v*h)/(v-1),d=(m=(A-(v+1)*h)/v)<=0||Math.abs(d-g)0&&void 0!==arguments[0]?arguments[0]:{},t=!this._snapshotBegun,i=void 0!==e.width&&void 0!==e.height,r=this.scene.canvas.canvas,s=r.clientWidth,n=r.clientHeight,o=e.width?Math.floor(e.width):r.width,a=e.height?Math.floor(e.height):r.height;i&&(r.width=o,r.height=a),this._snapshotBegun||this.beginSnapshot({width:o,height:a}),e.includeGizmos||this.sendToPlugins("snapshotStarting");for(var l={},u=0,c=this._plugins.length;u0&&void 0!==b[0]?b[0]:{},i=!this._snapshotBegun,r=void 0!==t.width&&void 0!==t.height,s=this.scene.canvas.canvas,n=s.clientWidth,o=s.clientHeight,l=t.width?Math.floor(t.width):s.width,u=t.height?Math.floor(t.height):s.height,r&&(s.width=l,s.height=u),this._snapshotBegun||this.beginSnapshot(),t.includeGizmos||this.sendToPlugins("snapshotStarting"),this.scene._renderer.renderSnapshot(),c=this.scene._renderer.readSnapshotAsCanvas(),r&&(s.width=n,s.height=o,this.scene.glRedraw()),A={},h=[],d=0,p=this._plugins.length;d1&&void 0!==arguments[1])||arguments[1],i=arguments.length>2?arguments[2]:void 0,r=i||new Set;if(e){if(tx(e))r.add(e);else if(tx(e.buffer))r.add(e.buffer);else if(ArrayBuffer.isView(e));else if(t&&"object"===w(e))for(var s in e)ex(e[s],t,r)}else;return void 0===i?Array.from(r):[]}function tx(e){return!!e&&(e instanceof ArrayBuffer||("undefined"!=typeof MessagePort&&e instanceof MessagePort||("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)))}var ix=function(){},rx=function(){function e(t){B(this,e),Xb(this,"name",void 0),Xb(this,"source",void 0),Xb(this,"url",void 0),Xb(this,"terminated",!1),Xb(this,"worker",void 0),Xb(this,"onMessage",void 0),Xb(this,"onError",void 0),Xb(this,"_loadableURL","");var i=t.name,r=t.source,s=t.url;Vb(r||s),this.name=i,this.source=r,this.url=s,this.onMessage=ix,this.onError=function(e){return console.log(e)},this.worker=Gb?this._createBrowserWorker():this._createNodeWorker()}return C(e,[{key:"destroy",value:function(){this.onMessage=ix,this.onError=ix,this.worker.terminate(),this.terminated=!0}},{key:"isRunning",get:function(){return Boolean(this.onMessage)}},{key:"postMessage",value:function(e,t){t=t||ex(e),this.worker.postMessage(e,t)}},{key:"_getErrorFromErrorEvent",value:function(e){var t="Failed to load ";return t+="worker ".concat(this.name," from ").concat(this.url,". "),e.message&&(t+="".concat(e.message," in ")),e.lineno&&(t+=":".concat(e.lineno,":").concat(e.colno)),new Error(t)}},{key:"_createBrowserWorker",value:function(){var e=this;this._loadableURL=qb({source:this.source,url:this.url});var t=new Worker(this._loadableURL,{name:this.name});return t.onmessage=function(t){t.data?e.onMessage(t.data):e.onError(new Error("No data received"))},t.onerror=function(t){e.onError(e._getErrorFromErrorEvent(t)),e.terminated=!0},t.onmessageerror=function(e){return console.error(e)},t}},{key:"_createNodeWorker",value:function(){var e,t=this;if(this.url){var i=this.url.includes(":/")||this.url.startsWith("/")?this.url:"./".concat(this.url);e=new Yb(i,{eval:!1})}else{if(!this.source)throw new Error("no worker");e=new Yb(this.source,{eval:!0})}return e.on("message",(function(e){t.onMessage(e)})),e.on("error",(function(e){t.onError(e)})),e.on("exit",(function(e){})),e}}],[{key:"isSupported",value:function(){return"undefined"!=typeof Worker&&Gb||void 0!==w(Yb)}}]),e}(),sx=function(){function e(t){B(this,e),Xb(this,"name","unnamed"),Xb(this,"source",void 0),Xb(this,"url",void 0),Xb(this,"maxConcurrency",1),Xb(this,"maxMobileConcurrency",1),Xb(this,"onDebug",(function(){})),Xb(this,"reuseWorkers",!0),Xb(this,"props",{}),Xb(this,"jobQueue",[]),Xb(this,"idleQueue",[]),Xb(this,"count",0),Xb(this,"isDestroyed",!1),this.source=t.source,this.url=t.url,this.setProps(t)}var t,i;return C(e,[{key:"destroy",value:function(){this.idleQueue.forEach((function(e){return e.destroy()})),this.isDestroyed=!0}},{key:"setProps",value:function(e){this.props=n(n({},this.props),e),void 0!==e.name&&(this.name=e.name),void 0!==e.maxConcurrency&&(this.maxConcurrency=e.maxConcurrency),void 0!==e.maxMobileConcurrency&&(this.maxMobileConcurrency=e.maxMobileConcurrency),void 0!==e.reuseWorkers&&(this.reuseWorkers=e.reuseWorkers),void 0!==e.onDebug&&(this.onDebug=e.onDebug)}},{key:"startJob",value:(i=u(a().mark((function e(t){var i,r,s,n=this,o=arguments;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=o.length>1&&void 0!==o[1]?o[1]:function(e,t,i){return e.done(i)},r=o.length>2&&void 0!==o[2]?o[2]:function(e,t){return e.error(t)},s=new Promise((function(e){return n.jobQueue.push({name:t,onMessage:i,onError:r,onStart:e}),n})),this._startQueuedJob(),e.next=6,s;case 6:return e.abrupt("return",e.sent);case 7:case"end":return e.stop()}}),e,this)}))),function(e){return i.apply(this,arguments)})},{key:"_startQueuedJob",value:(t=u(a().mark((function e(){var t,i,r;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.jobQueue.length){e.next=2;break}return e.abrupt("return");case 2:if(t=this._getAvailableWorker()){e.next=5;break}return e.abrupt("return");case 5:if(!(i=this.jobQueue.shift())){e.next=18;break}return this.onDebug({message:"Starting job",name:i.name,workerThread:t,backlog:this.jobQueue.length}),r=new Jb(i.name,t),t.onMessage=function(e){return i.onMessage(r,e.type,e.payload)},t.onError=function(e){return i.onError(r,e)},i.onStart(r),e.prev=12,e.next=15,r.result;case 15:return e.prev=15,this.returnWorkerToQueue(t),e.finish(15);case 18:case"end":return e.stop()}}),e,this,[[12,,15,18]])}))),function(){return t.apply(this,arguments)})},{key:"returnWorkerToQueue",value:function(e){this.isDestroyed||!this.reuseWorkers||this.count>this._getMaxConcurrency()?(e.destroy(),this.count--):this.idleQueue.push(e),this.isDestroyed||this._startQueuedJob()}},{key:"_getAvailableWorker",value:function(){if(this.idleQueue.length>0)return this.idleQueue.shift()||null;if(this.count0&&void 0!==arguments[0]?arguments[0]:{};return e._workerFarm=e._workerFarm||new e({}),e._workerFarm.setProps(t),e._workerFarm}}]),e}();Xb(ox,"_workerFarm",void 0);function ax(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t[e.id]||{},r="".concat(e.id,"-worker.js"),s=i.workerUrl;if(s||"compression"!==e.id||(s=t.workerUrl),"test"===t._workerType&&(s="modules/".concat(e.module,"/dist/").concat(r)),!s){var n=e.version;"latest"===n&&(n="latest");var o=n?"@".concat(n):"";s="https://unpkg.com/@loaders.gl/".concat(e.module).concat(o,"/dist/").concat(r)}return Vb(s),s}function lx(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"3.2.6";Vb(e,"no worker provided");var i=e.version;return!(!t||!i)}var ux=Object.freeze({__proto__:null,default:{}}),cx={};function Ax(e){return hx.apply(this,arguments)}function hx(){return hx=u(a().mark((function e(t){var i,r,s=arguments;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=s.length>1&&void 0!==s[1]?s[1]:null,r=s.length>2&&void 0!==s[2]?s[2]:{},i&&(t=dx(t,i,r)),cx[t]=cx[t]||px(t),e.next=6,cx[t];case 6:return e.abrupt("return",e.sent);case 7:case"end":return e.stop()}}),e)}))),hx.apply(this,arguments)}function dx(e,t,i){if(e.startsWith("http"))return e;var r=i.modules||{};return r[e]?r[e]:Gb?i.CDN?(Vb(i.CDN.startsWith("http")),"".concat(i.CDN,"/").concat(t,"@").concat("3.2.6","/dist/libs/").concat(e)):zb?"../src/libs/".concat(e):"modules/".concat(t,"/src/libs/").concat(e):"modules/".concat(t,"/dist/libs/").concat(e)}function px(e){return fx.apply(this,arguments)}function fx(){return(fx=u(a().mark((function e(t){var i,r,s;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.endsWith("wasm")){e.next=7;break}return e.next=3,fetch(t);case 3:return i=e.sent,e.next=6,i.arrayBuffer();case 6:return e.abrupt("return",e.sent);case 7:if(Gb){e.next=20;break}if(e.prev=8,e.t0=ux&&void 0,!e.t0){e.next=14;break}return e.next=13,(void 0)(t);case 13:e.t0=e.sent;case 14:return e.abrupt("return",e.t0);case 17:return e.prev=17,e.t1=e.catch(8),e.abrupt("return",null);case 20:if(!zb){e.next=22;break}return e.abrupt("return",importScripts(t));case 22:return e.next=24,fetch(t);case 24:return r=e.sent,e.next=27,r.text();case 27:return s=e.sent,e.abrupt("return",vx(s,t));case 29:case"end":return e.stop()}}),e,null,[[8,17]])})))).apply(this,arguments)}function vx(e,t){if(Gb){if(zb)return eval.call(jb,e),null;var i=document.createElement("script");i.id=t;try{i.appendChild(document.createTextNode(e))}catch(t){i.text=e}return document.body.appendChild(i),null}}function gx(e,t){return!!ox.isSupported()&&(!!(Gb||null!=t&&t._nodeWorkers)&&(e.worker&&(null==t?void 0:t.worker)))}function mx(e,t,i,r,s){return _x.apply(this,arguments)}function _x(){return _x=u(a().mark((function e(t,i,r,s,n){var o,l,u,c,A,h;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return o=t.id,l=ax(t,r),u=ox.getWorkerFarm(r),c=u.getWorkerPool({name:o,url:l}),r=JSON.parse(JSON.stringify(r)),s=JSON.parse(JSON.stringify(s||{})),e.next=8,c.startJob("process-on-worker",yx.bind(null,n));case 8:return(A=e.sent).postMessage("process",{input:i,options:r,context:s}),e.next=12,A.result;case 12:return h=e.sent,e.next=15,h.result;case 15:return e.abrupt("return",e.sent);case 16:case"end":return e.stop()}}),e)}))),_x.apply(this,arguments)}function yx(e,t,i,r){return bx.apply(this,arguments)}function bx(){return(bx=u(a().mark((function e(t,i,r,s){var n,o,l,u,c;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:e.t0=r,e.next="done"===e.t0?3:"error"===e.t0?5:"process"===e.t0?7:20;break;case 3:return i.done(s),e.abrupt("break",21);case 5:return i.error(new Error(s.error)),e.abrupt("break",21);case 7:return n=s.id,o=s.input,l=s.options,e.prev=8,e.next=11,t(o,l);case 11:u=e.sent,i.postMessage("done",{id:n,result:u}),e.next=19;break;case 15:e.prev=15,e.t1=e.catch(8),c=e.t1 instanceof Error?e.t1.message:"unknown error",i.postMessage("error",{id:n,error:c});case 19:return e.abrupt("break",21);case 20:console.warn("parse-with-worker unknown message ".concat(r));case 21:case"end":return e.stop()}}),e,null,[[8,15]])})))).apply(this,arguments)}function xx(e,t,i){if(e.byteLength<=t+i)return"";for(var r=new DataView(e),s="",n=0;n1&&void 0!==arguments[1]?arguments[1]:5;if("string"==typeof e)return e.slice(0,t);if(ArrayBuffer.isView(e))return xx(e.buffer,e.byteOffset,t);if(e instanceof ArrayBuffer){return xx(e,0,t)}return""}(e),'"'))}}function Bx(e){return e&&"object"===w(e)&&e.isBuffer}function Px(e){if(Bx(e))return Bx(t=e)?new Uint8Array(t.buffer,t.byteOffset,t.length).slice().buffer:t;var t;if(e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e))return 0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);if("string"==typeof e){var i=e;return(new TextEncoder).encode(i).buffer}if(e&&"object"===w(e)&&e._toArrayBuffer)return e._toArrayBuffer();throw new Error("toArrayBuffer")}function Cx(){for(var e=arguments.length,t=new Array(e),i=0;i=0),Ob(t>0),e+(t-1)&~(t-1)}function Fx(e,t,i){var r;if(e instanceof ArrayBuffer)r=new Uint8Array(e);else{var s=e.byteOffset,n=e.byteLength;r=new Uint8Array(e.buffer||e.arrayBuffer,s,n)}return t.set(r,i),i+Ex(r.byteLength,4)}function kx(e){return Ix.apply(this,arguments)}function Ix(){return(Ix=u(a().mark((function e(t){var i,r,s,n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=[],r=!1,s=!1,e.prev=3,o=I(t);case 5:return e.next=7,o.next();case 7:if(!(r=!(l=e.sent).done)){e.next=13;break}u=l.value,i.push(u);case 10:r=!1,e.next=5;break;case 13:e.next=19;break;case 15:e.prev=15,e.t0=e.catch(3),s=!0,n=e.t0;case 19:if(e.prev=19,e.prev=20,!r||null==o.return){e.next=24;break}return e.next=24,o.return();case 24:if(e.prev=24,!s){e.next=27;break}throw n;case 27:return e.finish(24);case 28:return e.finish(19);case 29:return e.abrupt("return",Cx.apply(void 0,i));case 30:case"end":return e.stop()}}),e,null,[[3,15,19,29],[20,,24,28]])})))).apply(this,arguments)}var Dx={};function Sx(e){for(var t in Dx)if(e.startsWith(t)){var i=Dx[t];e=e.replace(t,i)}return e.startsWith("http://")||e.startsWith("https://")||(e="".concat("").concat(e)),e}var Tx=function(e){return"function"==typeof e},Lx=function(e){return null!==e&&"object"===w(e)},Rx=function(e){return Lx(e)&&e.constructor==={}.constructor},Ux=function(e){return e&&"function"==typeof e[Symbol.iterator]},Ox=function(e){return e&&"function"==typeof e[Symbol.asyncIterator]},Nx=function(e){return"undefined"!=typeof Response&&e instanceof Response||e&&e.arrayBuffer&&e.text&&e.json},Qx=function(e){return"undefined"!=typeof Blob&&e instanceof Blob},Vx=function(e){return function(e){return"undefined"!=typeof ReadableStream&&e instanceof ReadableStream||Lx(e)&&Tx(e.tee)&&Tx(e.cancel)&&Tx(e.getReader)}(e)||function(e){return Lx(e)&&Tx(e.read)&&Tx(e.pipe)&&function(e){return"boolean"==typeof e}(e.readable)}(e)},Hx=/^data:([-\w.]+\/[-\w.+]+)(;|,)/,jx=/^([-\w.]+\/[-\w.+]+)/;function Gx(e){var t=jx.exec(e);return t?t[1]:e}function zx(e){var t=Hx.exec(e);return t?t[1]:""}var Wx=/\?.*/;function Kx(e){if(Nx(e)){var t=Jx(e.url||"");return{url:t,type:Gx(e.headers.get("content-type")||"")||zx(t)}}return Qx(e)?{url:Jx(e.name||""),type:e.type||""}:"string"==typeof e?{url:Jx(e),type:zx(e)}:{url:"",type:""}}function Xx(e){return Nx(e)?e.headers["content-length"]||-1:Qx(e)?e.size:"string"==typeof e?e.length:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:-1}function Jx(e){return e.replace(Wx,"")}function Yx(e){return Zx.apply(this,arguments)}function Zx(){return(Zx=u(a().mark((function e(t){var i,r,s,n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!Nx(t)){e.next=2;break}return e.abrupt("return",t);case 2:return i={},(r=Xx(t))>=0&&(i["content-length"]=String(r)),s=Kx(t),n=s.url,(o=s.type)&&(i["content-type"]=o),e.next=9,iw(t);case 9:return(l=e.sent)&&(i["x-first-bytes"]=l),"string"==typeof t&&(t=(new TextEncoder).encode(t)),u=new Response(t,{headers:i}),Object.defineProperty(u,"url",{value:n}),e.abrupt("return",u);case 15:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function qx(e){return $x.apply(this,arguments)}function $x(){return($x=u(a().mark((function e(t){var i;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.ok){e.next=5;break}return e.next=3,ew(t);case 3:throw i=e.sent,new Error(i);case 5:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ew(e){return tw.apply(this,arguments)}function tw(){return(tw=u(a().mark((function e(t){var i,r,s;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i="Failed to fetch resource ".concat(t.url," (").concat(t.status,"): "),e.prev=1,r=t.headers.get("Content-Type"),s=t.statusText,!r.includes("application/json")){e.next=11;break}return e.t0=s,e.t1=" ",e.next=9,t.text();case 9:e.t2=e.sent,s=e.t0+=e.t1.concat.call(e.t1,e.t2);case 11:i=(i+=s).length>60?"".concat(i.slice(0,60),"..."):i,e.next=17;break;case 15:e.prev=15,e.t3=e.catch(1);case 17:return e.abrupt("return",i);case 18:case"end":return e.stop()}}),e,null,[[1,15]])})))).apply(this,arguments)}function iw(e){return rw.apply(this,arguments)}function rw(){return(rw=u(a().mark((function e(t){var i,r,s,n;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=5,"string"!=typeof t){e.next=3;break}return e.abrupt("return","data:,".concat(t.slice(0,i)));case 3:if(!(t instanceof Blob)){e.next=8;break}return r=t.slice(0,5),e.next=7,new Promise((function(e){var t=new FileReader;t.onload=function(t){var i;return e(null==t||null===(i=t.target)||void 0===i?void 0:i.result)},t.readAsDataURL(r)}));case 7:return e.abrupt("return",e.sent);case 8:if(!(t instanceof ArrayBuffer)){e.next=12;break}return s=t.slice(0,i),n=sw(s),e.abrupt("return","data:base64,".concat(n));case 12:return e.abrupt("return",null);case 13:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function sw(e){for(var t="",i=new Uint8Array(e),r=0;r=0)}();function hw(e){try{var t=window[e],i="__storage_test__";return t.setItem(i,i),t.removeItem(i),t}catch(e){return null}}var dw=function(){function e(t,i){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"sessionStorage";B(this,e),this.storage=hw(r),this.id=t,this.config={},Object.assign(this.config,i),this._loadConfiguration()}return C(e,[{key:"getConfiguration",value:function(){return this.config}},{key:"setConfiguration",value:function(e){return this.config={},this.updateConfiguration(e)}},{key:"updateConfiguration",value:function(e){if(Object.assign(this.config,e),this.storage){var t=JSON.stringify(this.config);this.storage.setItem(this.id,t)}return this}},{key:"_loadConfiguration",value:function(){var e={};if(this.storage){var t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}}]),e}();function pw(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:600,s=e.src.replace(/\(/g,"%28").replace(/\)/g,"%29");e.width>r&&(i=Math.min(i,r/e.width));var n=e.width*i,o=e.height*i,a=["font-size:1px;","padding:".concat(Math.floor(o/2),"px ").concat(Math.floor(n/2),"px;"),"line-height:".concat(o,"px;"),"background:url(".concat(s,");"),"background-size:".concat(n,"px ").concat(o,"px;"),"color:transparent;"].join("");return["".concat(t," %c+"),a]}var fw={BLACK:30,RED:31,GREEN:32,YELLOW:33,BLUE:34,MAGENTA:35,CYAN:36,WHITE:37,BRIGHT_BLACK:90,BRIGHT_RED:91,BRIGHT_GREEN:92,BRIGHT_YELLOW:93,BRIGHT_BLUE:94,BRIGHT_MAGENTA:95,BRIGHT_CYAN:96,BRIGHT_WHITE:97};function vw(e){return"string"==typeof e?fw[e.toUpperCase()]||fw.WHITE:e}function gw(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:["constructor"],r=Object.getPrototypeOf(e),s=Object.getOwnPropertyNames(r),n=c(s);try{var o=function(){var r=t.value;"function"==typeof e[r]&&(i.find((function(e){return r===e}))||(e[r]=e[r].bind(e)))};for(n.s();!(t=n.n()).done;)o()}catch(e){n.e(e)}finally{n.f()}}function mw(e,t){if(!e)throw new Error(t||"Assertion failed")}function _w(){var e;if(Aw&&lw.performance)e=lw.performance.now();else if(uw.hrtime){var t=uw.hrtime();e=1e3*t[0]+t[1]/1e6}else e=Date.now();return e}var yw={debug:Aw&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},bw={enabled:!0,level:0};function xw(){}var ww={},Bw={once:!0};function Pw(e){for(var t in e)for(var i in e[t])return i||"untitled";return"empty"}var Cw=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{id:""},i=t.id;B(this,e),this.id=i,this.VERSION=cw,this._startTs=_w(),this._deltaTs=_w(),this.LOG_THROTTLE_TIMEOUT=0,this._storage=new dw("__probe-".concat(this.id,"__"),bw),this.userData={},this.timeStamp("".concat(this.id," started")),gw(this),Object.seal(this)}return C(e,[{key:"level",get:function(){return this.getLevel()},set:function(e){this.setLevel(e)}},{key:"isEnabled",value:function(){return this._storage.config.enabled}},{key:"getLevel",value:function(){return this._storage.config.level}},{key:"getTotal",value:function(){return Number((_w()-this._startTs).toPrecision(10))}},{key:"getDelta",value:function(){return Number((_w()-this._deltaTs).toPrecision(10))}},{key:"priority",get:function(){return this.level},set:function(e){this.level=e}},{key:"getPriority",value:function(){return this.level}},{key:"enable",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this._storage.updateConfiguration({enabled:e}),this}},{key:"setLevel",value:function(e){return this._storage.updateConfiguration({level:e}),this}},{key:"assert",value:function(e,t){mw(e,t)}},{key:"warn",value:function(e){return this._getLogFunction(0,e,yw.warn,arguments,Bw)}},{key:"error",value:function(e){return this._getLogFunction(0,e,yw.error,arguments)}},{key:"deprecated",value:function(e,t){return this.warn("`".concat(e,"` is deprecated and will be removed in a later version. Use `").concat(t,"` instead"))}},{key:"removed",value:function(e,t){return this.error("`".concat(e,"` has been removed. Use `").concat(t,"` instead"))}},{key:"probe",value:function(e,t){return this._getLogFunction(e,t,yw.log,arguments,{time:!0,once:!0})}},{key:"log",value:function(e,t){return this._getLogFunction(e,t,yw.debug,arguments)}},{key:"info",value:function(e,t){return this._getLogFunction(e,t,console.info,arguments)}},{key:"once",value:function(e,t){return this._getLogFunction(e,t,yw.debug||yw.info,arguments,Bw)}},{key:"table",value:function(e,t,i){return t?this._getLogFunction(e,t,console.table||xw,i&&[i],{tag:Pw(t)}):xw}},{key:"image",value:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){var t=e.logLevel,i=e.priority,r=e.image,s=e.message,n=void 0===s?"":s,o=e.scale,a=void 0===o?1:o;return this._shouldLog(t||i)?Aw?function(e){var t=e.image,i=e.message,r=void 0===i?"":i,s=e.scale,n=void 0===s?1:s;if("string"==typeof t){var o=new Image;return o.onload=function(){var e,t=pw(o,r,n);(e=console).log.apply(e,h(t))},o.src=t,xw}var a=t.nodeName||"";if("img"===a.toLowerCase()){var l;return(l=console).log.apply(l,h(pw(t,r,n))),xw}if("canvas"===a.toLowerCase()){var u=new Image;return u.onload=function(){var e;return(e=console).log.apply(e,h(pw(u,r,n)))},u.src=t.toDataURL(),xw}return xw}({image:r,message:n,scale:a}):function(e){var t=e.image,i=(e.message,e.scale),r=void 0===i?1:i,s=null;try{s=module.require("asciify-image")}catch(e){}if(s)return function(){return s(t,{fit:"box",width:"".concat(Math.round(80*r),"%")}).then((function(e){return console.log(e)}))};return xw}({image:r,message:n,scale:a}):xw}))},{key:"settings",value:function(){console.table?console.table(this._storage.config):console.log(this._storage.config)}},{key:"get",value:function(e){return this._storage.config[e]}},{key:"set",value:function(e,t){this._storage.updateConfiguration(o({},e,t))}},{key:"time",value:function(e,t){return this._getLogFunction(e,t,console.time?console.time:console.info)}},{key:"timeEnd",value:function(e,t){return this._getLogFunction(e,t,console.timeEnd?console.timeEnd:console.info)}},{key:"timeStamp",value:function(e,t){return this._getLogFunction(e,t,console.timeStamp||xw)}},{key:"group",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{collapsed:!1},r=i=Ew({logLevel:e,message:t,opts:i}),s=r.collapsed;return i.method=(s?console.groupCollapsed:console.group)||console.info,this._getLogFunction(i)}},{key:"groupCollapsed",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.group(e,t,Object.assign({},i,{collapsed:!0}))}},{key:"groupEnd",value:function(e){return this._getLogFunction(e,"",console.groupEnd||xw)}},{key:"withGroup",value:function(e,t,i){this.group(e,t)();try{i()}finally{this.groupEnd(e)()}}},{key:"trace",value:function(){console.trace&&console.trace()}},{key:"_shouldLog",value:function(e){return this.isEnabled()&&this.getLevel()>=Mw(e)}},{key:"_getLogFunction",value:function(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],s=arguments.length>4?arguments[4]:void 0;if(this._shouldLog(e)){var n;s=Ew({logLevel:e,message:t,args:r,opts:s}),mw(i=i||s.method),s.total=this.getTotal(),s.delta=this.getDelta(),this._deltaTs=_w();var o=s.tag||s.message;if(s.once){if(ww[o])return xw;ww[o]=_w()}return t=Fw(this.id,s.message,s),(n=i).bind.apply(n,[console,t].concat(h(s.args)))}return xw}}]),e}();function Mw(e){if(!e)return 0;var t;switch(w(e)){case"number":t=e;break;case"object":t=e.logLevel||e.priority||0;break;default:return 0}return mw(Number.isFinite(t)&&t>=0),t}function Ew(e){var t=e.logLevel,i=e.message;e.logLevel=Mw(t);for(var r=e.args?Array.from(e.args):[];r.length&&r.shift()!==i;);switch(e.args=r,w(t)){case"string":case"function":void 0!==i&&r.unshift(i),e.message=t;break;case"object":Object.assign(e,t)}"function"==typeof e.message&&(e.message=e.message());var s=w(e.message);return mw("string"===s||"object"===s),Object.assign(e,e.opts)}function Fw(e,t,i){if("string"==typeof t){var r=i.time?function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8,i=Math.max(t-e.length,0);return"".concat(" ".repeat(i)).concat(e)}((s=i.total)<10?"".concat(s.toFixed(2),"ms"):s<100?"".concat(s.toFixed(1),"ms"):s<1e3?"".concat(s.toFixed(0),"ms"):"".concat((s/1e3).toFixed(2),"s")):"";t=function(e,t,i){return Aw||"string"!=typeof e||(t&&(t=vw(t),e="[".concat(t,"m").concat(e,"")),i&&(t=vw(i),e="[".concat(i+10,"m").concat(e,""))),e}(t=i.time?"".concat(e,": ").concat(r," ").concat(t):"".concat(e,": ").concat(t),i.color,i.background)}var s;return t}Cw.VERSION=cw;var kw=new Cw({id:"loaders.gl"}),Iw=function(){function e(){B(this,e)}return C(e,[{key:"log",value:function(){return function(){}}},{key:"info",value:function(){return function(){}}},{key:"warn",value:function(){return function(){}}},{key:"error",value:function(){return function(){}}}]),e}(),Dw={fetch:null,mimeType:void 0,nothrow:!1,log:new(function(){function e(){B(this,e),Xb(this,"console",void 0),this.console=console}return C(e,[{key:"log",value:function(){for(var e,t=arguments.length,i=new Array(t),r=0;r=0)}()}var zw={self:"undefined"!=typeof self&&self,window:"undefined"!=typeof window&&window,global:"undefined"!=typeof global&&global,document:"undefined"!=typeof document&&document,process:"object"===("undefined"==typeof process?"undefined":w(process))&&process},Ww=zw.window||zw.self||zw.global,Kw=zw.process||{},Xw="undefined"!=typeof __VERSION__?__VERSION__:"untranspiled source";function Jw(e){try{var t=window[e],i="__storage_test__";return t.setItem(i,i),t.removeItem(i),t}catch(e){return null}}Gw();var Yw,Zw=function(){function e(t){B(this,e);var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"sessionStorage";Xb(this,"storage",void 0),Xb(this,"id",void 0),Xb(this,"config",{}),this.storage=Jw(r),this.id=t,this.config={},Object.assign(this.config,i),this._loadConfiguration()}return C(e,[{key:"getConfiguration",value:function(){return this.config}},{key:"setConfiguration",value:function(e){return this.config={},this.updateConfiguration(e)}},{key:"updateConfiguration",value:function(e){if(Object.assign(this.config,e),this.storage){var t=JSON.stringify(this.config);this.storage.setItem(this.id,t)}return this}},{key:"_loadConfiguration",value:function(){var e={};if(this.storage){var t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}}]),e}();function qw(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:600,s=e.src.replace(/\(/g,"%28").replace(/\)/g,"%29");e.width>r&&(i=Math.min(i,r/e.width));var n=e.width*i,o=e.height*i,a=["font-size:1px;","padding:".concat(Math.floor(o/2),"px ").concat(Math.floor(n/2),"px;"),"line-height:".concat(o,"px;"),"background:url(".concat(s,");"),"background-size:".concat(n,"px ").concat(o,"px;"),"color:transparent;"].join("");return["".concat(t," %c+"),a]}function $w(e){return"string"==typeof e?Yw[e.toUpperCase()]||Yw.WHITE:e}function eB(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:["constructor"],r=Object.getPrototypeOf(e),s=Object.getOwnPropertyNames(r),n=c(s);try{var o=function(){var r=t.value;"function"==typeof e[r]&&(i.find((function(e){return r===e}))||(e[r]=e[r].bind(e)))};for(n.s();!(t=n.n()).done;)o()}catch(e){n.e(e)}finally{n.f()}}function tB(e,t){if(!e)throw new Error(t||"Assertion failed")}function iB(){var e,t,i;if(Gw&&"performance"in Ww)e=null==Ww||null===(t=Ww.performance)||void 0===t||null===(i=t.now)||void 0===i?void 0:i.call(t);else if("hrtime"in Kw){var r,s=null==Kw||null===(r=Kw.hrtime)||void 0===r?void 0:r.call(Kw);e=1e3*s[0]+s[1]/1e6}else e=Date.now();return e}!function(e){e[e.BLACK=30]="BLACK",e[e.RED=31]="RED",e[e.GREEN=32]="GREEN",e[e.YELLOW=33]="YELLOW",e[e.BLUE=34]="BLUE",e[e.MAGENTA=35]="MAGENTA",e[e.CYAN=36]="CYAN",e[e.WHITE=37]="WHITE",e[e.BRIGHT_BLACK=90]="BRIGHT_BLACK",e[e.BRIGHT_RED=91]="BRIGHT_RED",e[e.BRIGHT_GREEN=92]="BRIGHT_GREEN",e[e.BRIGHT_YELLOW=93]="BRIGHT_YELLOW",e[e.BRIGHT_BLUE=94]="BRIGHT_BLUE",e[e.BRIGHT_MAGENTA=95]="BRIGHT_MAGENTA",e[e.BRIGHT_CYAN=96]="BRIGHT_CYAN",e[e.BRIGHT_WHITE=97]="BRIGHT_WHITE"}(Yw||(Yw={}));var rB={debug:Gw&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},sB={enabled:!0,level:0};function nB(){}var oB={},aB={once:!0},lB=function(){function e(){B(this,e);var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{id:""},i=t.id;Xb(this,"id",void 0),Xb(this,"VERSION",Xw),Xb(this,"_startTs",iB()),Xb(this,"_deltaTs",iB()),Xb(this,"_storage",void 0),Xb(this,"userData",{}),Xb(this,"LOG_THROTTLE_TIMEOUT",0),this.id=i,this._storage=new Zw("__probe-".concat(this.id,"__"),sB),this.userData={},this.timeStamp("".concat(this.id," started")),eB(this),Object.seal(this)}return C(e,[{key:"level",get:function(){return this.getLevel()},set:function(e){this.setLevel(e)}},{key:"isEnabled",value:function(){return this._storage.config.enabled}},{key:"getLevel",value:function(){return this._storage.config.level}},{key:"getTotal",value:function(){return Number((iB()-this._startTs).toPrecision(10))}},{key:"getDelta",value:function(){return Number((iB()-this._deltaTs).toPrecision(10))}},{key:"priority",get:function(){return this.level},set:function(e){this.level=e}},{key:"getPriority",value:function(){return this.level}},{key:"enable",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this._storage.updateConfiguration({enabled:e}),this}},{key:"setLevel",value:function(e){return this._storage.updateConfiguration({level:e}),this}},{key:"get",value:function(e){return this._storage.config[e]}},{key:"set",value:function(e,t){this._storage.updateConfiguration(o({},e,t))}},{key:"settings",value:function(){console.table?console.table(this._storage.config):console.log(this._storage.config)}},{key:"assert",value:function(e,t){tB(e,t)}},{key:"warn",value:function(e){return this._getLogFunction(0,e,rB.warn,arguments,aB)}},{key:"error",value:function(e){return this._getLogFunction(0,e,rB.error,arguments)}},{key:"deprecated",value:function(e,t){return this.warn("`".concat(e,"` is deprecated and will be removed in a later version. Use `").concat(t,"` instead"))}},{key:"removed",value:function(e,t){return this.error("`".concat(e,"` has been removed. Use `").concat(t,"` instead"))}},{key:"probe",value:function(e,t){return this._getLogFunction(e,t,rB.log,arguments,{time:!0,once:!0})}},{key:"log",value:function(e,t){return this._getLogFunction(e,t,rB.debug,arguments)}},{key:"info",value:function(e,t){return this._getLogFunction(e,t,console.info,arguments)}},{key:"once",value:function(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),s=2;s2&&void 0!==arguments[2]?arguments[2]:{collapsed:!1},r=cB({logLevel:e,message:t,opts:i}),s=i.collapsed;return r.method=(s?console.groupCollapsed:console.group)||console.info,this._getLogFunction(r)}},{key:"groupCollapsed",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.group(e,t,Object.assign({},i,{collapsed:!0}))}},{key:"groupEnd",value:function(e){return this._getLogFunction(e,"",console.groupEnd||nB)}},{key:"withGroup",value:function(e,t,i){this.group(e,t)();try{i()}finally{this.groupEnd(e)()}}},{key:"trace",value:function(){console.trace&&console.trace()}},{key:"_shouldLog",value:function(e){return this.isEnabled()&&this.getLevel()>=uB(e)}},{key:"_getLogFunction",value:function(e,t,i,r,s){if(this._shouldLog(e)){var n;s=cB({logLevel:e,message:t,args:r,opts:s}),tB(i=i||s.method),s.total=this.getTotal(),s.delta=this.getDelta(),this._deltaTs=iB();var o=s.tag||s.message;if(s.once){if(oB[o])return nB;oB[o]=iB()}return t=function(e,t,i){if("string"==typeof t){var r=i.time?function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8,i=Math.max(t-e.length,0);return"".concat(" ".repeat(i)).concat(e)}((s=i.total)<10?"".concat(s.toFixed(2),"ms"):s<100?"".concat(s.toFixed(1),"ms"):s<1e3?"".concat(s.toFixed(0),"ms"):"".concat((s/1e3).toFixed(2),"s")):"";t=function(e,t,i){return Gw||"string"!=typeof e||(t&&(t=$w(t),e="[".concat(t,"m").concat(e,"")),i&&(t=$w(i),e="[".concat(i+10,"m").concat(e,""))),e}(t=i.time?"".concat(e,": ").concat(r," ").concat(t):"".concat(e,": ").concat(t),i.color,i.background)}var s;return t}(this.id,s.message,s),(n=i).bind.apply(n,[console,t].concat(h(s.args)))}return nB}}]),e}();function uB(e){if(!e)return 0;var t;switch(w(e)){case"number":t=e;break;case"object":t=e.logLevel||e.priority||0;break;default:return 0}return tB(Number.isFinite(t)&&t>=0),t}function cB(e){var t=e.logLevel,i=e.message;e.logLevel=uB(t);for(var r=e.args?Array.from(e.args):[];r.length&&r.shift()!==i;);switch(w(t)){case"string":case"function":void 0!==i&&r.unshift(i),e.message=t;break;case"object":Object.assign(e,t)}"function"==typeof e.message&&(e.message=e.message());var s=w(e.message);return tB("string"===s||"object"===s),Object.assign(e,{args:r},e.opts)}function AB(e){for(var t in e)for(var i in e[t])return i||"untitled";return"empty"}Xb(lB,"VERSION",Xw);var hB=new lB({id:"loaders.gl"}),dB=/\.([^.]+)$/;function pB(e){return fB.apply(this,arguments)}function fB(){return fB=u(a().mark((function e(t){var i,r,s,o,l=arguments;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=l.length>1&&void 0!==l[1]?l[1]:[],r=l.length>2?l[2]:void 0,s=l.length>3?l[3]:void 0,mB(t)){e.next=5;break}return e.abrupt("return",null);case 5:if(!(o=vB(t,i,n(n({},r),{},{nothrow:!0}),s))){e.next=8;break}return e.abrupt("return",o);case 8:if(!Qx(t)){e.next=13;break}return e.next=11,t.slice(0,10).arrayBuffer();case 11:t=e.sent,o=vB(t,i,r,s);case 13:if(o||null!=r&&r.nothrow){e.next=15;break}throw new Error(_B(t));case 15:return e.abrupt("return",o);case 16:case"end":return e.stop()}}),e)}))),fB.apply(this,arguments)}function vB(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],i=arguments.length>2?arguments[2]:void 0,r=arguments.length>3?arguments[3]:void 0;if(!mB(e))return null;if(t&&!Array.isArray(t))return Hw(t);var s,n=[];(t&&(n=n.concat(t)),null!=i&&i.ignoreRegisteredLoaders)||(s=n).push.apply(s,h(jw()));yB(n);var o=gB(e,n,i,r);if(!(o||null!=i&&i.nothrow))throw new Error(_B(e));return o}function gB(e,t,i,r){var s,n=Kx(e),o=n.url,a=n.type,l=o||(null==r?void 0:r.url),u=null,A="";(null!=i&&i.mimeType&&(u=bB(t,null==i?void 0:i.mimeType),A="match forced by supplied MIME type ".concat(null==i?void 0:i.mimeType)),u=u||function(e,t){var i=t&&dB.exec(t),r=i&&i[1];return r?function(e,t){t=t.toLowerCase();var i,r=c(e);try{for(r.s();!(i=r.n()).done;){var s,n=i.value,o=c(n.extensions);try{for(o.s();!(s=o.n()).done;){if(s.value.toLowerCase()===t)return n}}catch(e){o.e(e)}finally{o.f()}}}catch(e){r.e(e)}finally{r.f()}return null}(e,r):null}(t,l),A=A||(u?"matched url ".concat(l):""),u=u||bB(t,a),A=A||(u?"matched MIME type ".concat(a):""),u=u||function(e,t){if(!t)return null;var i,r=c(e);try{for(r.s();!(i=r.n()).done;){var s=i.value;if("string"==typeof t){if(xB(t,s))return s}else if(ArrayBuffer.isView(t)){if(wB(t.buffer,t.byteOffset,s))return s}else if(t instanceof ArrayBuffer){if(wB(t,0,s))return s}}}catch(e){r.e(e)}finally{r.f()}return null}(t,e),A=A||(u?"matched initial data ".concat(BB(e)):""),u=u||bB(t,null==i?void 0:i.fallbackMimeType),A=A||(u?"matched fallback MIME type ".concat(a):""))&&hB.log(1,"selectLoader selected ".concat(null===(s=u)||void 0===s?void 0:s.name,": ").concat(A,"."));return u}function mB(e){return!(e instanceof Response&&204===e.status)}function _B(e){var t=Kx(e),i=t.url,r=t.type,s="No valid loader found (";s+=i?"".concat(function(e){var t=e&&e.lastIndexOf("/");return t>=0?e.substr(t+1):""}(i),", "):"no url provided, ",s+="MIME type: ".concat(r?'"'.concat(r,'"'):"not provided",", ");var n=e?BB(e):"";return s+=n?' first bytes: "'.concat(n,'"'):"first bytes: not available",s+=")"}function yB(e){var t,i=c(e);try{for(i.s();!(t=i.n()).done;){Hw(t.value)}}catch(e){i.e(e)}finally{i.f()}}function bB(e,t){var i,r=c(e);try{for(r.s();!(i=r.n()).done;){var s=i.value;if(s.mimeTypes&&s.mimeTypes.includes(t))return s;if(t==="application/x.".concat(s.id))return s}}catch(e){r.e(e)}finally{r.f()}return null}function xB(e,t){return t.testText?t.testText(e):(Array.isArray(t.tests)?t.tests:[t.tests]).some((function(t){return e.startsWith(t)}))}function wB(e,t,i){return(Array.isArray(i.tests)?i.tests:[i.tests]).some((function(r){return function(e,t,i,r){if(r instanceof ArrayBuffer)return function(e,t,i){if(i=i||e.byteLength,e.byteLength1&&void 0!==arguments[1]?arguments[1]:5;if("string"==typeof e)return e.slice(0,t);if(ArrayBuffer.isView(e))return PB(e.buffer,e.byteOffset,t);if(e instanceof ArrayBuffer){var i=0;return PB(e,i,t)}return""}function PB(e,t,i){if(e.byteLength1&&void 0!==c[1]?c[1]:{},r=t.chunkSize,s=void 0===r?262144:r,n=0;case 3:if(!(n2&&void 0!==arguments[2]?arguments[2]:null;if(i)return i;var r=n({fetch:Uw(t,e)},e);return Array.isArray(r.loaders)||(r.loaders=null),r}function OB(e,t){if(!t&&e&&!Array.isArray(e))return e;var i;if(e&&(i=Array.isArray(e)?e:[e]),t&&t.loaders){var r=Array.isArray(t.loaders)?t.loaders:[t.loaders];i=i?[].concat(h(i),h(r)):r}return i&&i.length?i:null}function NB(e,t,i,r){return QB.apply(this,arguments)}function QB(){return(QB=u(a().mark((function e(t,i,r,s){var n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return Vb(!s||"object"===w(s)),!i||Array.isArray(i)||Vw(i)||(s=void 0,r=i,i=void 0),e.next=4,t;case 4:return t=e.sent,r=r||{},n=Kx(t),o=n.url,l=OB(i,s),e.next=11,pB(t,l,r);case 11:if(u=e.sent){e.next=14;break}return e.abrupt("return",null);case 14:return r=Rw(r,u,l,o),s=UB({url:o,parse:NB,loaders:l},r,s),e.next=18,VB(u,t,r,s);case 18:return e.abrupt("return",e.sent);case 19:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function VB(e,t,i,r){return HB.apply(this,arguments)}function HB(){return(HB=u(a().mark((function e(t,i,r,s){var n,o,l,u,c,A,h,d;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return lx(t),Nx(i)&&(o=(n=i).ok,l=n.redirected,u=n.status,c=n.statusText,A=n.type,h=n.url,d=Object.fromEntries(n.headers.entries()),s.response={headers:d,ok:o,redirected:l,status:u,statusText:c,type:A,url:h}),e.next=4,LB(i,t,r);case 4:if(i=e.sent,!t.parseTextSync||"string"!=typeof i){e.next=8;break}return r.dataType="text",e.abrupt("return",t.parseTextSync(i,r,s,t));case 8:if(!gx(t,r)){e.next=12;break}return e.next=11,mx(t,i,r,s,NB);case 11:case 15:case 19:return e.abrupt("return",e.sent);case 12:if(!t.parseText||"string"!=typeof i){e.next=16;break}return e.next=15,t.parseText(i,r,s,t);case 16:if(!t.parse){e.next=20;break}return e.next=19,t.parse(i,r,s,t);case 20:throw Vb(!t.parseSync),new Error("".concat(t.id," loader - no parser found and worker is disabled"));case 22:case"end":return e.stop()}}),e)})))).apply(this,arguments)}var jB,GB,zB="https://unpkg.com/@loaders.gl/textures@".concat("3.2.6","/dist/libs/basis_encoder.wasm"),WB="https://unpkg.com/@loaders.gl/textures@".concat("3.2.6","/dist/libs/basis_encoder.js");function KB(e){return XB.apply(this,arguments)}function XB(){return(XB=u(a().mark((function e(t){var i;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(i=t.modules||{}).basis){e.next=3;break}return e.abrupt("return",i.basis);case 3:return jB=jB||JB(t),e.next=6,jB;case 6:return e.abrupt("return",e.sent);case 7:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function JB(e){return YB.apply(this,arguments)}function YB(){return(YB=u(a().mark((function e(t){var i,r,s,n;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=null,r=null,e.t0=Promise,e.next=5,Ax("basis_transcoder.js","textures",t);case 5:return e.t1=e.sent,e.next=8,Ax("basis_transcoder.wasm","textures",t);case 8:return e.t2=e.sent,e.t3=[e.t1,e.t2],e.next=12,e.t0.all.call(e.t0,e.t3);case 12:return s=e.sent,n=A(s,2),i=n[0],r=n[1],i=i||globalThis.BASIS,e.next=19,ZB(i,r);case 19:return e.abrupt("return",e.sent);case 20:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ZB(e,t){var i={};return t&&(i.wasmBinary=t),new Promise((function(t){e(i).then((function(e){var i=e.BasisFile;(0,e.initializeBasis)(),t({BasisFile:i})}))}))}function qB(e){return $B.apply(this,arguments)}function $B(){return($B=u(a().mark((function e(t){var i;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(i=t.modules||{}).basisEncoder){e.next=3;break}return e.abrupt("return",i.basisEncoder);case 3:return GB=GB||eP(t),e.next=6,GB;case 6:return e.abrupt("return",e.sent);case 7:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function eP(e){return tP.apply(this,arguments)}function tP(){return(tP=u(a().mark((function e(t){var i,r,s,n;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=null,r=null,e.t0=Promise,e.next=5,Ax(WB,"textures",t);case 5:return e.t1=e.sent,e.next=8,Ax(zB,"textures",t);case 8:return e.t2=e.sent,e.t3=[e.t1,e.t2],e.next=12,e.t0.all.call(e.t0,e.t3);case 12:return s=e.sent,n=A(s,2),i=n[0],r=n[1],i=i||globalThis.BASIS,e.next=19,iP(i,r);case 19:return e.abrupt("return",e.sent);case 20:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function iP(e,t){var i={};return t&&(i.wasmBinary=t),new Promise((function(t){e(i).then((function(e){var i=e.BasisFile,r=e.KTX2File,s=e.initializeBasis,n=e.BasisEncoder;s(),t({BasisFile:i,KTX2File:r,BasisEncoder:n})}))}))}var rP,sP,nP,oP,aP,lP,uP,cP,AP,hP=33776,dP=33779,pP=35840,fP=35842,vP=36196,gP=37808,mP=["","WEBKIT_","MOZ_"],_P={WEBGL_compressed_texture_s3tc:"dxt",WEBGL_compressed_texture_s3tc_srgb:"dxt-srgb",WEBGL_compressed_texture_etc1:"etc1",WEBGL_compressed_texture_etc:"etc2",WEBGL_compressed_texture_pvrtc:"pvrtc",WEBGL_compressed_texture_atc:"atc",WEBGL_compressed_texture_astc:"astc",EXT_texture_compression_rgtc:"rgtc"},yP=null;function bP(e){if(!yP){e=e||function(){try{return document.createElement("canvas").getContext("webgl")}catch(e){return null}}()||void 0,yP=new Set;var t,i=c(mP);try{for(i.s();!(t=i.n()).done;){var r=t.value;for(var s in _P)if(e&&e.getExtension("".concat(r).concat(s))){var n=_P[s];yP.add(n)}}}catch(e){i.e(e)}finally{i.f()}}return yP}(AP=rP||(rP={}))[AP.NONE=0]="NONE",AP[AP.BASISLZ=1]="BASISLZ",AP[AP.ZSTD=2]="ZSTD",AP[AP.ZLIB=3]="ZLIB",function(e){e[e.BASICFORMAT=0]="BASICFORMAT"}(sP||(sP={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.ETC1S=163]="ETC1S",e[e.UASTC=166]="UASTC"}(nP||(nP={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.SRGB=1]="SRGB"}(oP||(oP={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.LINEAR=1]="LINEAR",e[e.SRGB=2]="SRGB",e[e.ITU=3]="ITU",e[e.NTSC=4]="NTSC",e[e.SLOG=5]="SLOG",e[e.SLOG2=6]="SLOG2"}(aP||(aP={})),function(e){e[e.ALPHA_STRAIGHT=0]="ALPHA_STRAIGHT",e[e.ALPHA_PREMULTIPLIED=1]="ALPHA_PREMULTIPLIED"}(lP||(lP={})),function(e){e[e.RGB=0]="RGB",e[e.RRR=3]="RRR",e[e.GGG=4]="GGG",e[e.AAA=15]="AAA"}(uP||(uP={})),function(e){e[e.RGB=0]="RGB",e[e.RGBA=3]="RGBA",e[e.RRR=4]="RRR",e[e.RRRG=5]="RRRG"}(cP||(cP={}));var xP=[171,75,84,88,32,50,48,187,13,10,26,10];function wP(e){var t=new Uint8Array(e);return!(t.byteLength1&&void 0!==r[1]?r[1]:null)&&YP||(i=null),!i){e.next=13;break}return e.prev=3,e.next=6,createImageBitmap(t,i);case 6:return e.abrupt("return",e.sent);case 9:e.prev=9,e.t0=e.catch(3),console.warn(e.t0),YP=!1;case 13:return e.next=15,createImageBitmap(t);case 15:return e.abrupt("return",e.sent);case 16:case"end":return e.stop()}}),e,null,[[3,9]])}))),eC.apply(this,arguments)}function tC(e){for(var t in e||JP)return!1;return!0}function iC(e){var t=rC(e);return function(e){var t=rC(e);if(!(t.byteLength>=24&&2303741511===t.getUint32(0,false)))return null;return{mimeType:"image/png",width:t.getUint32(16,false),height:t.getUint32(20,false)}}(t)||function(e){var t=rC(e);if(!(t.byteLength>=3&&65496===t.getUint16(0,false)&&255===t.getUint8(2)))return null;var i=function(){for(var e=new Set([65499,65476,65484,65501,65534]),t=65504;t<65520;++t)e.add(t);var i=new Set([65472,65473,65474,65475,65477,65478,65479,65481,65482,65483,65485,65486,65487,65502]);return{tableMarkers:e,sofMarkers:i}}(),r=i.tableMarkers,s=i.sofMarkers,n=2;for(;n+9=10&&1195984440===t.getUint32(0,false)))return null;return{mimeType:"image/gif",width:t.getUint16(6,true),height:t.getUint16(8,true)}}(t)||function(e){var t=rC(e);if(!(t.byteLength>=14&&16973===t.getUint16(0,false)&&t.getUint32(2,true)===t.byteLength))return null;return{mimeType:"image/bmp",width:t.getUint32(18,true),height:t.getUint32(22,true)}}(t)}function rC(e){if(e instanceof DataView)return e;if(ArrayBuffer.isView(e))return new DataView(e.buffer);if(e instanceof ArrayBuffer)return new DataView(e);throw new Error("toDataView")}function sC(e,t){return nC.apply(this,arguments)}function nC(){return nC=u(a().mark((function e(t,i){var r,s,n;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=iC(t)||{},s=r.mimeType,Ob(n=globalThis._parseImageNode),e.next=5,n(t,s);case 5:return e.abrupt("return",e.sent);case 6:case"end":return e.stop()}}),e)}))),nC.apply(this,arguments)}function oC(){return(oC=u(a().mark((function e(t,i,r){var s,n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:s=(i=i||{}).image||{},n=s.type||"auto",o=(r||{}).url,l=aC(n),e.t0=l,e.next="imagebitmap"===e.t0?8:"image"===e.t0?12:"data"===e.t0?16:20;break;case 8:return e.next=10,ZP(t,i,o);case 10:return u=e.sent,e.abrupt("break",21);case 12:return e.next=14,zP(t,i,o);case 14:return u=e.sent,e.abrupt("break",21);case 16:return e.next=18,sC(t);case 18:return u=e.sent,e.abrupt("break",21);case 20:Ob(!1);case 21:return"data"===n&&(u=NP(u)),e.abrupt("return",u);case 23:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function aC(e){switch(e){case"auto":case"data":return function(){if(LP)return"imagebitmap";if(TP)return"image";if(UP)return"data";throw new Error("Install '@loaders.gl/polyfills' to parse images under Node.js")}();default:return function(e){switch(e){case"auto":return LP||TP||UP;case"imagebitmap":return LP;case"image":return TP;case"data":return UP;default:throw new Error("@loaders.gl/images: image ".concat(e," not supported in this environment"))}}(e),e}}var lC={id:"image",module:"images",name:"Images",version:"3.2.6",mimeTypes:["image/png","image/jpeg","image/gif","image/webp","image/bmp","image/vnd.microsoft.icon","image/svg+xml"],extensions:["png","jpg","jpeg","gif","webp","bmp","ico","svg"],parse:function(e,t,i){return oC.apply(this,arguments)},tests:[function(e){return Boolean(iC(new DataView(e)))}],options:{image:{type:"auto",decode:!0}}},uC=["image/png","image/jpeg","image/gif"],cC={};function AC(e){return void 0===cC[e]&&(cC[e]=function(e){switch(e){case"image/webp":return function(){if(!Nb)return!1;try{return 0===document.createElement("canvas").toDataURL("image/webp").indexOf("data:image/webp")}catch(e){return!1}}();case"image/svg":return Nb;default:if(!Nb){var t=globalThis._parseImageNode;return Boolean(t)&&uC.includes(e)}return!0}}(e)),cC[e]}function hC(e,t){if(!e)throw new Error(t||"assert failed: gltf")}function dC(e,t){if(e.startsWith("data:")||e.startsWith("http:")||e.startsWith("https:"))return e;var i=t.baseUri||t.uri;if(!i)throw new Error("'baseUri' must be provided to resolve relative url ".concat(e));return i.substr(0,i.lastIndexOf("/")+1)+e}function pC(e,t,i){var r=e.bufferViews[i];hC(r);var s=t[r.buffer];hC(s);var n=(r.byteOffset||0)+s.byteOffset;return new Uint8Array(s.arrayBuffer,n,r.byteLength)}var fC=["SCALAR","VEC2","VEC3","VEC4"],vC=[[Int8Array,5120],[Uint8Array,5121],[Int16Array,5122],[Uint16Array,5123],[Uint32Array,5125],[Float32Array,5126],[Float64Array,5130]],gC=new Map(vC),mC={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},_C={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},yC={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array};function bC(e){return fC[e-1]||fC[0]}function xC(e){var t=gC.get(e.constructor);if(!t)throw new Error("Illegal typed array");return t}function wC(e,t){var i=yC[e.componentType],r=mC[e.type],s=_C[e.componentType],n=e.count*r,o=e.count*r*s;return hC(o>=0&&o<=t.byteLength),{ArrayType:i,length:n,byteLength:o}}var BC,PC={asset:{version:"2.0",generator:"loaders.gl"},buffers:[]},CC=function(){function e(t){B(this,e),Xb(this,"gltf",void 0),Xb(this,"sourceBuffers",void 0),Xb(this,"byteLength",void 0),this.gltf=t||{json:n({},PC),buffers:[]},this.sourceBuffers=[],this.byteLength=0,this.gltf.buffers&&this.gltf.buffers[0]&&(this.byteLength=this.gltf.buffers[0].byteLength,this.sourceBuffers=[this.gltf.buffers[0]])}return C(e,[{key:"json",get:function(){return this.gltf.json}},{key:"getApplicationData",value:function(e){return this.json[e]}},{key:"getExtraData",value:function(e){return(this.json.extras||{})[e]}},{key:"getExtension",value:function(e){var t=this.getUsedExtensions().find((function(t){return t===e})),i=this.json.extensions||{};return t?i[e]||!0:null}},{key:"getRequiredExtension",value:function(e){var t=this.getRequiredExtensions().find((function(t){return t===e}));return t?this.getExtension(e):null}},{key:"getRequiredExtensions",value:function(){return this.json.extensionsRequired||[]}},{key:"getUsedExtensions",value:function(){return this.json.extensionsUsed||[]}},{key:"getObjectExtension",value:function(e,t){return(e.extensions||{})[t]}},{key:"getScene",value:function(e){return this.getObject("scenes",e)}},{key:"getNode",value:function(e){return this.getObject("nodes",e)}},{key:"getSkin",value:function(e){return this.getObject("skins",e)}},{key:"getMesh",value:function(e){return this.getObject("meshes",e)}},{key:"getMaterial",value:function(e){return this.getObject("materials",e)}},{key:"getAccessor",value:function(e){return this.getObject("accessors",e)}},{key:"getTexture",value:function(e){return this.getObject("textures",e)}},{key:"getSampler",value:function(e){return this.getObject("samplers",e)}},{key:"getImage",value:function(e){return this.getObject("images",e)}},{key:"getBufferView",value:function(e){return this.getObject("bufferViews",e)}},{key:"getBuffer",value:function(e){return this.getObject("buffers",e)}},{key:"getObject",value:function(e,t){if("object"===w(t))return t;var i=this.json[e]&&this.json[e][t];if(!i)throw new Error("glTF file error: Could not find ".concat(e,"[").concat(t,"]"));return i}},{key:"getTypedArrayForBufferView",value:function(e){var t=(e=this.getBufferView(e)).buffer,i=this.gltf.buffers[t];hC(i);var r=(e.byteOffset||0)+i.byteOffset;return new Uint8Array(i.arrayBuffer,r,e.byteLength)}},{key:"getTypedArrayForAccessor",value:function(e){e=this.getAccessor(e);var t=this.getBufferView(e.bufferView),i=this.getBuffer(t.buffer).data,r=wC(e,t),s=r.ArrayType,n=r.length;return new s(i,t.byteOffset+e.byteOffset,n)}},{key:"getTypedArrayForImageData",value:function(e){e=this.getAccessor(e);var t=this.getBufferView(e.bufferView),i=this.getBuffer(t.buffer).data,r=t.byteOffset||0;return new Uint8Array(i,r,t.byteLength)}},{key:"addApplicationData",value:function(e,t){return this.json[e]=t,this}},{key:"addExtraData",value:function(e,t){return this.json.extras=this.json.extras||{},this.json.extras[e]=t,this}},{key:"addObjectExtension",value:function(e,t,i){return e.extensions=e.extensions||{},e.extensions[t]=i,this.registerUsedExtension(t),this}},{key:"setObjectExtension",value:function(e,t,i){(e.extensions||{})[t]=i}},{key:"removeObjectExtension",value:function(e,t){var i=e.extensions||{},r=i[t];return delete i[t],r}},{key:"addExtension",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return hC(t),this.json.extensions=this.json.extensions||{},this.json.extensions[e]=t,this.registerUsedExtension(e),t}},{key:"addRequiredExtension",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return hC(t),this.addExtension(e,t),this.registerRequiredExtension(e),t}},{key:"registerUsedExtension",value:function(e){this.json.extensionsUsed=this.json.extensionsUsed||[],this.json.extensionsUsed.find((function(t){return t===e}))||this.json.extensionsUsed.push(e)}},{key:"registerRequiredExtension",value:function(e){this.registerUsedExtension(e),this.json.extensionsRequired=this.json.extensionsRequired||[],this.json.extensionsRequired.find((function(t){return t===e}))||this.json.extensionsRequired.push(e)}},{key:"removeExtension",value:function(e){this.json.extensionsRequired&&this._removeStringFromArray(this.json.extensionsRequired,e),this.json.extensionsUsed&&this._removeStringFromArray(this.json.extensionsUsed,e),this.json.extensions&&delete this.json.extensions[e]}},{key:"setDefaultScene",value:function(e){this.json.scene=e}},{key:"addScene",value:function(e){var t=e.nodeIndices;return this.json.scenes=this.json.scenes||[],this.json.scenes.push({nodes:t}),this.json.scenes.length-1}},{key:"addNode",value:function(e){var t=e.meshIndex,i=e.matrix;this.json.nodes=this.json.nodes||[];var r={mesh:t};return i&&(r.matrix=i),this.json.nodes.push(r),this.json.nodes.length-1}},{key:"addMesh",value:function(e){var t=e.attributes,i=e.indices,r=e.material,s=e.mode,n=void 0===s?4:s,o={primitives:[{attributes:this._addAttributes(t),mode:n}]};if(i){var a=this._addIndices(i);o.primitives[0].indices=a}return Number.isFinite(r)&&(o.primitives[0].material=r),this.json.meshes=this.json.meshes||[],this.json.meshes.push(o),this.json.meshes.length-1}},{key:"addPointCloud",value:function(e){var t={primitives:[{attributes:this._addAttributes(e),mode:0}]};return this.json.meshes=this.json.meshes||[],this.json.meshes.push(t),this.json.meshes.length-1}},{key:"addImage",value:function(e,t){var i=iC(e),r=t||(null==i?void 0:i.mimeType),s={bufferView:this.addBufferView(e),mimeType:r};return this.json.images=this.json.images||[],this.json.images.push(s),this.json.images.length-1}},{key:"addBufferView",value:function(e){var t=e.byteLength;hC(Number.isFinite(t)),this.sourceBuffers=this.sourceBuffers||[],this.sourceBuffers.push(e);var i={buffer:0,byteOffset:this.byteLength,byteLength:t};return this.byteLength+=Ex(t,4),this.json.bufferViews=this.json.bufferViews||[],this.json.bufferViews.push(i),this.json.bufferViews.length-1}},{key:"addAccessor",value:function(e,t){var i={bufferView:e,type:bC(t.size),componentType:t.componentType,count:t.count,max:t.max,min:t.min};return this.json.accessors=this.json.accessors||[],this.json.accessors.push(i),this.json.accessors.length-1}},{key:"addBinaryBuffer",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{size:3},i=this.addBufferView(e),r={min:t.min,max:t.max};r.min&&r.max||(r=this._getAccessorMinMax(e,t.size));var s={size:t.size,componentType:xC(e),count:Math.round(e.length/t.size),min:r.min,max:r.max};return this.addAccessor(i,Object.assign(s,t))}},{key:"addTexture",value:function(e){var t={source:e.imageIndex};return this.json.textures=this.json.textures||[],this.json.textures.push(t),this.json.textures.length-1}},{key:"addMaterial",value:function(e){return this.json.materials=this.json.materials||[],this.json.materials.push(e),this.json.materials.length-1}},{key:"createBinaryChunk",value:function(){var e,t;this.gltf.buffers=[];var i,r=this.byteLength,s=new ArrayBuffer(r),n=new Uint8Array(s),o=0,a=c(this.sourceBuffers||[]);try{for(a.s();!(i=a.n()).done;){o=Fx(i.value,n,o)}}catch(e){a.e(e)}finally{a.f()}null!==(e=this.json)&&void 0!==e&&null!==(t=e.buffers)&&void 0!==t&&t[0]?this.json.buffers[0].byteLength=r:this.json.buffers=[{byteLength:r}],this.gltf.binary=s,this.sourceBuffers=[s]}},{key:"_removeStringFromArray",value:function(e,t){for(var i=!0;i;){var r=e.indexOf(t);r>-1?e.splice(r,1):i=!1}}},{key:"_addAttributes",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};for(var i in e){var r=e[i],s=this._getGltfAttributeName(i),n=this.addBinaryBuffer(r.value,r);t[s]=n}return t}},{key:"_addIndices",value:function(e){return this.addBinaryBuffer(e,{size:1})}},{key:"_getGltfAttributeName",value:function(e){switch(e.toLowerCase()){case"position":case"positions":case"vertices":return"POSITION";case"normal":case"normals":return"NORMAL";case"color":case"colors":return"COLOR_0";case"texcoord":case"texcoords":return"TEXCOORD_0";default:return e}}},{key:"_getAccessorMinMax",value:function(e,t){var i={min:null,max:null};if(e.length5&&void 0!==u[5]?u[5]:"NONE",e.next=3,LC();case 3:QC(l=e.sent,l.exports[DC[n]],t,i,r,s,l.exports[IC[o||"NONE"]]);case 5:case"end":return e.stop()}}),e)}))),TC.apply(this,arguments)}function LC(){return RC.apply(this,arguments)}function RC(){return(RC=u(a().mark((function e(){return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return BC||(BC=UC()),e.abrupt("return",BC);case 2:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function UC(){return OC.apply(this,arguments)}function OC(){return(OC=u(a().mark((function e(){var t,i;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=MC,WebAssembly.validate(FC)&&(t=EC,console.log("Warning: meshopt_decoder is using experimental SIMD support")),e.next=4,WebAssembly.instantiate(NC(t),{});case 4:return i=e.sent,e.next=7,i.instance.exports.__wasm_call_ctors();case 7:return e.abrupt("return",i.instance);case 8:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function NC(e){for(var t=new Uint8Array(e.length),i=0;i96?r-71:r>64?r-65:r>47?r+4:r>46?63:62}for(var s=0,n=0;ns?c:s,n=A>n?A:n,o=h>o?h:o}return[[t,i,r],[s,n,o]]}var JC=function(){function e(t,i){B(this,e),Xb(this,"fields",void 0),Xb(this,"metadata",void 0),function(e,t){if(!e)throw new Error(t||"loader assertion failed.")}(Array.isArray(t)),function(e){var t,i={},r=c(e);try{for(r.s();!(t=r.n()).done;){var s=t.value;i[s.name]&&console.warn("Schema: duplicated field name",s.name,s),i[s.name]=!0}}catch(e){r.e(e)}finally{r.f()}}(t),this.fields=t,this.metadata=i||new Map}return C(e,[{key:"compareTo",value:function(e){if(this.metadata!==e.metadata)return!1;if(this.fields.length!==e.fields.length)return!1;for(var t=0;t2&&void 0!==arguments[2]&&arguments[2],s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:new Map;B(this,e),Xb(this,"name",void 0),Xb(this,"type",void 0),Xb(this,"nullable",void 0),Xb(this,"metadata",void 0),this.name=t,this.type=i,this.nullable=r,this.metadata=s}return C(e,[{key:"typeId",get:function(){return this.type&&this.type.typeId}},{key:"clone",value:function(){return new e(this.name,this.type,this.nullable,this.metadata)}},{key:"compareTo",value:function(e){return this.name===e.name&&this.type===e.type&&this.nullable===e.nullable&&this.metadata===e.metadata}},{key:"toString",value:function(){return"".concat(this.type).concat(this.nullable?", nullable":"").concat(this.metadata?", metadata: ".concat(this.metadata):"")}}]),e}();!function(e){e[e.NONE=0]="NONE",e[e.Null=1]="Null",e[e.Int=2]="Int",e[e.Float=3]="Float",e[e.Binary=4]="Binary",e[e.Utf8=5]="Utf8",e[e.Bool=6]="Bool",e[e.Decimal=7]="Decimal",e[e.Date=8]="Date",e[e.Time=9]="Time",e[e.Timestamp=10]="Timestamp",e[e.Interval=11]="Interval",e[e.List=12]="List",e[e.Struct=13]="Struct",e[e.Union=14]="Union",e[e.FixedSizeBinary=15]="FixedSizeBinary",e[e.FixedSizeList=16]="FixedSizeList",e[e.Map=17]="Map",e[e.Dictionary=-1]="Dictionary",e[e.Int8=-2]="Int8",e[e.Int16=-3]="Int16",e[e.Int32=-4]="Int32",e[e.Int64=-5]="Int64",e[e.Uint8=-6]="Uint8",e[e.Uint16=-7]="Uint16",e[e.Uint32=-8]="Uint32",e[e.Uint64=-9]="Uint64",e[e.Float16=-10]="Float16",e[e.Float32=-11]="Float32",e[e.Float64=-12]="Float64",e[e.DateDay=-13]="DateDay",e[e.DateMillisecond=-14]="DateMillisecond",e[e.TimestampSecond=-15]="TimestampSecond",e[e.TimestampMillisecond=-16]="TimestampMillisecond",e[e.TimestampMicrosecond=-17]="TimestampMicrosecond",e[e.TimestampNanosecond=-18]="TimestampNanosecond",e[e.TimeSecond=-19]="TimeSecond",e[e.TimeMillisecond=-20]="TimeMillisecond",e[e.TimeMicrosecond=-21]="TimeMicrosecond",e[e.TimeNanosecond=-22]="TimeNanosecond",e[e.DenseUnion=-23]="DenseUnion",e[e.SparseUnion=-24]="SparseUnion",e[e.IntervalDayTime=-25]="IntervalDayTime",e[e.IntervalYearMonth=-26]="IntervalYearMonth"}(ZC||(ZC={}));var $C=function(){function e(){B(this,e)}return C(e,[{key:"typeId",get:function(){return ZC.NONE}},{key:"compareTo",value:function(e){return this===e}}],[{key:"isNull",value:function(e){return e&&e.typeId===ZC.Null}},{key:"isInt",value:function(e){return e&&e.typeId===ZC.Int}},{key:"isFloat",value:function(e){return e&&e.typeId===ZC.Float}},{key:"isBinary",value:function(e){return e&&e.typeId===ZC.Binary}},{key:"isUtf8",value:function(e){return e&&e.typeId===ZC.Utf8}},{key:"isBool",value:function(e){return e&&e.typeId===ZC.Bool}},{key:"isDecimal",value:function(e){return e&&e.typeId===ZC.Decimal}},{key:"isDate",value:function(e){return e&&e.typeId===ZC.Date}},{key:"isTime",value:function(e){return e&&e.typeId===ZC.Time}},{key:"isTimestamp",value:function(e){return e&&e.typeId===ZC.Timestamp}},{key:"isInterval",value:function(e){return e&&e.typeId===ZC.Interval}},{key:"isList",value:function(e){return e&&e.typeId===ZC.List}},{key:"isStruct",value:function(e){return e&&e.typeId===ZC.Struct}},{key:"isUnion",value:function(e){return e&&e.typeId===ZC.Union}},{key:"isFixedSizeBinary",value:function(e){return e&&e.typeId===ZC.FixedSizeBinary}},{key:"isFixedSizeList",value:function(e){return e&&e.typeId===ZC.FixedSizeList}},{key:"isMap",value:function(e){return e&&e.typeId===ZC.Map}},{key:"isDictionary",value:function(e){return e&&e.typeId===ZC.Dictionary}}]),e}(),eM=function(e,t){g(r,$C);var i=_(r);function r(e,t){var s;return B(this,r),Xb(b(s=i.call(this)),"isSigned",void 0),Xb(b(s),"bitWidth",void 0),s.isSigned=e,s.bitWidth=t,s}return C(r,[{key:"typeId",get:function(){return ZC.Int}},{key:t,get:function(){return"Int"}},{key:"toString",value:function(){return"".concat(this.isSigned?"I":"Ui","nt").concat(this.bitWidth)}}]),r}(0,Symbol.toStringTag),tM=function(e){g(i,eM);var t=_(i);function i(){return B(this,i),t.call(this,!0,8)}return C(i)}(),iM=function(e){g(i,eM);var t=_(i);function i(){return B(this,i),t.call(this,!0,16)}return C(i)}(),rM=function(e){g(i,eM);var t=_(i);function i(){return B(this,i),t.call(this,!0,32)}return C(i)}(),sM=function(e){g(i,eM);var t=_(i);function i(){return B(this,i),t.call(this,!1,8)}return C(i)}(),nM=function(e){g(i,eM);var t=_(i);function i(){return B(this,i),t.call(this,!1,16)}return C(i)}(),oM=function(e){g(i,eM);var t=_(i);function i(){return B(this,i),t.call(this,!1,32)}return C(i)}(),aM=32,lM=64,uM=function(e,t){g(r,$C);var i=_(r);function r(e){var t;return B(this,r),Xb(b(t=i.call(this)),"precision",void 0),t.precision=e,t}return C(r,[{key:"typeId",get:function(){return ZC.Float}},{key:t,get:function(){return"Float"}},{key:"toString",value:function(){return"Float".concat(this.precision)}}]),r}(0,Symbol.toStringTag),cM=function(e){g(i,uM);var t=_(i);function i(){return B(this,i),t.call(this,aM)}return C(i)}(),AM=function(e){g(i,uM);var t=_(i);function i(){return B(this,i),t.call(this,lM)}return C(i)}(),hM=function(e,t){g(r,$C);var i=_(r);function r(e,t){var s;return B(this,r),Xb(b(s=i.call(this)),"listSize",void 0),Xb(b(s),"children",void 0),s.listSize=e,s.children=[t],s}return C(r,[{key:"typeId",get:function(){return ZC.FixedSizeList}},{key:"valueType",get:function(){return this.children[0].type}},{key:"valueField",get:function(){return this.children[0]}},{key:t,get:function(){return"FixedSizeList"}},{key:"toString",value:function(){return"FixedSizeList[".concat(this.listSize,"]<").concat(this.valueType,">")}}]),r}(0,Symbol.toStringTag);function dM(e,t,i){var r=function(e){switch(e.constructor){case Int8Array:return new tM;case Uint8Array:return new sM;case Int16Array:return new iM;case Uint16Array:return new nM;case Int32Array:return new rM;case Uint32Array:return new oM;case Float32Array:return new cM;case Float64Array:return new AM;default:throw new Error("array type not supported")}}(t.value),s=i||function(e){var t=new Map;"byteOffset"in e&&t.set("byteOffset",e.byteOffset.toString(10));"byteStride"in e&&t.set("byteStride",e.byteStride.toString(10));"normalized"in e&&t.set("normalized",e.normalized.toString());return t}(t);return new qC(e,new hM(t.size,new qC("value",r)),!1,s)}function pM(e,t,i){var r=vM(t.metadata),s=[],n=function(e){var t={};for(var i in e){var r=e[i];t[r.name||"undefined"]=r}return t}(t.attributes);for(var o in e){var a=fM(o,e[o],n[o]);s.push(a)}if(i){var l=fM("indices",i);s.push(l)}return new JC(s,r)}function fM(e,t,i){return dM(e,t,i?vM(i.metadata):void 0)}function vM(e){var t=new Map;for(var i in e)t.set("".concat(i,".string"),JSON.stringify(e[i]));return t}var gM={POSITION:"POSITION",NORMAL:"NORMAL",COLOR:"COLOR_0",TEX_COORD:"TEXCOORD_0"},mM={1:Int8Array,2:Uint8Array,3:Int16Array,4:Uint16Array,5:Int32Array,6:Uint32Array,9:Float32Array},_M=function(){function e(t){B(this,e),Xb(this,"draco",void 0),Xb(this,"decoder",void 0),Xb(this,"metadataQuerier",void 0),this.draco=t,this.decoder=new this.draco.Decoder,this.metadataQuerier=new this.draco.MetadataQuerier}return C(e,[{key:"destroy",value:function(){this.draco.destroy(this.decoder),this.draco.destroy(this.metadataQuerier)}},{key:"parseSync",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=new this.draco.DecoderBuffer;i.Init(new Int8Array(e),e.byteLength),this._disableAttributeTransforms(t);var r=this.decoder.GetEncodedGeometryType(i),s=r===this.draco.TRIANGULAR_MESH?new this.draco.Mesh:new this.draco.PointCloud;try{var o;switch(r){case this.draco.TRIANGULAR_MESH:o=this.decoder.DecodeBufferToMesh(i,s);break;case this.draco.POINT_CLOUD:o=this.decoder.DecodeBufferToPointCloud(i,s);break;default:throw new Error("DRACO: Unknown geometry type.")}if(!o.ok()||!s.ptr){var a="DRACO decompression failed: ".concat(o.error_msg());throw new Error(a)}var l=this._getDracoLoaderData(s,r,t),u=this._getMeshData(s,l,t),c=XC(u.attributes),A=pM(u.attributes,l,u.indices),h=n(n({loader:"draco",loaderData:l,header:{vertexCount:s.num_points(),boundingBox:c}},u),{},{schema:A});return h}finally{this.draco.destroy(i),s&&this.draco.destroy(s)}}},{key:"_getDracoLoaderData",value:function(e,t,i){var r=this._getTopLevelMetadata(e),s=this._getDracoAttributes(e,i);return{geometry_type:t,num_attributes:e.num_attributes(),num_points:e.num_points(),num_faces:e instanceof this.draco.Mesh?e.num_faces():0,metadata:r,attributes:s}}},{key:"_getDracoAttributes",value:function(e,t){for(var i={},r=0;r2&&void 0!==arguments[2]&&arguments[2];if(!e)return null;if(Array.isArray(e))return new t(e);if(i&&!(e instanceof t))return new t(e);return e}(t,Float32Array)),r=t.length/i);return{buffer:t,size:i,count:r}}(e),i=t.buffer,r=t.size;return{value:i,size:r,byteOffset:0,count:t.count,type:bC(r),componentType:xC(i)}}function SM(){return(SM=u(a().mark((function e(t,i,r){var s,n,o,l,u,A;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(null!=i&&null!==(s=i.gltf)&&void 0!==s&&s.decompressMeshes){e.next=2;break}return e.abrupt("return");case 2:n=new CC(t),o=[],l=c(OM(n));try{for(l.s();!(u=l.n()).done;)A=u.value,n.getObjectExtension(A,"KHR_draco_mesh_compression")&&o.push(TM(n,A,i,r))}catch(e){l.e(e)}finally{l.f()}return e.next=8,Promise.all(o);case 8:n.removeExtension("KHR_draco_mesh_compression");case 9:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function TM(e,t,i,r){return LM.apply(this,arguments)}function LM(){return LM=u(a().mark((function e(t,i,r,s){var o,l,u,c,h,d,p,f,v,g,m,_,y,b;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(o=t.getObjectExtension(i,"KHR_draco_mesh_compression")){e.next=3;break}return e.abrupt("return");case 3:return l=t.getTypedArrayForBufferView(o.bufferView),u=Mx(l.buffer,l.byteOffset),c=s.parse,delete(h=n({},r))["3d-tiles"],e.next=10,c(u,FM,h,s);case 10:for(d=e.sent,p=IM(d.attributes),f=0,v=Object.entries(p);f2&&void 0!==arguments[2]?arguments[2]:4,s=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0;if(!s.DracoWriter)throw new Error("options.gltf.DracoWriter not provided");var a=s.DracoWriter.encodeSync({attributes:e}),l=null==n||null===(i=n.parseSync)||void 0===i?void 0:i.call(n,{attributes:e}),u=s._addFauxAttributes(l.attributes),c=s.addBufferView(a),A={primitives:[{attributes:u,mode:r,extensions:o({},"KHR_draco_mesh_compression",{bufferView:c,attributes:u})}]};return A}function UM(e){if(!e.attributes&&Object.keys(e.attributes).length>0)throw new Error("glTF: Empty primitive detected: Draco decompression failure?")}function OM(e){var t,i,s,n,o,l;return a().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:t=c(e.json.meshes||[]),r.prev=1,t.s();case 3:if((i=t.n()).done){r.next=24;break}s=i.value,n=c(s.primitives),r.prev=6,n.s();case 8:if((o=n.n()).done){r.next=14;break}return l=o.value,r.next=12,l;case 12:r.next=8;break;case 14:r.next=19;break;case 16:r.prev=16,r.t0=r.catch(6),n.e(r.t0);case 19:return r.prev=19,n.f(),r.finish(19);case 22:r.next=3;break;case 24:r.next=29;break;case 26:r.prev=26,r.t1=r.catch(1),t.e(r.t1);case 29:return r.prev=29,t.f(),r.finish(29);case 32:case"end":return r.stop()}}),r,null,[[1,26,29,32],[6,16,19,22]])}function NM(){return(NM=u(a().mark((function e(t){var i,r,s,n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=new CC(t),r=i.json,(s=i.getExtension("KHR_lights_punctual"))&&(i.json.lights=s.lights,i.removeExtension("KHR_lights_punctual")),n=c(r.nodes||[]);try{for(n.s();!(o=n.n()).done;)l=o.value,(u=i.getObjectExtension(l,"KHR_lights_punctual"))&&(l.light=u.light),i.removeObjectExtension(l,"KHR_lights_punctual")}catch(e){n.e(e)}finally{n.f()}case 6:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function QM(){return(QM=u(a().mark((function e(t){var i,r,s,n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=new CC(t),(r=i.json).lights&&(hC(!(s=i.addExtension("KHR_lights_punctual")).lights),s.lights=r.lights,delete r.lights),i.json.lights){n=c(i.json.lights);try{for(n.s();!(o=n.n()).done;)l=o.value,u=l.node,i.addObjectExtension(u,"KHR_lights_punctual",l)}catch(e){n.e(e)}finally{n.f()}delete i.json.lights}case 4:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function VM(){return(VM=u(a().mark((function e(t){var i,r,s,n,o;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=new CC(t),r=i.json,i.removeExtension("KHR_materials_unlit"),s=c(r.materials||[]);try{for(s.s();!(n=s.n()).done;)o=n.value,o.extensions&&o.extensions.KHR_materials_unlit&&(o.unlit=!0),i.removeObjectExtension(o,"KHR_materials_unlit")}catch(e){s.e(e)}finally{s.f()}case 5:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function HM(){return(HM=u(a().mark((function e(t){var i,r,s,n,o,l,u,A;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=new CC(t),r=i.json,s=i.getExtension("KHR_techniques_webgl")){n=GM(s,i),o=c(r.materials||[]);try{for(o.s();!(l=o.n()).done;)u=l.value,(A=i.getObjectExtension(u,"KHR_techniques_webgl"))&&(u.technique=Object.assign({},A,n[A.technique]),u.technique.values=zM(u.technique,i)),i.removeObjectExtension(u,"KHR_techniques_webgl")}catch(e){o.e(e)}finally{o.f()}i.removeExtension("KHR_techniques_webgl")}case 4:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function jM(){return(jM=u(a().mark((function e(t,i){return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function GM(e,t){var i=e.programs,r=void 0===i?[]:i,s=e.shaders,n=void 0===s?[]:s,o=e.techniques,a=void 0===o?[]:o,l=new TextDecoder;return n.forEach((function(e){if(!Number.isFinite(e.bufferView))throw new Error("KHR_techniques_webgl: no shader code");e.code=l.decode(t.getTypedArrayForBufferView(e.bufferView))})),r.forEach((function(e){e.fragmentShader=n[e.fragmentShader],e.vertexShader=n[e.vertexShader]})),a.forEach((function(e){e.program=r[e.program]})),a}function zM(e,t){var i=Object.assign({},e.values);return Object.keys(e.uniforms||{}).forEach((function(t){e.uniforms[t].value&&!(t in i)&&(i[t]=e.uniforms[t].value)})),Object.keys(i).forEach((function(e){"object"===w(i[e])&&void 0!==i[e].index&&(i[e].texture=t.getTexture(i[e].index))})),i}var WM=[GC,zC,WC,Object.freeze({__proto__:null,name:"KHR_draco_mesh_compression",preprocess:function(e,t,i){var r,s=new CC(e),n=c(OM(s));try{for(n.s();!(r=n.n()).done;){var o=r.value;s.getObjectExtension(o,"KHR_draco_mesh_compression")}}catch(e){n.e(e)}finally{n.f()}},decode:function(e,t,i){return SM.apply(this,arguments)},encode:function(e){var t,i=new CC(e),r=c(i.json.meshes||[]);try{for(r.s();!(t=r.n()).done;){var s=t.value;RM(s),i.addRequiredExtension("KHR_draco_mesh_compression")}}catch(e){r.e(e)}finally{r.f()}}}),Object.freeze({__proto__:null,name:"KHR_lights_punctual",decode:function(e){return NM.apply(this,arguments)},encode:function(e){return QM.apply(this,arguments)}}),Object.freeze({__proto__:null,name:"KHR_materials_unlit",decode:function(e){return VM.apply(this,arguments)},encode:function(e){var t=new CC(e),i=t.json;if(t.materials){var r,s=c(i.materials||[]);try{for(s.s();!(r=s.n()).done;){var n=r.value;n.unlit&&(delete n.unlit,t.addObjectExtension(n,"KHR_materials_unlit",{}),t.addExtension("KHR_materials_unlit"))}}catch(e){s.e(e)}finally{s.f()}}}}),Object.freeze({__proto__:null,name:"KHR_techniques_webgl",decode:function(e){return HM.apply(this,arguments)},encode:function(e,t){return jM.apply(this,arguments)}})];function KM(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0,s=WM.filter((function(e){return YM(e.name,i)})),n=c(s);try{for(n.s();!(t=n.n()).done;){var o,a=t.value;null===(o=a.preprocess)||void 0===o||o.call(a,e,i,r)}}catch(e){n.e(e)}finally{n.f()}}function XM(e){return JM.apply(this,arguments)}function JM(){return JM=u(a().mark((function e(t){var i,r,s,n,o,l,u,A=arguments;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=A.length>1&&void 0!==A[1]?A[1]:{},r=A.length>2?A[2]:void 0,s=WM.filter((function(e){return YM(e.name,i)})),n=c(s),e.prev=4,n.s();case 6:if((o=n.n()).done){e.next=12;break}return l=o.value,e.next=10,null===(u=l.decode)||void 0===u?void 0:u.call(l,t,i,r);case 10:e.next=6;break;case 12:e.next=17;break;case 14:e.prev=14,e.t0=e.catch(4),n.e(e.t0);case 17:return e.prev=17,n.f(),e.finish(17);case 20:case"end":return e.stop()}}),e,null,[[4,14,17,20]])}))),JM.apply(this,arguments)}function YM(e,t){var i,r=(null==t||null===(i=t.gltf)||void 0===i?void 0:i.excludeExtensions)||{};return!(e in r&&!r[e])}var ZM={accessors:"accessor",animations:"animation",buffers:"buffer",bufferViews:"bufferView",images:"image",materials:"material",meshes:"mesh",nodes:"node",samplers:"sampler",scenes:"scene",skins:"skin",textures:"texture"},qM={accessor:"accessors",animations:"animation",buffer:"buffers",bufferView:"bufferViews",image:"images",material:"materials",mesh:"meshes",node:"nodes",sampler:"samplers",scene:"scenes",skin:"skins",texture:"textures"},$M=function(){function e(){B(this,e),Xb(this,"idToIndexMap",{animations:{},accessors:{},buffers:{},bufferViews:{},images:{},materials:{},meshes:{},nodes:{},samplers:{},scenes:{},skins:{},textures:{}}),Xb(this,"json",void 0)}return C(e,[{key:"normalize",value:function(e,t){this.json=e.json;var i=e.json;switch(i.asset&&i.asset.version){case"2.0":return;case void 0:case"1.0":break;default:return void console.warn("glTF: Unknown version ".concat(i.asset.version))}if(!t.normalize)throw new Error("glTF v1 is not supported.");console.warn("Converting glTF v1 to glTF v2 format. This is experimental and may fail."),this._addAsset(i),this._convertTopLevelObjectsToArrays(i),function(e){var t,i=new CC(e),r=i.json,s=c(r.images||[]);try{for(s.s();!(t=s.n()).done;){var n=t.value,o=i.getObjectExtension(n,"KHR_binary_glTF");o&&Object.assign(n,o),i.removeObjectExtension(n,"KHR_binary_glTF")}}catch(e){s.e(e)}finally{s.f()}r.buffers&&r.buffers[0]&&delete r.buffers[0].uri,i.removeExtension("KHR_binary_glTF")}(e),this._convertObjectIdsToArrayIndices(i),this._updateObjects(i),this._updateMaterial(i)}},{key:"_addAsset",value:function(e){e.asset=e.asset||{},e.asset.version="2.0",e.asset.generator=e.asset.generator||"Normalized to glTF 2.0 by loaders.gl"}},{key:"_convertTopLevelObjectsToArrays",value:function(e){for(var t in ZM)this._convertTopLevelObjectToArray(e,t)}},{key:"_convertTopLevelObjectToArray",value:function(e,t){var i=e[t];if(i&&!Array.isArray(i))for(var r in e[t]=[],i){var s=i[r];s.id=s.id||r;var n=e[t].length;e[t].push(s),this.idToIndexMap[t][r]=n}}},{key:"_convertObjectIdsToArrayIndices",value:function(e){for(var t in ZM)this._convertIdsToIndices(e,t);"scene"in e&&(e.scene=this._convertIdToIndex(e.scene,"scene"));var i,r=c(e.textures);try{for(r.s();!(i=r.n()).done;){var s=i.value;this._convertTextureIds(s)}}catch(e){r.e(e)}finally{r.f()}var n,o=c(e.meshes);try{for(o.s();!(n=o.n()).done;){var a=n.value;this._convertMeshIds(a)}}catch(e){o.e(e)}finally{o.f()}var l,u=c(e.nodes);try{for(u.s();!(l=u.n()).done;){var A=l.value;this._convertNodeIds(A)}}catch(e){u.e(e)}finally{u.f()}var h,d=c(e.scenes);try{for(d.s();!(h=d.n()).done;){var p=h.value;this._convertSceneIds(p)}}catch(e){d.e(e)}finally{d.f()}}},{key:"_convertTextureIds",value:function(e){e.source&&(e.source=this._convertIdToIndex(e.source,"image"))}},{key:"_convertMeshIds",value:function(e){var t,i=c(e.primitives);try{for(i.s();!(t=i.n()).done;){var r=t.value,s=r.attributes,n=r.indices,o=r.material;for(var a in s)s[a]=this._convertIdToIndex(s[a],"accessor");n&&(r.indices=this._convertIdToIndex(n,"accessor")),o&&(r.material=this._convertIdToIndex(o,"material"))}}catch(e){i.e(e)}finally{i.f()}}},{key:"_convertNodeIds",value:function(e){var t=this;e.children&&(e.children=e.children.map((function(e){return t._convertIdToIndex(e,"node")}))),e.meshes&&(e.meshes=e.meshes.map((function(e){return t._convertIdToIndex(e,"mesh")})))}},{key:"_convertSceneIds",value:function(e){var t=this;e.nodes&&(e.nodes=e.nodes.map((function(e){return t._convertIdToIndex(e,"node")})))}},{key:"_convertIdsToIndices",value:function(e,t){e[t]||(console.warn("gltf v1: json doesn't contain attribute ".concat(t)),e[t]=[]);var i,r=c(e[t]);try{for(r.s();!(i=r.n()).done;){var s=i.value;for(var n in s){var o=s[n],a=this._convertIdToIndex(o,n);s[n]=a}}}catch(e){r.e(e)}finally{r.f()}}},{key:"_convertIdToIndex",value:function(e,t){var i=qM[t];if(i in this.idToIndexMap){var r=this.idToIndexMap[i][e];if(!Number.isFinite(r))throw new Error("gltf v1: failed to resolve ".concat(t," with id ").concat(e));return r}return e}},{key:"_updateObjects",value:function(e){var t,i=c(this.json.buffers);try{for(i.s();!(t=i.n()).done;){delete t.value.type}}catch(e){i.e(e)}finally{i.f()}}},{key:"_updateMaterial",value:function(e){var t,i=c(e.materials);try{var r=function(){var i=t.value;i.pbrMetallicRoughness={baseColorFactor:[1,1,1,1],metallicFactor:1,roughnessFactor:1};var r=(null===(s=i.values)||void 0===s?void 0:s.tex)||(null===(n=i.values)||void 0===n?void 0:n.texture2d_0),o=e.textures.findIndex((function(e){return e.id===r}));-1!==o&&(i.pbrMetallicRoughness.baseColorTexture={index:o})};for(i.s();!(t=i.n()).done;){var s,n;r()}}catch(e){i.e(e)}finally{i.f()}}}]),e}();function eE(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return(new $M).normalize(e,t)}var tE={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},iE={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},rE=10240,sE=10241,nE=10242,oE=10243,aE=10497,lE=9986,uE={magFilter:rE,minFilter:sE,wrapS:nE,wrapT:oE},cE=(o(e={},rE,9729),o(e,sE,lE),o(e,nE,aE),o(e,oE,aE),e);var AE=function(){function e(){B(this,e),Xb(this,"baseUri",""),Xb(this,"json",{}),Xb(this,"buffers",[]),Xb(this,"images",[])}return C(e,[{key:"postProcess",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=e.json,r=e.buffers,s=void 0===r?[]:r,n=e.images,o=void 0===n?[]:n,a=e.baseUri,l=void 0===a?"":a;return hC(i),this.baseUri=l,this.json=i,this.buffers=s,this.images=o,this._resolveTree(this.json,t),this.json}},{key:"_resolveTree",value:function(e){var t=this;e.bufferViews&&(e.bufferViews=e.bufferViews.map((function(e,i){return t._resolveBufferView(e,i)}))),e.images&&(e.images=e.images.map((function(e,i){return t._resolveImage(e,i)}))),e.samplers&&(e.samplers=e.samplers.map((function(e,i){return t._resolveSampler(e,i)}))),e.textures&&(e.textures=e.textures.map((function(e,i){return t._resolveTexture(e,i)}))),e.accessors&&(e.accessors=e.accessors.map((function(e,i){return t._resolveAccessor(e,i)}))),e.materials&&(e.materials=e.materials.map((function(e,i){return t._resolveMaterial(e,i)}))),e.meshes&&(e.meshes=e.meshes.map((function(e,i){return t._resolveMesh(e,i)}))),e.nodes&&(e.nodes=e.nodes.map((function(e,i){return t._resolveNode(e,i)}))),e.skins&&(e.skins=e.skins.map((function(e,i){return t._resolveSkin(e,i)}))),e.scenes&&(e.scenes=e.scenes.map((function(e,i){return t._resolveScene(e,i)}))),void 0!==e.scene&&(e.scene=e.scenes[this.json.scene])}},{key:"getScene",value:function(e){return this._get("scenes",e)}},{key:"getNode",value:function(e){return this._get("nodes",e)}},{key:"getSkin",value:function(e){return this._get("skins",e)}},{key:"getMesh",value:function(e){return this._get("meshes",e)}},{key:"getMaterial",value:function(e){return this._get("materials",e)}},{key:"getAccessor",value:function(e){return this._get("accessors",e)}},{key:"getCamera",value:function(e){return null}},{key:"getTexture",value:function(e){return this._get("textures",e)}},{key:"getSampler",value:function(e){return this._get("samplers",e)}},{key:"getImage",value:function(e){return this._get("images",e)}},{key:"getBufferView",value:function(e){return this._get("bufferViews",e)}},{key:"getBuffer",value:function(e){return this._get("buffers",e)}},{key:"_get",value:function(e,t){if("object"===w(t))return t;var i=this.json[e]&&this.json[e][t];return i||console.warn("glTF file error: Could not find ".concat(e,"[").concat(t,"]")),i}},{key:"_resolveScene",value:function(e,t){var i=this;return e.id=e.id||"scene-".concat(t),e.nodes=(e.nodes||[]).map((function(e){return i.getNode(e)})),e}},{key:"_resolveNode",value:function(e,t){var i=this;return e.id=e.id||"node-".concat(t),e.children&&(e.children=e.children.map((function(e){return i.getNode(e)}))),void 0!==e.mesh?e.mesh=this.getMesh(e.mesh):void 0!==e.meshes&&e.meshes.length&&(e.mesh=e.meshes.reduce((function(e,t){var r=i.getMesh(t);return e.id=r.id,e.primitives=e.primitives.concat(r.primitives),e}),{primitives:[]})),void 0!==e.camera&&(e.camera=this.getCamera(e.camera)),void 0!==e.skin&&(e.skin=this.getSkin(e.skin)),e}},{key:"_resolveSkin",value:function(e,t){return e.id=e.id||"skin-".concat(t),e.inverseBindMatrices=this.getAccessor(e.inverseBindMatrices),e}},{key:"_resolveMesh",value:function(e,t){var i=this;return e.id=e.id||"mesh-".concat(t),e.primitives&&(e.primitives=e.primitives.map((function(e){var t=(e=n({},e)).attributes;for(var r in e.attributes={},t)e.attributes[r]=i.getAccessor(t[r]);return void 0!==e.indices&&(e.indices=i.getAccessor(e.indices)),void 0!==e.material&&(e.material=i.getMaterial(e.material)),e}))),e}},{key:"_resolveMaterial",value:function(e,t){if(e.id=e.id||"material-".concat(t),e.normalTexture&&(e.normalTexture=n({},e.normalTexture),e.normalTexture.texture=this.getTexture(e.normalTexture.index)),e.occlusionTexture&&(e.occlustionTexture=n({},e.occlustionTexture),e.occlusionTexture.texture=this.getTexture(e.occlusionTexture.index)),e.emissiveTexture&&(e.emmisiveTexture=n({},e.emmisiveTexture),e.emissiveTexture.texture=this.getTexture(e.emissiveTexture.index)),e.emissiveFactor||(e.emissiveFactor=e.emmisiveTexture?[1,1,1]:[0,0,0]),e.pbrMetallicRoughness){e.pbrMetallicRoughness=n({},e.pbrMetallicRoughness);var i=e.pbrMetallicRoughness;i.baseColorTexture&&(i.baseColorTexture=n({},i.baseColorTexture),i.baseColorTexture.texture=this.getTexture(i.baseColorTexture.index)),i.metallicRoughnessTexture&&(i.metallicRoughnessTexture=n({},i.metallicRoughnessTexture),i.metallicRoughnessTexture.texture=this.getTexture(i.metallicRoughnessTexture.index))}return e}},{key:"_resolveAccessor",value:function(e,t){var i,r;if(e.id=e.id||"accessor-".concat(t),void 0!==e.bufferView&&(e.bufferView=this.getBufferView(e.bufferView)),e.bytesPerComponent=(i=e.componentType,iE[i]),e.components=(r=e.type,tE[r]),e.bytesPerElement=e.bytesPerComponent*e.components,e.bufferView){var s=e.bufferView.buffer,n=wC(e,e.bufferView),o=n.ArrayType,a=n.byteLength,l=(e.bufferView.byteOffset||0)+(e.byteOffset||0)+s.byteOffset,u=s.arrayBuffer.slice(l,l+a);e.bufferView.byteStride&&(u=this._getValueFromInterleavedBuffer(s,l,e.bufferView.byteStride,e.bytesPerElement,e.count)),e.value=new o(u)}return e}},{key:"_getValueFromInterleavedBuffer",value:function(e,t,i,r,s){for(var n=new Uint8Array(s*r),o=0;o1&&void 0!==arguments[1]?arguments[1]:0;return"".concat(String.fromCharCode(e.getUint8(t+0))).concat(String.fromCharCode(e.getUint8(t+1))).concat(String.fromCharCode(e.getUint8(t+2))).concat(String.fromCharCode(e.getUint8(t+3)))}function fE(e,t,i){Ob(e.header.byteLength>20);var r=t.getUint32(i+0,dE),s=t.getUint32(i+4,dE);return i+=8,Ob(0===s),gE(e,t,i,r),i+=r,i+=mE(e,t,i,e.header.byteLength)}function vE(e,t,i,r){return Ob(e.header.byteLength>20),function(e,t,i,r){for(;i+8<=e.header.byteLength;){var s=t.getUint32(i+0,dE),n=t.getUint32(i+4,dE);switch(i+=8,n){case 1313821514:gE(e,t,i,s);break;case 5130562:mE(e,t,i,s);break;case 0:r.strict||gE(e,t,i,s);break;case 1:r.strict||mE(e,t,i,s)}i+=Ex(s,4)}}(e,t,i,r),i+e.header.byteLength}function gE(e,t,i,r){var s=new Uint8Array(t.buffer,i,r),n=new TextDecoder("utf8").decode(s);return e.json=JSON.parse(n),Ex(r,4)}function mE(e,t,i,r){return e.header.hasBinChunk=!0,e.binChunks.push({byteOffset:i,byteLength:r,arrayBuffer:t.buffer}),Ex(r,4)}function _E(e,t){return yE.apply(this,arguments)}function yE(){return yE=u(a().mark((function e(t,i){var r,s,n,o,l,u,c,A,h,d,p=arguments;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=p.length>2&&void 0!==p[2]?p[2]:0,s=p.length>3?p[3]:void 0,n=p.length>4?p[4]:void 0,bE(t,i,r,s),eE(t,{normalize:null==s||null===(o=s.gltf)||void 0===o?void 0:o.normalize}),KM(t,s,n),A=[],null==s||null===(l=s.gltf)||void 0===l||!l.loadBuffers||!t.json.buffers){e.next=10;break}return e.next=10,xE(t,s,n);case 10:return null!=s&&null!==(u=s.gltf)&&void 0!==u&&u.loadImages&&(h=BE(t,s,n),A.push(h)),d=XM(t,s,n),A.push(d),e.next=15,Promise.all(A);case 15:return e.abrupt("return",null!=s&&null!==(c=s.gltf)&&void 0!==c&&c.postProcess?hE(t,s):t);case 16:case"end":return e.stop()}}),e)}))),yE.apply(this,arguments)}function bE(e,t,i,r){(r.uri&&(e.baseUri=r.uri),t instanceof ArrayBuffer&&!function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=new DataView(e),s=i.magic,n=void 0===s?1735152710:s,o=r.getUint32(t,!1);return o===n||1735152710===o}(t,i,r))&&(t=(new TextDecoder).decode(t));if("string"==typeof t)e.json=wx(t);else if(t instanceof ArrayBuffer){var s={};i=function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,r=new DataView(t),s=pE(r,i+0),n=r.getUint32(i+4,dE),o=r.getUint32(i+8,dE);switch(Object.assign(e,{header:{byteOffset:i,byteLength:o,hasBinChunk:!1},type:s,version:n,json:{},binChunks:[]}),i+=12,e.version){case 1:return fE(e,r,i);case 2:return vE(e,r,i,{});default:throw new Error("Invalid GLB version ".concat(e.version,". Only supports v1 and v2."))}}(s,t,i,r.glb),hC("glTF"===s.type,"Invalid GLB magic string ".concat(s.type)),e._glb=s,e.json=s.json}else hC(!1,"GLTF: must be ArrayBuffer or string");var n=e.json.buffers||[];if(e.buffers=new Array(n.length).fill(null),e._glb&&e._glb.header.hasBinChunk){var o=e._glb.binChunks;e.buffers[0]={arrayBuffer:o[0].arrayBuffer,byteOffset:o[0].byteOffset,byteLength:o[0].byteLength}}var a=e.json.images||[];e.images=new Array(a.length).fill({})}function xE(e,t,i){return wE.apply(this,arguments)}function wE(){return(wE=u(a().mark((function e(t,i,r){var s,n,o,l,u,c,A,h;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:s=t.json.buffers||[],n=0;case 2:if(!(n1&&void 0!==u[1]?u[1]:{},r=u.length>2?u[2]:void 0,(i=n(n({},FE.options),i)).gltf=n(n({},FE.options.gltf),i.gltf),s=i.byteOffset,o=void 0===s?0:s,l={},e.next=8,_E(l,t,o,i,r);case 8:return e.abrupt("return",e.sent);case 9:case"end":return e.stop()}}),e)}))),kE.apply(this,arguments)}var IE=function(){function e(t){B(this,e)}return C(e,[{key:"load",value:function(e,t,i,r,s,n,o){!function(e,t,i,r,s,n,o){var a=e.viewer.scene.canvas.spinner;a.processes++,"glb"===t.split(".").pop()?e.dataSource.getGLB(t,(function(o){r.basePath=DE(t),SE(e,t,o,i,r,s,n),a.processes--}),(function(e){a.processes--,o(e)})):e.dataSource.getGLTF(t,(function(o){r.basePath=DE(t),SE(e,t,o,i,r,s,n),a.processes--}),(function(e){a.processes--,o(e)}))}(e,t,i,r=r||{},s,(function(){we.scheduleTask((function(){s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1)})),n&&n()}),(function(t){e.error(t),o&&o(t),s.fire("error",t)}))}},{key:"parse",value:function(e,t,i,r,s,n,o){SE(e,"",t,i,r=r||{},s,(function(){s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1),n&&n()}))}}]),e}();function DE(e){var t=e.lastIndexOf("/");return 0!==t?e.substring(0,t+1):""}function SE(e,t,i,r,s,n,o){var a=e.viewer.scene.canvas.spinner;a.processes++,NB(i,FE,{baseUri:s.basePath}).then((function(i){var l={src:t,entityId:s.entityId,metaModelJSON:r,autoMetaModel:s.autoMetaModel,metaObjects:[],loadBuffer:s.loadBuffer,basePath:s.basePath,handlenode:s.handlenode,backfaces:!!s.backfaces,gltfData:i,scene:n.scene,plugin:e,sceneModel:n,numObjects:0,nodes:[],nextId:0,log:function(t){e.log(t)}};!function(e){var t=e.gltfData.textures;if(t)for(var i=0,r=t.length;i0)for(var o=0;o0&&(e.sceneModel.createEntity({id:l,meshIds:n,isObject:!0}),e.autoMetaModel&&e.metaObjects.push({id:l,type:"Default",name:l,parent:e.sceneModel.id})),n=s.pop())}))}(r,0,null)}(l),n.finalize(),s.autoMetaModel&&e.viewer.metaScene.createMetaModel(n.id,{metaObjects:l.metaObjects}),a.processes--,o()}))}function TE(e,t){if(t.source&&t.source.image){var i="texture-".concat(e.nextId++),r=1005;switch(t.sampler.minFilter){case 9728:r=1003;break;case 9729:r=1006;break;case 9984:r=1004;break;case 9985:r=1007;break;case 9986:r=1005;break;case 9987:r=1008}var s=1006;switch(t.sampler.magFilter){case 9728:s=1003;break;case 9729:s=1006}var n=1e3;switch(t.sampler.wrapS){case 33071:n=1001;break;case 33648:n=1002;break;case 10497:n=1e3}var o=1e3;switch(t.sampler.wrapT){case 33071:o=1001;break;case 33648:o=1002;break;case 10497:o=1e3}var a=1e3;switch(t.sampler.wrapR){case 33071:a=1001;break;case 33648:a=1002;break;case 10497:a=1e3}e.sceneModel.createTexture({id:i,image:t.source.image,flipY:!!t.flipY,minFilter:r,magFilter:s,wrapS:n,wrapT:o,wrapR:a,encoding:3001}),t._textureId=i}}function LE(e,t){var i={};switch(t.normalTexture&&(i.normalTextureId=t.normalTexture.texture._textureId),t.occlusionTexture&&(i.occlusionTextureId=t.occlusionTexture.texture._textureId),t.emissiveTexture&&(i.emissiveTextureId=t.emissiveTexture.texture._textureId),t.alphaMode){case"OPAQUE":break;case"MASK":var r=t.alphaCutoff;i.alphaCutoff=void 0!==r?r:.5}var s=t.pbrMetallicRoughness;if(t.pbrMetallicRoughness){var n=t.pbrMetallicRoughness,o=n.baseColorTexture||n.colorTexture;o&&(o.texture?i.colorTextureId=o.texture._textureId:i.colorTextureId=e.gltfData.textures[o.index]._textureId),s.metallicRoughnessTexture&&(i.metallicRoughnessTextureId=s.metallicRoughnessTexture.texture._textureId)}var a=t.extensions;if(a){var l=a.KHR_materials_pbrSpecularGlossiness;if(l){l.specularTexture;var u=l.specularColorTexture;null!=u&&(i.colorTextureId=e.gltfData.textures[u.index]._textureId)}}return void 0!==i.normalTextureId||void 0!==i.occlusionTextureId||void 0!==i.emissiveTextureId||void 0!==i.colorTextureId||void 0!==i.metallicRoughnessTextureId?(i.id="textureSet-".concat(e.nextId++,";"),e.sceneModel.createTextureSet(i),i.id):null}function RE(e,t){var i=t.extensions,r={color:new Float32Array([1,1,1,1]),opacity:1,metallic:0,roughness:1,doubleSided:!0};if(i){var s=i.KHR_materials_pbrSpecularGlossiness;if(s){var n=s.diffuseFactor;null!=n&&r.color.set(n)}var o=i.KHR_materials_common;if(o){var a=o.technique,l=o.values||{},u="BLINN"===a,c="PHONG"===a,A="LAMBERT"===a,h=l.diffuse;h&&(u||c||A)&&(he.isString(h)||r.color.set(h));var d=l.transparency;null!=d&&(r.opacity=d);var p=l.transparent;null!=p&&(r.opacity=p)}}var f=t.pbrMetallicRoughness;if(f){var v=f.baseColorFactor;v&&(r.color[0]=v[0],r.color[1]=v[1],r.color[2]=v[2],r.opacity=v[3]);var g=f.metallicFactor;null!=g&&(r.metallic=g);var m=f.roughnessFactor;null!=m&&(r.roughness=m)}return r.doubleSided=!1!==t.doubleSided,r}var UE={DEFAULT:{}},OE=function(e){g(i,Ue);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),(r=t.call(this,"GLTFLoader",e,s))._sceneModelLoader=new IE(b(r),s),r.dataSource=s.dataSource,r.objectDefaults=s.objectDefaults,r}return C(i,[{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new Ad}},{key:"objectDefaults",get:function(){return this._objectDefaults},set:function(e){this._objectDefaults=e||UE}},{key:"load",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.id&&this.viewer.scene.components[t.id]&&(this.error("Component with this ID already exists in viewer: "+t.id+" - will autogenerate this ID"),delete t.id);var i=new Qh(this.viewer.scene,he.apply(t,{isModel:!0,dtxEnabled:t.dtxEnabled})),r=i.id;if(!t.src&&!t.gltf)return this.error("load() param expected: src or gltf"),i;if(t.metaModelSrc||t.metaModelJSON){var s=function(s){e.viewer.metaScene.createMetaModel(r,s,{}),e.viewer.scene.canvas.spinner.processes--,t.src?e._sceneModelLoader.load(e,t.src,s,t,i):e._sceneModelLoader.parse(e,t.gltf,s,t,i)};if(t.metaModelSrc){var n=t.metaModelSrc;this.viewer.scene.canvas.spinner.processes++,this._dataSource.getMetaModel(n,(function(t){e.viewer.scene.canvas.spinner.processes--,s(t)}),(function(t){e.error("load(): Failed to load model metadata for model '".concat(r," from '").concat(n,"' - ").concat(t)),e.viewer.scene.canvas.spinner.processes--}))}else t.metaModelJSON&&s(t.metaModelJSON)}else t.src?this._sceneModelLoader.load(this,t.src,null,t,i):this._sceneModelLoader.parse(this,t.gltf,null,t,i);return i.once("destroyed",(function(){e.viewer.metaScene.destroyMetaModel(r)})),i}},{key:"destroy",value:function(){f(x(i.prototype),"destroy",this).call(this)}}]),i}();function NE(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r="lightgrey",s=i.hoverColor||"rgba(0,0,0,0.4)",n=i.textColor||"black",o=500,a=o+o/3,l=a/24,u=[{boundary:[6,6,6,6],color:i.frontColor||i.color||"#55FF55"},{boundary:[18,6,6,6],color:i.backColor||i.color||"#55FF55"},{boundary:[12,6,6,6],color:i.rightColor||i.color||"#FF5555"},{boundary:[0,6,6,6],color:i.leftColor||i.color||"#FF5555"},{boundary:[6,0,6,6],color:i.topColor||i.color||"#7777FF"},{boundary:[6,12,6,6],color:i.bottomColor||i.color||"#7777FF"}],c=[{label:"NavCube.front",boundaries:[[7,7,4,4]],dir:[0,1,0],up:[0,0,1]},{label:"NavCube.back",boundaries:[[19,7,4,4]],dir:[0,-1,0],up:[0,0,1]},{label:"NavCube.right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,0,1]},{label:"NavCube.left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,0,1]},{label:"NavCube.top",boundaries:[[7,1,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"NavCube.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]}];i.frontColor||i.color,i.backColor||i.color,i.rightColor||i.color,i.leftColor||i.color,i.topColor||i.color,i.bottomColor||i.color;for(var A=[{yUp:"",label:"NavCube.front",boundaries:[[7,7,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"NavCube.back",boundaries:[[19,7,4,4]],dir:[0,0,1],up:[0,1,0]},{label:"NavCube.right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,1,0]},{label:"NavCube.left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,1,0]},{label:"NavCube.top",boundaries:[[7,1,4,4]],dir:[0,-1,0],up:[0,0,-1]},{label:"NavCube.bottom",boundaries:[[7,13,4,4]],dir:[0,1,0],up:[0,0,1]},{boundaries:[[7,5,4,2]],dir:[0,-.7071,-.7071],up:[0,.7071,-.7071]},{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,-.7071,.7071],up:[0,.7071,.7071]},{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:[.5,.7071,-.5],up:[-.5,.7071,.5]},{boundaries:[[23,11,1,1],[6,17,1,1],[0,11,1,1]],dir:[.5,.7071,.5],up:[-.5,.7071,-.5]},{boundaries:[[5,5,2,2]],dir:[.5,-.7071,-.5],up:[.5,.7071,-.5]},{boundaries:[[11,17,1,1],[17,11,2,1]],dir:[-.5,.7071,.5],up:[.5,.7071,-.5]},{boundaries:[[17,6,2,1],[11,0,1,1]],dir:[-.5,-.7071,.5],up:[-.5,.7071,.5]},{boundaries:[[11,11,2,2]],dir:[-.5,.7071,-.5],up:[.5,.7071,.5]},{boundaries:[[0,6,1,1],[6,0,1,1],[23,6,1,1]],dir:[.5,-.7071,.5],up:[.5,.7071,.5]},{boundaries:[[11,5,2,2]],dir:[-.5,-.7071,-.5],up:[-.5,.7071,-.5]}],h=0,d=c.length;h=A[0]*l&&t<=(A[0]+A[2])*l&&i>=A[1]*l&&i<=(A[1]+A[3])*l)return r}return-1},this.setAreaHighlighted=function(e,t){var i=v[e];if(!i)throw"Area not found: "+e;i.highlighted=!!t,y()},this.getAreaDir=function(e){var t=v[e];if(!t)throw"Unknown area: "+e;return t.dir},this.getAreaUp=function(e){var t=v[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)}}var QE=re.vec3(),VE=re.vec3();re.mat4();var HE=function(e){g(i,Ue);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};B(this,i),r=t.call(this,"NavCube",e,s),e.navCube=b(r);var n=!0;try{r._navCubeScene=new hr(e,{canvasId:s.canvasId,canvasElement:s.canvasElement,transparent:!0}),r._navCubeCanvas=r._navCubeScene.canvas.canvas,r._navCubeScene.input.keyboardEnabled=!1}catch(e){return r.error(e),y(r)}var o=r._navCubeScene;o.clearLights(),new Ti(o,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new Ti(o,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new Ti(o,{dir:[.8,-.6,-.8],color:[1,1,1],intensity:1,space:"view"}),r._navCubeCamera=o.camera,r._navCubeCamera.ortho.scale=7,r._navCubeCamera.ortho.near=.1,r._navCubeCamera.ortho.far=2e3,o.edgeMaterial.edgeColor=[.2,.2,.2],o.edgeMaterial.edgeAlpha=.6,r._zUp=Boolean(e.camera.zUp);var a=b(r);r.setIsProjectNorth(s.isProjectNorth),r.setProjectNorthOffsetAngle(s.projectNorthOffsetAngle);var l,u=(l=re.mat4(),function(e,t,i){return re.identityMat4(l),re.rotationMat4v(e*a._projectNorthOffsetAngle*re.DEGTORAD,[0,1,0],l),re.transformVec3(l,t,i)});r._synchCamera=function(){var t=re.rotationMat4c(-90*re.DEGTORAD,1,0,0),i=re.vec3(),r=re.vec3(),s=re.vec3();return function(){var n=e.camera.eye,o=e.camera.look,l=e.camera.up;i=re.mulVec3Scalar(re.normalizeVec3(re.subVec3(n,o,i)),5),a._isProjectNorth&&a._projectNorthOffsetAngle&&(i=u(-1,i,QE),l=u(-1,l,VE)),a._zUp?(re.transformVec3(t,i,r),re.transformVec3(t,l,s),a._navCubeCamera.look=[0,0,0],a._navCubeCamera.eye=re.transformVec3(t,i,r),a._navCubeCamera.up=re.transformPoint3(t,l,s)):(a._navCubeCamera.look=[0,0,0],a._navCubeCamera.eye=i,a._navCubeCamera.up=l)}}(),r._cubeTextureCanvas=new NE(e,o,s),r._cubeSampler=new Zn(o,{image:r._cubeTextureCanvas.getImage(),flipY:!0,wrapS:1001,wrapT:1001}),r._cubeMesh=new mn(o,{geometry:new Ki(o,{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 qi(o,{diffuse:[.4,.4,.4],specular:[.4,.4,.4],emissive:[.6,.6,.6],diffuseMap:r._cubeSampler,emissiveMap:r._cubeSampler}),visible:!!n,edges:!0}),r._shadow=!1===s.shadowVisible?null:new mn(o,{geometry:new Ki(o,yn({center:[0,0,0],radiusTop:.001,radiusBottom:1.4,height:.01,radialSegments:20,heightSegments:1,openEnded:!0})),material:new qi(o,{diffuse:[0,0,0],specular:[0,0,0],emissive:[0,0,0],alpha:.5}),position:[0,-1.5,0],visible:!!n,pickable:!1,backfaces:!1}),r._onCameraMatrix=e.camera.on("matrix",r._synchCamera),r._onCameraWorldAxis=e.camera.on("worldAxis",(function(){e.camera.zUp?(r._zUp=!0,r._cubeTextureCanvas.setZUp(),r._repaint(),r._synchCamera()):e.camera.yUp&&(r._zUp=!1,r._cubeTextureCanvas.setYUp(),r._repaint(),r._synchCamera())})),r._onCameraFOV=e.camera.perspective.on("fov",(function(e){r._synchProjection&&(r._navCubeCamera.perspective.fov=e)})),r._onCameraProjection=e.camera.on("projection",(function(e){r._synchProjection&&(r._navCubeCamera.projection="ortho"===e||"perspective"===e?e:"perspective")}));var c=-1;function A(t,i){var r=(t-d)*-_,s=(i-p)*-_;e.camera.orbitYaw(r),e.camera.orbitPitch(-s),d=t,p=i}function h(e){var t=[0,0];if(e){for(var i=e.target,r=0,s=0;i.offsetParent;)r+=i.offsetLeft,s+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-r,t[1]=e.pageY-s}else e=window.event,t[0]=e.x,t[1]=e.y;return t}var d,p,f=null,v=null,g=!1,m=!1,_=.5;a._navCubeCanvas.addEventListener("mouseenter",a._onMouseEnter=function(e){m=!0}),a._navCubeCanvas.addEventListener("mouseleave",a._onMouseLeave=function(e){m=!1}),a._navCubeCanvas.addEventListener("mousedown",a._onMouseDown=function(e){if(1===e.which){f=e.x,v=e.y,d=e.clientX,p=e.clientY;var t=h(e),i=o.pick({canvasPos:t});g=!!i}}),document.addEventListener("mouseup",a._onMouseUp=function(e){if(1===e.which&&(g=!1,null!==f)){var t=h(e),i=o.pick({canvasPos:t,pickSurface:!0});if(i&&i.uv){var r=a._cubeTextureCanvas.getArea(i.uv);if(r>=0&&(document.body.style.cursor="pointer",c>=0&&(a._cubeTextureCanvas.setAreaHighlighted(c,!1),a._repaint(),c=-1),r>=0)){if(a._cubeTextureCanvas.setAreaHighlighted(r,!0),c=r,a._repaint(),e.xf+3||e.yv+3)return;var s=a._cubeTextureCanvas.getAreaDir(r);if(s){var n=a._cubeTextureCanvas.getAreaUp(r);a._isProjectNorth&&a._projectNorthOffsetAngle&&(s=u(1,s,QE),n=u(1,n,VE)),x(s,n,(function(){c>=0&&(a._cubeTextureCanvas.setAreaHighlighted(c,!1),a._repaint(),c=-1),document.body.style.cursor="pointer",c>=0&&(a._cubeTextureCanvas.setAreaHighlighted(c,!1),a._repaint(),c=-1),r>=0&&(a._cubeTextureCanvas.setAreaHighlighted(r,!1),c=-1,a._repaint())}))}}}}}),document.addEventListener("mousemove",a._onMouseMove=function(e){if(c>=0&&(a._cubeTextureCanvas.setAreaHighlighted(c,!1),a._repaint(),c=-1),1!==e.buttons||g){if(g){var t=e.clientX,i=e.clientY;return document.body.style.cursor="move",void A(t,i)}if(m){var r=h(e),s=o.pick({canvasPos:r,pickSurface:!0});if(s){if(s.uv){document.body.style.cursor="pointer";var n=a._cubeTextureCanvas.getArea(s.uv);if(n===c)return;c>=0&&a._cubeTextureCanvas.setAreaHighlighted(c,!1),n>=0&&(a._cubeTextureCanvas.setAreaHighlighted(n,!0),a._repaint(),c=n)}}else document.body.style.cursor="default",c>=0&&(a._cubeTextureCanvas.setAreaHighlighted(c,!1),a._repaint(),c=-1)}}});var x=function(){var t=re.vec3();return function(i,r,s){var n=a._fitVisible?e.scene.getAABB(e.scene.visibleObjectIds):e.scene.aabb,o=re.getAABB3Diag(n);re.getAABB3Center(n,t);var l=Math.abs(o/Math.tan(a._cameraFitFOV*re.DEGTORAD));e.cameraControl.pivotPos=t,a._cameraFly?e.cameraFlight.flyTo({look:t,eye:[t[0]-l*i[0],t[1]-l*i[1],t[2]-l*i[2]],up:r||[0,1,0],orthoScale:1.1*o,fitFOV:a._cameraFitFOV,duration:a._cameraFlyDuration},s):e.cameraFlight.jumpTo({look:t,eye:[t[0]-l*i[0],t[1]-l*i[1],t[2]-l*i[2]],up:r||[0,1,0],orthoScale:1.1*o,fitFOV:a._cameraFitFOV},s)}}();return r._onUpdated=e.localeService.on("updated",(function(){r._cubeTextureCanvas.clear(),r._repaint()})),r.setVisible(s.visible),r.setCameraFitFOV(s.cameraFitFOV),r.setCameraFly(s.cameraFly),r.setCameraFlyDuration(s.cameraFlyDuration),r.setFitVisible(s.fitVisible),r.setSynchProjection(s.synchProjection),r}return C(i,[{key:"send",value:function(e,t){if("language"===e)this._cubeTextureCanvas.clear(),this._repaint()}},{key:"_repaint",value:function(){var e=this._cubeTextureCanvas.getImage();this._cubeMesh.material.diffuseMap.image=e,this._cubeMesh.material.emissiveMap.image=e}},{key:"setVisible",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this._navCubeCanvas&&(this._cubeMesh.visible=e,this._shadow&&(this._shadow.visible=e),this._navCubeCanvas.style.visibility=e?"visible":"hidden")}},{key:"getVisible",value:function(){return!!this._navCubeCanvas&&this._cubeMesh.visible}},{key:"setFitVisible",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._fitVisible=e}},{key:"getFitVisible",value:function(){return this._fitVisible}},{key:"setCameraFly",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this._cameraFly=e}},{key:"getCameraFly",value:function(){return this._cameraFly}},{key:"setCameraFitFOV",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:45;this._cameraFitFOV=e}},{key:"getCameraFitFOV",value:function(){return this._cameraFitFOV}},{key:"setCameraFlyDuration",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:.5;this._cameraFlyDuration=e}},{key:"getCameraFlyDuration",value:function(){return this._cameraFlyDuration}},{key:"setSynchProjection",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._synchProjection=e}},{key:"getSynchProjection",value:function(){return this._synchProjection}},{key:"setIsProjectNorth",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._isProjectNorth=e}},{key:"getIsProjectNorth",value:function(){return this._isProjectNorth}},{key:"setProjectNorthOffsetAngle",value:function(e){this._projectNorthOffsetAngle=e}},{key:"getProjectNorthOffsetAngle",value:function(){return this._projectNorthOffsetAngle}},{key:"destroy",value:function(){this._navCubeCanvas&&(this.viewer.localeService.off(this._onUpdated),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,f(x(i.prototype),"destroy",this).call(this)}}]),i}(),jE=re.vec3(),GE=function(){function e(){B(this,e)}return C(e,[{key:"load",value:function(e,t){var i=e.scene.canvas.spinner;i.processes++,zE(e,t,(function(t){KE(e,t,(function(){YE(e,t),i.processes--,we.scheduleTask((function(){e.fire("loaded",!0,!1)}))}))}))}},{key:"parse",value:function(e,t,i,r){if(t){var s=WE(e,t,null);i&&JE(e,i,r),YE(e,s),e.src=null,e.fire("loaded",!0,!1)}else this.warn("load() param expected: objText")}}]),e}(),zE=function(e,t,i){ZE(t,(function(r){var s=WE(e,r,t);i(s)}),(function(t){e.error(t)}))},WE=function(){var e={vertex_pattern:/^v\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,normal_pattern:/^vn\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,uv_pattern:/^vt\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,face_vertex:/^f\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)(?:\s+(-?\d+))?/,face_vertex_uv:/^f\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+))?/,face_vertex_uv_normal:/^f\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+)\/(-?\d+))?/,face_vertex_normal:/^f\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)(?:\s+(-?\d+)\/\/(-?\d+))?/,object_pattern:/^[og]\s*(.+)?/,smoothing_pattern:/^s\s+(\d+|on|off)/,material_library_pattern:/^mtllib /,material_use_pattern:/^usemtl /};return function(r,s,n){var o={src:n=n||"",basePath:t(n),objects:[],object:{},positions:[],normals:[],uv:[],materialLibraries:{}};i(o,"",!1),-1!==s.indexOf("\r\n")&&(s=s.replace("\r\n","\n"));for(var a=s.split("\n"),l="",u="",c="",d=[],p="function"==typeof"".trimLeft,f=0,v=a.length;f=0?i-1:i+t/3)}function s(e,t){var i=parseInt(e,10);return 3*(i>=0?i-1:i+t/3)}function n(e,t){var i=parseInt(e,10);return 2*(i>=0?i-1:i+t/2)}function o(e,t,i,r){var s=e.positions,n=e.object.geometry.positions;n.push(s[t+0]),n.push(s[t+1]),n.push(s[t+2]),n.push(s[i+0]),n.push(s[i+1]),n.push(s[i+2]),n.push(s[r+0]),n.push(s[r+1]),n.push(s[r+2])}function a(e,t){var i=e.positions,r=e.object.geometry.positions;r.push(i[t+0]),r.push(i[t+1]),r.push(i[t+2])}function l(e,t,i,r){var s=e.normals,n=e.object.geometry.normals;n.push(s[t+0]),n.push(s[t+1]),n.push(s[t+2]),n.push(s[i+0]),n.push(s[i+1]),n.push(s[i+2]),n.push(s[r+0]),n.push(s[r+1]),n.push(s[r+2])}function u(e,t,i,r){var s=e.uv,n=e.object.geometry.uv;n.push(s[t+0]),n.push(s[t+1]),n.push(s[i+0]),n.push(s[i+1]),n.push(s[r+0]),n.push(s[r+1])}function c(e,t){var i=e.uv,r=e.object.geometry.uv;r.push(i[t+0]),r.push(i[t+1])}function A(e,t,i,a,c,A,h,d,p,f,v,g,m){var _,y=e.positions.length,b=r(t,y),x=r(i,y),w=r(a,y);if(void 0===c?o(e,b,x,w):(o(e,b,x,_=r(c,y)),o(e,x,w,_)),void 0!==A){var B=e.uv.length;b=n(A,B),x=n(h,B),w=n(d,B),void 0===c?u(e,b,x,w):(u(e,b,x,_=n(p,B)),u(e,x,w,_))}if(void 0!==f){var P=e.normals.length;b=s(f,P),x=f===v?b:s(v,P),w=f===g?b:s(g,P),void 0===c?l(e,b,x,w):(l(e,b,x,_=s(m,P)),l(e,x,w,_))}}function h(e,t,i){e.object.geometry.type="Line";for(var s=e.positions.length,o=e.uv.length,l=0,u=t.length;l=0?o.substring(0,a):o).toLowerCase(),u=(u=a>=0?o.substring(a+1):"").trim(),l.toLowerCase()){case"newmtl":i(e,h),h={id:u},d=!0;break;case"ka":h.ambient=r(u);break;case"kd":h.diffuse=r(u);break;case"ks":h.specular=r(u);break;case"map_kd":h.diffuseMap||(h.diffuseMap=t(e,n,u,"sRGB"));break;case"map_ks":h.specularMap||(h.specularMap=t(e,n,u,"linear"));break;case"map_bump":case"bump":h.normalMap||(h.normalMap=t(e,n,u));break;case"ns":h.shininess=parseFloat(u);break;case"d":(c=parseFloat(u))<1&&(h.alpha=c,h.alphaMode="blend");break;case"tr":(c=parseFloat(u))>0&&(h.alpha=1-c,h.alphaMode="blend")}d&&i(e,h)};function t(e,t,i,r){var s={},n=i.split(/\s+/),o=n.indexOf("-bm");return o>=0&&n.splice(o,2),(o=n.indexOf("-s"))>=0&&(s.scale=[parseFloat(n[o+1]),parseFloat(n[o+2])],n.splice(o,4)),(o=n.indexOf("-o"))>=0&&(s.translate=[parseFloat(n[o+1]),parseFloat(n[o+2])],n.splice(o,4)),s.src=t+n.join(" ").trim(),s.flipY=!0,s.encoding=r||"linear",new Zn(e,s).id}function i(e,t){new qi(e,t)}function r(t){var i=t.split(e,3);return[parseFloat(i[0]),parseFloat(i[1]),parseFloat(i[2])]}}();function YE(e,t){for(var i=0,r=t.objects.length;i0&&(o.normals=n.normals),n.uv.length>0&&(o.uv=n.uv);for(var a=new Array(o.positions.length/3),l=0;l0&&void 0!==arguments[0]?arguments[0]:{};t.id&&this.viewer.scene.components[t.id]&&(this.error("Component with this ID already exists in viewer: "+t.id+" - will autogenerate this ID"),delete t.id);var i=new Ln(this.viewer.scene,he.apply(t,{isModel:!0})),r=i.id,s=t.src;if(!s)return this.error("load() param expected: src"),i;if(t.metaModelSrc){var n=t.metaModelSrc;he.loadJSON(n,(function(n){e.viewer.metaScene.createMetaModel(r,n),e._sceneGraphLoader.load(i,s,t)}),(function(t){e.error("load(): Failed to load model modelMetadata for model '".concat(r," from '").concat(n,"' - ").concat(t))}))}else this._sceneGraphLoader.load(i,s,t);return i.once("destroyed",(function(){e.viewer.metaScene.destroyMetaModel(r)})),i}},{key:"destroy",value:function(){f(x(i.prototype),"destroy",this).call(this)}}]),i}(),$E=new Float64Array([0,0,1]),eF=new Float64Array(4),tF=function(){function e(t){B(this,e),this.id=null,this._viewer=t.viewer,this._visible=!1,this._pos=re.vec3(),this._origin=re.vec3(),this._rtcPos=re.vec3(),this._baseDir=re.vec3(),this._rootNode=null,this._displayMeshes=null,this._affordanceMeshes=null,this._ignoreNextSectionPlaneDirUpdate=!1,this._createNodes(),this._bindEvents()}return C(e,[{key:"_setSectionPlane",value:function(e){var t=this;this._sectionPlane&&(this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._onSectionPlanePos=null,this._onSectionPlaneDir=null,this._sectionPlane=null),e&&(this.id=e.id,this._setPos(e.pos),this._setDir(e.dir),this._sectionPlane=e,this._onSectionPlanePos=e.on("pos",(function(){t._setPos(t._sectionPlane.pos)})),this._onSectionPlaneDir=e.on("dir",(function(){t._ignoreNextSectionPlaneDirUpdate?t._ignoreNextSectionPlaneDirUpdate=!1:t._setDir(t._sectionPlane.dir)})))}},{key:"sectionPlane",get:function(){return this._sectionPlane}},{key:"_setPos",value:function(e){this._pos.set(e),He(this._pos,this._origin,this._rtcPos),this._rootNode.origin=this._origin,this._rootNode.position=this._rtcPos}},{key:"_setDir",value:function(e){this._baseDir.set(e),this._rootNode.quaternion=re.vec3PairToQuaternion($E,e,eF)}},{key:"_setSectionPlaneDir",value:function(e){this._sectionPlane&&(this._ignoreNextSectionPlaneDirUpdate=!0,this._sectionPlane.dir=e)}},{key:"setVisible",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[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)}}},{key:"getVisible",value:function(){return this._visible}},{key:"setCulled",value:function(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)}},{key:"_createNodes",value:function(){var e=!1,t=this._viewer.scene,i=.01;this._rootNode=new Ln(t,{position:[0,0,0],scale:[5,5,5],isObject:!1});var r,s,n=this._rootNode,o={arrowHead:new Ki(n,yn({radiusTop:.001,radiusBottom:.07,radialSegments:32,heightSegments:1,height:.2,openEnded:!1})),arrowHeadBig:new Ki(n,yn({radiusTop:.001,radiusBottom:.09,radialSegments:32,heightSegments:1,height:.25,openEnded:!1})),arrowHeadHandle:new Ki(n,yn({radiusTop:.09,radiusBottom:.09,radialSegments:8,heightSegments:1,height:.37,openEnded:!1})),curve:new Ki(n,uo({radius:.8,tube:i,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),curveHandle:new Ki(n,uo({radius:.8,tube:.06,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),hoop:new Ki(n,uo({radius:.8,tube:i,radialSegments:64,tubeSegments:8,arc:2*Math.PI})),axis:new Ki(n,yn({radiusTop:i,radiusBottom:i,radialSegments:20,heightSegments:1,height:1,openEnded:!1})),axisHandle:new Ki(n,yn({radiusTop:.08,radiusBottom:.08,radialSegments:20,heightSegments:1,height:1,openEnded:!1}))},a={pickable:new qi(n,{diffuse:[1,1,0],alpha:0,alphaMode:"blend"}),red:new qi(n,{diffuse:[1,0,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightRed:new er(n,{edges:!1,fill:!0,fillColor:[1,0,0],fillAlpha:.6}),green:new qi(n,{diffuse:[0,1,0],emissive:[0,1,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightGreen:new er(n,{edges:!1,fill:!0,fillColor:[0,1,0],fillAlpha:.6}),blue:new qi(n,{diffuse:[0,0,1],emissive:[0,0,1],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightBlue:new er(n,{edges:!1,fill:!0,fillColor:[0,0,1],fillAlpha:.2}),center:new qi(n,{diffuse:[0,0,0],emissive:[0,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80}),highlightBall:new er(n,{edges:!1,fill:!0,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1}),highlightPlane:new er(n,{edges:!0,edgeWidth:3,fill:!1,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1})};this._displayMeshes={plane:n.addChild(new mn(n,{geometry:new Ki(n,{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 qi(n,{emissive:[0,0,0],diffuse:[0,0,0],backfaces:!0}),opacity:.6,ghosted:!0,ghostMaterial:new er(n,{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],isObject:!1}),e),planeFrame:n.addChild(new mn(n,{geometry:new Ki(n,uo({center:[0,0,0],radius:1.7,tube:.02,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new qi(n,{emissive:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],shininess:0}),highlightMaterial:new er(n,{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],isObject:!1}),e),xCurve:n.addChild(new mn(n,{geometry:o.curve,material:a.red,matrix:(r=re.rotationMat4v(90*re.DEGTORAD,[0,1,0],re.identityMat4()),s=re.rotationMat4v(270*re.DEGTORAD,[1,0,0],re.identityMat4()),re.mulMat4(s,r,re.identityMat4())),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xCurveHandle:n.addChild(new mn(n,{geometry:o.curveHandle,material:a.pickable,matrix:function(){var e=re.rotationMat4v(90*re.DEGTORAD,[0,1,0],re.identityMat4()),t=re.rotationMat4v(270*re.DEGTORAD,[1,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xCurveArrow1:n.addChild(new mn(n,{geometry:o.arrowHead,material:a.red,matrix:function(){var e=re.translateMat4c(0,-.07,-.8,re.identityMat4()),t=re.scaleMat4v([.6,.6,.6],re.identityMat4()),i=re.rotationMat4v(0*re.DEGTORAD,[0,0,1],re.identityMat4());return re.mulMat4(re.mulMat4(e,t,re.identityMat4()),i,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xCurveArrow2:n.addChild(new mn(n,{geometry:o.arrowHead,material:a.red,matrix:function(){var e=re.translateMat4c(0,-.8,-.07,re.identityMat4()),t=re.scaleMat4v([.6,.6,.6],re.identityMat4()),i=re.rotationMat4v(90*re.DEGTORAD,[1,0,0],re.identityMat4());return re.mulMat4(re.mulMat4(e,t,re.identityMat4()),i,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yCurve:n.addChild(new mn(n,{geometry:o.curve,material:a.green,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),yCurveHandle:n.addChild(new mn(n,{geometry:o.curveHandle,material:a.pickable,rotation:[-90,0,0],pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),yCurveArrow1:n.addChild(new mn(n,{geometry:o.arrowHead,material:a.green,matrix:function(){var e=re.translateMat4c(.07,0,-.8,re.identityMat4()),t=re.scaleMat4v([.6,.6,.6],re.identityMat4()),i=re.rotationMat4v(90*re.DEGTORAD,[0,0,1],re.identityMat4());return re.mulMat4(re.mulMat4(e,t,re.identityMat4()),i,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yCurveArrow2:n.addChild(new mn(n,{geometry:o.arrowHead,material:a.green,matrix:function(){var e=re.translateMat4c(.8,0,-.07,re.identityMat4()),t=re.scaleMat4v([.6,.6,.6],re.identityMat4()),i=re.rotationMat4v(90*re.DEGTORAD,[1,0,0],re.identityMat4());return re.mulMat4(re.mulMat4(e,t,re.identityMat4()),i,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurve:n.addChild(new mn(n,{geometry:o.curve,material:a.blue,matrix:re.rotationMat4v(180*re.DEGTORAD,[1,0,0],re.identityMat4()),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveHandle:n.addChild(new mn(n,{geometry:o.curveHandle,material:a.pickable,matrix:re.rotationMat4v(180*re.DEGTORAD,[1,0,0],re.identityMat4()),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveCurveArrow1:n.addChild(new mn(n,{geometry:o.arrowHead,material:a.blue,matrix:function(){var e=re.translateMat4c(.8,-.07,0,re.identityMat4()),t=re.scaleMat4v([.6,.6,.6],re.identityMat4());return re.mulMat4(e,t,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveArrow2:n.addChild(new mn(n,{geometry:o.arrowHead,material:a.blue,matrix:function(){var e=re.translateMat4c(.05,-.8,0,re.identityMat4()),t=re.scaleMat4v([.6,.6,.6],re.identityMat4()),i=re.rotationMat4v(90*re.DEGTORAD,[0,0,1],re.identityMat4());return re.mulMat4(re.mulMat4(e,t,re.identityMat4()),i,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),center:n.addChild(new mn(n,{geometry:new Ki(n,bn({radius:.05})),material:a.center,pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisArrow:n.addChild(new mn(n,{geometry:o.arrowHead,material:a.red,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[0,0,1],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisArrowHandle:n.addChild(new mn(n,{geometry:o.arrowHeadHandle,material:a.pickable,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[0,0,1],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxis:n.addChild(new mn(n,{geometry:o.axis,material:a.red,matrix:function(){var e=re.translateMat4c(0,.5,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[0,0,1],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisHandle:n.addChild(new mn(n,{geometry:o.axisHandle,material:a.pickable,matrix:function(){var e=re.translateMat4c(0,.5,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[0,0,1],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrow:n.addChild(new mn(n,{geometry:o.arrowHead,material:a.green,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(180*re.DEGTORAD,[1,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrowHandle:n.addChild(new mn(n,{geometry:o.arrowHeadHandle,material:a.pickable,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(180*re.DEGTORAD,[1,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,opacity:.2,isObject:!1}),e),yShaft:n.addChild(new mn(n,{geometry:o.axis,material:a.green,position:[0,-.5,0],pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yShaftHandle:n.addChild(new mn(n,{geometry:o.axisHandle,material:a.pickable,position:[0,-.5,0],pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrow:n.addChild(new mn(n,{geometry:o.arrowHead,material:a.blue,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[.8,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrowHandle:n.addChild(new mn(n,{geometry:o.arrowHeadHandle,material:a.pickable,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[.8,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zShaft:n.addChild(new mn(n,{geometry:o.axis,material:a.blue,matrix:function(){var e=re.translateMat4c(0,.5,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[1,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),clippable:!1,pickable:!1,collidable:!0,visible:!1,isObject:!1}),e),zAxisHandle:n.addChild(new mn(n,{geometry:o.axisHandle,material:a.pickable,matrix:function(){var e=re.translateMat4c(0,.5,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[1,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),clippable:!1,pickable:!0,collidable:!0,visible:!1,isObject:!1}),e)},this._affordanceMeshes={planeFrame:n.addChild(new mn(n,{geometry:new Ki(n,uo({center:[0,0,0],radius:2,tube:i,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new qi(n,{ambient:[1,1,1],diffuse:[0,0,0],emissive:[1,1,0]}),highlighted:!0,highlightMaterial:new er(n,{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],isObject:!1}),e),xHoop:n.addChild(new mn(n,{geometry:o.hoop,material:a.red,highlighted:!0,highlightMaterial:a.highlightRed,matrix:function(){var e=re.rotationMat4v(90*re.DEGTORAD,[0,1,0],re.identityMat4()),t=re.rotationMat4v(270*re.DEGTORAD,[1,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yHoop:n.addChild(new mn(n,{geometry:o.hoop,material:a.green,highlighted:!0,highlightMaterial:a.highlightGreen,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zHoop:n.addChild(new mn(n,{geometry:o.hoop,material:a.blue,highlighted:!0,highlightMaterial:a.highlightBlue,matrix:re.rotationMat4v(180*re.DEGTORAD,[1,0,0],re.identityMat4()),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xAxisArrow:n.addChild(new mn(n,{geometry:o.arrowHeadBig,material:a.red,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[0,0,1],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrow:n.addChild(new mn(n,{geometry:o.arrowHeadBig,material:a.green,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(180*re.DEGTORAD,[1,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrow:n.addChild(new mn(n,{geometry:o.arrowHeadBig,material:a.blue,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[.8,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e)}}},{key:"_bindEvents",value:function(){var e=this,t=this,i=!1,r=-1,s=0,n=1,o=2,a=3,l=4,u=5,c=this._rootNode,A=null,h=null,d=re.vec2(),p=re.vec3([1,0,0]),f=re.vec3([0,1,0]),v=re.vec3([0,0,1]),g=this._viewer.scene.canvas.canvas,m=this._viewer.camera,_=this._viewer.scene,y=re.vec3([0,0,0]),b=-1;this._onCameraViewMatrix=_.camera.on("viewMatrix",(function(){})),this._onCameraProjMatrix=_.camera.on("projMatrix",(function(){})),this._onSceneTick=_.on("tick",(function(){var t=Math.abs(re.lenVec3(re.subVec3(_.camera.eye,e._pos,y)));if(t!==b&&"perspective"===m.projection){var i=.07*(Math.tan(m.perspective.fov*re.DEGTORAD)*t);c.scale=[i,i,i],b=t}if("ortho"===m.projection){var r=m.ortho.scale/10;c.scale=[r,r,r],b=t}}));var x,w,B,P,C,M=function(){var e=new Float64Array(2);return function(t){if(t){for(var i=t.target,r=0,s=0;i.offsetParent;)r+=i.offsetLeft,s+=i.offsetTop,i=i.offsetParent;e[0]=t.pageX-r,e[1]=t.pageY-s}else t=window.event,e[0]=t.x,e[1]=t.y;return e}}(),E=function(){var e=re.mat4();return function(i,r){return re.quaternionToMat4(t._rootNode.quaternion,e),re.transformVec3(e,i,r),re.normalizeVec3(r),r}}(),F=(x=re.vec3(),function(e){var t=Math.abs(e[0]);return t>Math.abs(e[1])&&t>Math.abs(e[2])?re.cross3Vec3(e,[0,1,0],x):re.cross3Vec3(e,[1,0,0],x),re.cross3Vec3(x,e,x),re.normalizeVec3(x),x}),k=(w=re.vec3(),B=re.vec3(),P=re.vec4(),function(e,i,r){E(e,P);var s=F(P,i,r);D(i,s,w),D(r,s,B),re.subVec3(B,w);var n=re.dotVec3(B,P);t._pos[0]+=P[0]*n,t._pos[1]+=P[1]*n,t._pos[2]+=P[2]*n,t._rootNode.position=t._pos,t._sectionPlane&&(t._sectionPlane.pos=t._pos)}),I=function(){var e=re.vec4(),i=re.vec4(),r=re.vec4(),s=re.vec4();return function(n,o,a){if(E(n,s),!(D(o,s,e)&&D(a,s,i))){var l=F(s,o,a);D(o,l,e,1),D(a,l,i,1);var u=re.dotVec3(e,s);e[0]-=u*s[0],e[1]-=u*s[1],e[2]-=u*s[2],u=re.dotVec3(i,s),i[0]-=u*s[0],i[1]-=u*s[1],i[2]-=u*s[2]}re.normalizeVec3(e),re.normalizeVec3(i),u=re.dotVec3(e,i),u=re.clamp(u,-1,1);var c=Math.acos(u)*re.RADTODEG;re.cross3Vec3(e,i,r),re.dotVec3(r,s)<0&&(c=-c),t._rootNode.rotate(n,c),S()}}(),D=function(){var e=re.vec4([0,0,0,1]),i=re.mat4();return function(r,s,n,o){o=o||0,e[0]=r[0]/g.width*2-1,e[1]=-(r[1]/g.height*2-1),e[2]=0,e[3]=1,re.mulMat4(m.projMatrix,m.viewMatrix,i),re.inverseMat4(i),re.transformVec4(i,e,e),re.mulVec4Scalar(e,1/e[3]);var a=m.eye;re.subVec4(e,a,e);var l=t._sectionPlane.pos,u=-re.dotVec3(l,s)-o,c=re.dotVec3(s,e);if(Math.abs(c)>.005){var A=-(re.dotVec3(s,a)+u)/c;return re.mulVec3Scalar(e,A,n),re.addVec3(n,a),re.subVec3(n,l,n),!0}return!1}}(),S=function(){var e=re.vec3(),i=re.mat4();return function(){t.sectionPlane&&(re.quaternionToMat4(c.quaternion,i),re.transformVec3(i,[0,0,1],e),t._setSectionPlaneDir(e))}}(),T=!1;this._onCameraControlHover=this._viewer.cameraControl.on("hoverEnter",(function(t){if(e._visible&&!T){var c;switch(i=!1,C&&(C.visible=!1),t.entity.id){case e._displayMeshes.xAxisArrowHandle.id:case e._displayMeshes.xAxisHandle.id:c=e._affordanceMeshes.xAxisArrow,A=s;break;case e._displayMeshes.yAxisArrowHandle.id:case e._displayMeshes.yShaftHandle.id:c=e._affordanceMeshes.yAxisArrow,A=n;break;case e._displayMeshes.zAxisArrowHandle.id:case e._displayMeshes.zAxisHandle.id:c=e._affordanceMeshes.zAxisArrow,A=o;break;case e._displayMeshes.xCurveHandle.id:c=e._affordanceMeshes.xHoop,A=a;break;case e._displayMeshes.yCurveHandle.id:c=e._affordanceMeshes.yHoop,A=l;break;case e._displayMeshes.zCurveHandle.id:c=e._affordanceMeshes.zHoop,A=u;break;default:return void(A=r)}c&&(c.visible=!0),C=c,i=!0}})),this._onCameraControlHoverLeave=this._viewer.cameraControl.on("hoverOutEntity",(function(t){e._visible&&(C&&(C.visible=!1),C=null,A=r)})),g.addEventListener("mousedown",this._canvasMouseDownListener=function(t){if(t.preventDefault(),e._visible&&i&&(e._viewer.cameraControl.pointerEnabled=!1,1===t.which)){T=!0;var r=M(t);h=A,d[0]=r[0],d[1]=r[1]}}),g.addEventListener("mousemove",this._canvasMouseMoveListener=function(t){if(e._visible&&T){var i=M(t),r=i[0],c=i[1];switch(h){case s:k(p,d,i);break;case n:k(f,d,i);break;case o:k(v,d,i);break;case a:I(p,d,i);break;case l:I(f,d,i);break;case u:I(v,d,i)}d[0]=r,d[1]=c}}),g.addEventListener("mouseup",this._canvasMouseUpListener=function(t){e._visible&&(e._viewer.cameraControl.pointerEnabled=!0,T&&(t.which,T=!1,i=!1))}),g.addEventListener("wheel",this._canvasWheelListener=function(t){if(e._visible)Math.max(-1,Math.min(1,40*-t.deltaY))})}},{key:"_destroy",value:function(){this._unbindEvents(),this._destroyNodes()}},{key:"_unbindEvents",value:function(){var e=this._viewer,t=e.scene,i=t.canvas.canvas,r=e.camera,s=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),r.off(this._onCameraViewMatrix),r.off(this._onCameraProjMatrix),s.off(this._onCameraControlHover),s.off(this._onCameraControlHoverLeave)}},{key:"_destroyNodes",value:function(){this._setSectionPlane(null),this._rootNode.destroy(),this._displayMeshes={},this._affordanceMeshes={}}}]),e}(),iF=function(){function e(t,i,r){var s=this;B(this,e),this.id=r.id,this._sectionPlane=r,this._mesh=new mn(i,{id:r.id,geometry:new Ki(i,Xi({xSize:.5,ySize:.5,zSize:.001})),material:new qi(i,{emissive:[1,1,1],diffuse:[0,0,0],backfaces:!1}),edgeMaterial:new ir(i,{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),highlightMaterial:new er(i,{fill:!0,fillColor:[.5,1,.5],fillAlpha:.7,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),selectedMaterial:new er(i,{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});var n=re.vec3([0,0,0]),o=re.vec3(),a=re.vec3([0,0,1]),l=re.vec4(4),u=re.vec3(),c=function(){var e=s._sectionPlane.scene.center,t=[-s._sectionPlane.dir[0],-s._sectionPlane.dir[1],-s._sectionPlane.dir[2]];re.subVec3(e,s._sectionPlane.pos,n);var i=-re.dotVec3(t,n);re.normalizeVec3(t),re.mulVec3Scalar(t,i,o);var r=re.vec3PairToQuaternion(a,s._sectionPlane.dir,l);u[0]=.1*o[0],u[1]=.1*o[1],u[2]=.1*o[2],s._mesh.quaternion=r,s._mesh.position=u};this._onSectionPlanePos=this._sectionPlane.on("pos",c),this._onSectionPlaneDir=this._sectionPlane.on("dir",c),this._highlighted=!1,this._selected=!1}return C(e,[{key:"setHighlighted",value:function(e){this._highlighted=!!e,this._mesh.highlighted=this._highlighted,this._mesh.highlightMaterial.fillColor=e?[0,.7,0]:[0,0,0]}},{key:"getHighlighted",value:function(){return this._highlighted}},{key:"setSelected",value:function(e){this._selected=!!e,this._mesh.edgeMaterial.edgeWidth=e?3:1,this._mesh.highlightMaterial.edgeWidth=e?3:1}},{key:"getSelected",value:function(){return this._selected}},{key:"destroy",value:function(){this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._mesh.destroy()}}]),e}(),rF=function(){function e(t,i){var r=this;if(B(this,e),!(i.onHoverEnterPlane&&i.onHoverLeavePlane&&i.onClickedNothing&&i.onClickedPlane))throw"Missing config(s): onHoverEnterPlane, onHoverLeavePlane, onClickedNothing || onClickedPlane";this.plugin=t,this._viewer=t.viewer,this._onHoverEnterPlane=i.onHoverEnterPlane,this._onHoverLeavePlane=i.onHoverLeavePlane,this._onClickedNothing=i.onClickedNothing,this._onClickedPlane=i.onClickedPlane,this._visible=!0,this._planes={},this._canvas=i.overviewCanvas,this._scene=new hr(this._viewer,{canvasId:this._canvas.id,transparent:!0}),this._scene.clearLights(),new Ti(this._scene,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new Ti(this._scene,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new Ti(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;var s=this._scene.camera,n=re.rotationMat4c(-90*re.DEGTORAD,1,0,0),o=re.vec3(),a=re.vec3(),l=re.vec3();this._synchCamera=function(){var e=r._viewer.camera.eye,t=r._viewer.camera.look,i=r._viewer.camera.up;re.mulVec3Scalar(re.normalizeVec3(re.subVec3(e,t,o)),7),r._zUp?(re.transformVec3(n,o,a),re.transformVec3(n,i,l),s.look=[0,0,0],s.eye=re.transformVec3(n,o,a),s.up=re.transformPoint3(n,i,l)):(s.look=[0,0,0],s.eye=o,s.up=i)},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",(function(e){r._scene.camera.perspective.fov=e}));var u=null;this._onInputMouseMove=this._scene.input.on("mousemove",(function(e){var t=r._scene.pick({canvasPos:e});if(t){if(!u||t.entity.id!==u.id){if(u)r._planes[u.id]&&r._onHoverLeavePlane(u.id);u=t.entity,r._planes[u.id]&&r._onHoverEnterPlane(u.id)}}else u&&(r._onHoverLeavePlane(u.id),u=null)})),this._scene.canvas.canvas.addEventListener("mouseup",this._onCanvasMouseUp=function(){u?r._planes[u.id]&&r._onClickedPlane(u.id):r._onClickedNothing()}),this._scene.canvas.canvas.addEventListener("mouseout",this._onCanvasMouseOut=function(){u&&(r._onHoverLeavePlane(u.id),u=null)}),this.setVisible(i.overviewVisible)}return C(e,[{key:"addSectionPlane",value:function(e){this._planes[e.id]=new iF(this,this._scene,e)}},{key:"setPlaneHighlighted",value:function(e,t){var i=this._planes[e];i&&i.setHighlighted(t)}},{key:"setPlaneSelected",value:function(e,t){var i=this._planes[e];i&&i.setSelected(t)}},{key:"removeSectionPlane",value:function(e){var t=this._planes[e.id];t&&(t.destroy(),delete this._planes[e.id])}},{key:"setVisible",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this._visible=e,this._canvas.style.visibility=e?"visible":"hidden"}},{key:"getVisible",value:function(){return this._visible}},{key:"destroy",value:function(){this._viewer.camera.off(this._onViewerCameraMatrix),this._viewer.camera.off(this._onViewerCameraWorldAxis),this._viewer.camera.perspective.off(this._onViewerCameraFOV),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()}}]),e}(),sF=re.AABB3(),nF=re.vec3(),oF=function(e){g(i,Ue);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(B(this,i),(r=t.call(this,"SectionPlanes",e))._freeControls=[],r._sectionPlanes=e.scene.sectionPlanes,r._controls={},r._shownControlId=null,null!==s.overviewCanvasId&&void 0!==s.overviewCanvasId){var n=document.getElementById(s.overviewCanvasId);n?r._overview=new rF(b(r),{overviewCanvas:n,visible:s.overviewVisible,onHoverEnterPlane:function(e){r._overview.setPlaneHighlighted(e,!0)},onHoverLeavePlane:function(e){r._overview.setPlaneHighlighted(e,!1)},onClickedPlane:function(e){if(r.getShownControl()!==e){r.showControl(e);var t=r.sectionPlanes[e].pos;sF.set(r.viewer.scene.aabb),re.getAABB3Center(sF,nF),sF[0]+=t[0]-nF[0],sF[1]+=t[1]-nF[1],sF[2]+=t[2]-nF[2],sF[3]+=t[0]-nF[0],sF[4]+=t[1]-nF[1],sF[5]+=t[2]-nF[2],r.viewer.cameraFlight.flyTo({aabb:sF,fitFOV:65})}else r.hideControl()},onClickedNothing:function(){r.hideControl()}}):r.warn("Can't find overview canvas: '"+s.overviewCanvasId+"' - will create plugin without overview")}return r._onSceneSectionPlaneCreated=e.scene.on("sectionPlaneCreated",(function(e){r._sectionPlaneCreated(e)})),r}return C(i,[{key:"setOverviewVisible",value:function(e){this._overview&&this._overview.setVisible(e)}},{key:"getOverviewVisible",value:function(){if(this._overview)return this._overview.getVisible()}},{key:"sectionPlanes",get:function(){return this._sectionPlanes}},{key:"createSectionPlane",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};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);var t=new Pn(this.viewer.scene,{id:e.id,pos:e.pos,dir:e.dir,active:!0});return t}},{key:"_sectionPlaneCreated",value:function(e){var t=this,i=this._freeControls.length>0?this._freeControls.pop():new tF(this);i._setSectionPlane(e),i.setVisible(!1),this._controls[e.id]=i,this._overview&&this._overview.addSectionPlane(e),e.once("destroyed",(function(){t._sectionPlaneDestroyed(e)}))}},{key:"flipSectionPlanes",value:function(){var e=this.viewer.scene.sectionPlanes;for(var t in e){e[t].flipDir()}}},{key:"showControl",value:function(e){var 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)}},{key:"getShownControl",value:function(){return this._shownControlId}},{key:"hideControl",value:function(){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}},{key:"destroySectionPlane",value:function(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)}},{key:"_sectionPlaneDestroyed",value:function(e){this._overview&&this._overview.removeSectionPlane(e);var t=this._controls[e.id];t&&(t.setVisible(!1),t._setSectionPlane(null),delete this._controls[e.id],this._freeControls.push(t))}},{key:"clear",value:function(){for(var e=Object.keys(this._sectionPlanes),t=0,i=e.length;t1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),(r=t.call(this,"StoreyViews",e))._objectsMemento=new Hd,r._cameraMemento=new Od,r.storeys={},r.modelStoreys={},r._fitStoreyMaps=!!s.fitStoreyMaps,r._onModelLoaded=r.viewer.scene.on("modelLoaded",(function(e){r._registerModelStoreys(e),r.fire("storeys",r.storeys)})),r}return C(i,[{key:"_registerModelStoreys",value:function(e){var t=this,i=this.viewer,r=i.scene,s=i.metaScene,n=s.metaModels[e],o=r.models[e];if(n&&n.rootMetaObjects)for(var a=n.rootMetaObjects,l=0,u=a.length;l.5?p.length:0,g=new aF(this,o.aabb,f,e,d,v);g._onModelDestroyed=o.once("destroyed",(function(){t._deregisterModelStoreys(e),t.fire("storeys",t.storeys)})),this.storeys[d]=g,this.modelStoreys[e]||(this.modelStoreys[e]={}),this.modelStoreys[e][d]=g}}},{key:"_deregisterModelStoreys",value:function(e){var t=this.modelStoreys[e];if(t){var i=this.viewer.scene;for(var r in t)if(t.hasOwnProperty(r)){var s=t[r],n=i.models[s.modelId];n&&n.off(s._onModelDestroyed),delete this.storeys[r]}delete this.modelStoreys[e]}}},{key:"fitStoreyMaps",get:function(){return this._fitStoreyMaps}},{key:"gotoStoreyCamera",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=this.storeys[e];if(!i)return this.error("IfcBuildingStorey not found with this ID: "+e),void(t.done&&t.done());var r=this.viewer,s=r.scene,n=s.camera,o=i.storeyAABB;if(o[3]1&&void 0!==arguments[1]?arguments[1]:{},i=this.storeys[e];if(i){var r=this.viewer,s=r.scene,n=r.metaScene,o=n.metaObjects[e];o&&(t.hideOthers&&s.setObjectsVisible(r.scene.visibleObjectIds,!1),this.withStoreyObjects(e,(function(e,t){e&&(e.visible=!0)})))}else this.error("IfcBuildingStorey not found with this ID: "+e)}},{key:"withStoreyObjects",value:function(e,t){var i=this.viewer,r=i.scene,s=i.metaScene,n=s.metaObjects[e];if(n)for(var o=n.getObjectIDsInSubtree(),a=0,l=o.length;a1&&void 0!==arguments[1]?arguments[1]:{},i=this.storeys[e];if(!i)return this.error("IfcBuildingStorey not found with this ID: "+e),AF;var r,s,n=this.viewer,o=n.scene,a=t.format||"png",l=this._fitStoreyMaps?i.storeyAABB:i.modelAABB,u=Math.abs((l[5]-l[2])/(l[3]-l[0])),c=t.padding||0;t.width&&t.height?(r=t.width,s=t.height):t.height?(s=t.height,r=Math.round(s/u)):t.width?(r=t.width,s=Math.round(r*u)):(r=300,s=Math.round(r*u)),this._objectsMemento.saveObjects(o),this._cameraMemento.saveCamera(o),this.showStoreyObjects(e,he.apply(t,{hideOthers:!0})),this._arrangeStoreyMapCamera(i);var A=n.getSnapshot({width:r,height:s,format:a});return this._objectsMemento.restoreObjects(o),this._cameraMemento.restoreCamera(o),new lF(e,A,a,r,s,c)}},{key:"_arrangeStoreyMapCamera",value:function(e){var t=this.viewer,i=t.scene.camera,r=this._fitStoreyMaps?e.storeyAABB:e.modelAABB,s=re.getAABB3Center(r),n=uF;n[0]=s[0]+.5*i.worldUp[0],n[1]=s[1]+.5*i.worldUp[1],n[2]=s[2]+.5*i.worldUp[2];var o=i.worldForward;t.cameraFlight.jumpTo({eye:n,look:s,up:o});var a=(r[3]-r[0])/2,l=(r[4]-r[1])/2,u=(r[5]-r[2])/2,c=-a,A=+a,h=-l,d=+l,p=-u,f=+u;t.camera.customProjection.matrix=re.orthoMat4c(c,A,p,f,h,d,cF),t.camera.projection="customProjection"}},{key:"pickStoreyMap",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=e.storeyId,s=this.storeys[r];if(!s)return this.error("IfcBuildingStorey not found with this ID: "+r),null;var n=1-t[0]/e.width,o=1-t[1]/e.height,a=this._fitStoreyMaps?s.storeyAABB:s.modelAABB,l=a[0],u=a[1],c=a[2],A=a[3],h=a[4],d=a[5],p=A-l,f=h-u,v=d-c,g=re.vec3([l+p*n,u+.5*f,c+v*o]),m=re.vec3([0,-1,0]),_=re.addVec3(g,m,uF),y=this.viewer.camera.worldForward,b=re.lookAtMat4v(g,_,y,cF),x=this.viewer.scene.pick({pickSurface:i.pickSurface,pickInvisible:!0,matrix:b});return x}},{key:"storeyMapToWorldPos",value:function(e,t){var i=e.storeyId,r=this.storeys[i];if(!r)return this.error("IfcBuildingStorey not found with this ID: "+i),null;var s=1-t[0]/e.width,n=1-t[1]/e.height,o=this._fitStoreyMaps?r.storeyAABB:r.modelAABB,a=o[0],l=o[1],u=o[2],c=o[3],A=o[4],h=o[5],d=c-a,p=A-l,f=h-u,v=re.vec3([a+d*s,l+.5*p,u+f*n]);return v}},{key:"getStoreyContainingWorldPos",value:function(e){for(var t in this.storeys){var i=this.storeys[t];if(re.point3AABB3AbsoluteIntersect(i.storeyAABB,e))return t}return null}},{key:"getStoreyInVerticalRange",value:function(e){for(var t in this.storeys){var i=this.storeys[t],r=[0,0,0,0,0,0],s=[0,0,0];if(r[1]=i.storeyAABB[1],r[4]=i.storeyAABB[4],s[1]=e[1],re.point3AABB3AbsoluteIntersect(r,s))return t}return null}},{key:"isPositionAboveOrBelowBuilding",value:function(e){var t=Object.keys(this.storeys),i=[t[0],t[t.length-1]];return e[1]this.storeys[i[1]].storeyAABB[4]?i[1]:null}},{key:"worldPosToStoreyMap",value:function(e,t,i){var r=e.storeyId,s=this.storeys[r];if(!s)return this.error("IfcBuildingStorey not found with this ID: "+r),!1;var n=this._fitStoreyMaps?s.storeyAABB:s.modelAABB,o=n[0],a=n[1],l=n[2],u=n[3]-o,c=n[4]-a,A=n[5]-l,h=this.viewer.camera.worldUp,d=h[0]>h[1]&&h[0]>h[2],p=!d&&h[1]>h[0]&&h[1]>h[2];!d&&!p&&h[2]>h[0]&&(h[2],h[1]);var f=e.width/u,v=p?e.height/A:e.height/c;return i[0]=Math.floor(e.width-(t[0]-o)*f),i[1]=Math.floor(e.height-(t[2]-l)*v),i[0]>=0&&i[0]=0&&i[1]<=e.height}},{key:"worldDirToStoreyMap",value:function(e,t,i){var r=this.viewer.camera,s=r.eye,n=r.look,o=re.subVec3(n,s,uF),a=r.worldUp,l=a[0]>a[1]&&a[0]>a[2],u=!l&&a[1]>a[0]&&a[1]>a[2];!l&&!u&&a[2]>a[0]&&(a[2],a[1]),l?(i[0]=o[1],i[1]=o[2]):u?(i[0]=o[0],i[1]=o[2]):(i[0]=o[0],i[1]=o[1]),re.normalizeVec2(i)}},{key:"destroy",value:function(){this.viewer.scene.off(this._onModelLoaded),f(x(i.prototype),"destroy",this).call(this)}}]),i}(),dF=new Float64Array([0,0,1]),pF=new Float64Array(4),fF=function(){function e(t){B(this,e),this.id=null,this._viewer=t.viewer,this._plugin=t,this._visible=!1,this._pos=re.vec3(),this._origin=re.vec3(),this._rtcPos=re.vec3(),this._baseDir=re.vec3(),this._rootNode=null,this._displayMeshes=null,this._affordanceMeshes=null,this._ignoreNextSectionPlaneDirUpdate=!1,this._createNodes(),this._bindEvents()}return C(e,[{key:"_setSectionPlane",value:function(e){var t=this;this._sectionPlane&&(this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._onSectionPlanePos=null,this._onSectionPlaneDir=null,this._sectionPlane=null),e&&(this.id=e.id,this._setPos(e.pos),this._setDir(e.dir),this._sectionPlane=e,this._onSectionPlanePos=e.on("pos",(function(){t._setPos(t._sectionPlane.pos)})),this._onSectionPlaneDir=e.on("dir",(function(){t._ignoreNextSectionPlaneDirUpdate?t._ignoreNextSectionPlaneDirUpdate=!1:t._setDir(t._sectionPlane.dir)})))}},{key:"sectionPlane",get:function(){return this._sectionPlane}},{key:"_setPos",value:function(e){this._pos.set(e),He(this._pos,this._origin,this._rtcPos),this._rootNode.origin=this._origin,this._rootNode.position=this._rtcPos}},{key:"_setDir",value:function(e){this._baseDir.set(e),this._rootNode.quaternion=re.vec3PairToQuaternion(dF,e,pF)}},{key:"_setSectionPlaneDir",value:function(e){this._sectionPlane&&(this._ignoreNextSectionPlaneDirUpdate=!0,this._sectionPlane.dir=e)}},{key:"setVisible",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[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)}}},{key:"getVisible",value:function(){return this._visible}},{key:"setCulled",value:function(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)}},{key:"_createNodes",value:function(){var e=!1,t=this._viewer.scene,i=.01;this._rootNode=new Ln(t,{position:[0,0,0],scale:[5,5,5]});var r=this._rootNode,s={arrowHead:new Ki(r,yn({radiusTop:.001,radiusBottom:.07,radialSegments:32,heightSegments:1,height:.2,openEnded:!1})),arrowHeadBig:new Ki(r,yn({radiusTop:.001,radiusBottom:.09,radialSegments:32,heightSegments:1,height:.25,openEnded:!1})),axis:new Ki(r,yn({radiusTop:i,radiusBottom:i,radialSegments:20,heightSegments:1,height:1,openEnded:!1}))},n={red:new qi(r,{diffuse:[1,0,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),green:new qi(r,{diffuse:[0,1,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),blue:new qi(r,{diffuse:[0,0,1],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightRed:new er(r,{edges:!1,fill:!0,fillColor:[1,0,0],fillAlpha:.6})};this._displayMeshes={plane:r.addChild(new mn(r,{geometry:new Ki(r,{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 qi(r,{emissive:[0,0,0],diffuse:[0,0,0],backfaces:!0}),opacity:.6,ghosted:!0,pickable:!1,collidable:!0,clippable:!1,visible:!1,scale:[2.4,2.4,1]}),e),planeFrame:r.addChild(new mn(r,{geometry:new Ki(r,uo({center:[0,0,0],radius:1.7,tube:.02,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new qi(r,{emissive:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],shininess:0}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,.1],rotation:[0,0,45]}),e),center:r.addChild(new mn(r,{geometry:new Ki(r,bn({radius:.05})),material:n.center,pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),zAxisArrow:r.addChild(new mn(r,{geometry:s.arrowHead,material:n.blue,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[.8,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),zShaft:r.addChild(new mn(r,{geometry:s.axis,material:n.blue,matrix:function(){var e=re.translateMat4c(0,.5,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[1,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),clippable:!1,pickable:!1,collidable:!0,visible:!1}),e)},this._affordanceMeshes={planeFrame:r.addChild(new mn(r,{geometry:new Ki(r,uo({center:[0,0,0],radius:2,tube:i,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new qi(r,{ambient:[1,1,1],diffuse:[0,0,0],emissive:[1,1,0]}),highlighted:!0,highlightMaterial:new er(r,{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]}),e),zAxisArrow:r.addChild(new mn(r,{geometry:s.arrowHeadBig,material:n.blue,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[.8,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e)}}},{key:"_bindEvents",value:function(){var e=this,t=this._rootNode,i=re.vec2(),r=this._viewer.camera,s=this._viewer.scene,n=0,o=!1,a=re.vec3([0,0,0]),l=-1;this._onCameraViewMatrix=s.camera.on("viewMatrix",(function(){})),this._onCameraProjMatrix=s.camera.on("projMatrix",(function(){})),this._onSceneTick=s.on("tick",(function(){o=!1;var i=Math.abs(re.lenVec3(re.subVec3(s.camera.eye,e._pos,a)));if(i!==l&&"perspective"===r.projection){var u=.07*(Math.tan(r.perspective.fov*re.DEGTORAD)*i);t.scale=[u,u,u],l=i}if("ortho"===r.projection){var A=r.ortho.scale/10;t.scale=[A,A,A],l=i}0!==n&&(c(n),n=0)}));var u=function(){var e=new Float64Array(2);return function(t){if(t){for(var i=t.target,r=0,s=0;i.offsetParent;)r+=i.offsetLeft,s+=i.offsetTop,i=i.offsetParent;e[0]=t.pageX-r,e[1]=t.pageY-s}else t=window.event,e[0]=t.x,e[1]=t.y;return e}}(),c=function(t){var i=e._sectionPlane.pos,r=e._sectionPlane.dir;re.addVec3(i,re.mulVec3Scalar(r,.1*t*e._plugin.getDragSensitivity(),re.vec3())),e._sectionPlane.pos=i},A=!1;this._plugin._controlElement.addEventListener("mousedown",this._canvasMouseDownListener=function(t){if(t.preventDefault(),e._visible&&(e._viewer.cameraControl.pointerEnabled=!1,1===t.which)){A=!0;var r=u(t);i[0]=r[0],i[1]=r[1]}}),this._plugin._controlElement.addEventListener("mousemove",this._canvasMouseMoveListener=function(t){if(e._visible&&A&&!o){var r=u(t),s=r[0],n=r[1];c(n-i[1]),i[0]=s,i[1]=n}}),this._plugin._controlElement.addEventListener("mouseup",this._canvasMouseUpListener=function(t){e._visible&&(e._viewer.cameraControl.pointerEnabled=!0,A&&(t.which,A=!1))}),this._plugin._controlElement.addEventListener("wheel",this._canvasWheelListener=function(t){e._visible&&(n+=Math.max(-1,Math.min(1,40*-t.deltaY)))});var h,d,p=null;this._plugin._controlElement.addEventListener("touchstart",this._handleTouchStart=function(t){t.stopPropagation(),t.preventDefault(),e._visible&&(h=t.touches[0].clientY,p=h,n=0)}),this._plugin._controlElement.addEventListener("touchmove",this._handleTouchMove=function(t){t.stopPropagation(),t.preventDefault(),e._visible&&(o||(o=!0,d=t.touches[0].clientY,null!==p&&(n+=d-p),p=d))}),this._plugin._controlElement.addEventListener("touchend",this._handleTouchEnd=function(t){t.stopPropagation(),t.preventDefault(),e._visible&&(h=null,d=null,n=0)})}},{key:"_destroy",value:function(){this._unbindEvents(),this._destroyNodes()}},{key:"_unbindEvents",value:function(){var e=this._viewer,t=e.scene,i=t.canvas.canvas,r=e.camera,s=this._plugin._controlElement;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.removeEventListener("touchstart",this._handleTouchStart),s.removeEventListener("touchmove",this._handleTouchMove),s.removeEventListener("touchend",this._handleTouchEnd),r.off(this._onCameraViewMatrix),r.off(this._onCameraProjMatrix)}},{key:"_destroyNodes",value:function(){this._setSectionPlane(null),this._rootNode.destroy(),this._displayMeshes={},this._affordanceMeshes={}}}]),e}(),vF=function(){function e(t,i,r){var s=this;B(this,e),this.id=r.id,this._sectionPlane=r,this._mesh=new mn(i,{id:r.id,geometry:new Ki(i,Xi({xSize:.5,ySize:.5,zSize:.001})),material:new qi(i,{emissive:[1,1,1],diffuse:[0,0,0],backfaces:!1}),edgeMaterial:new ir(i,{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),highlightMaterial:new er(i,{fill:!0,fillColor:[.5,1,.5],fillAlpha:.7,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),selectedMaterial:new er(i,{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});var n=re.vec3([0,0,0]),o=re.vec3(),a=re.vec3([0,0,1]),l=re.vec4(4),u=re.vec3(),c=function(){var e=s._sectionPlane.scene.center,t=[-s._sectionPlane.dir[0],-s._sectionPlane.dir[1],-s._sectionPlane.dir[2]];re.subVec3(e,s._sectionPlane.pos,n);var i=-re.dotVec3(t,n);re.normalizeVec3(t),re.mulVec3Scalar(t,i,o);var r=re.vec3PairToQuaternion(a,s._sectionPlane.dir,l);u[0]=.1*o[0],u[1]=.1*o[1],u[2]=.1*o[2],s._mesh.quaternion=r,s._mesh.position=u};this._onSectionPlanePos=this._sectionPlane.on("pos",c),this._onSectionPlaneDir=this._sectionPlane.on("dir",c),this._highlighted=!1,this._selected=!1}return C(e,[{key:"setHighlighted",value:function(e){this._highlighted=!!e,this._mesh.highlighted=this._highlighted,this._mesh.highlightMaterial.fillColor=e?[0,.7,0]:[0,0,0]}},{key:"getHighlighted",value:function(){return this._highlighted}},{key:"setSelected",value:function(e){this._selected=!!e,this._mesh.edgeMaterial.edgeWidth=e?3:1,this._mesh.highlightMaterial.edgeWidth=e?3:1}},{key:"getSelected",value:function(){return this._selected}},{key:"destroy",value:function(){this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._mesh.destroy()}}]),e}(),gF=function(){function e(t,i){var r=this;if(B(this,e),!(i.onHoverEnterPlane&&i.onHoverLeavePlane&&i.onClickedNothing&&i.onClickedPlane))throw"Missing config(s): onHoverEnterPlane, onHoverLeavePlane, onClickedNothing || onClickedPlane";this.plugin=t,this._viewer=t.viewer,this._onHoverEnterPlane=i.onHoverEnterPlane,this._onHoverLeavePlane=i.onHoverLeavePlane,this._onClickedNothing=i.onClickedNothing,this._onClickedPlane=i.onClickedPlane,this._visible=!0,this._planes={},this._canvas=i.overviewCanvas,this._scene=new hr(this._viewer,{canvasId:this._canvas.id,transparent:!0}),this._scene.clearLights(),new Ti(this._scene,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new Ti(this._scene,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new Ti(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;var s=this._scene.camera,n=re.rotationMat4c(-90*re.DEGTORAD,1,0,0),o=re.vec3(),a=re.vec3(),l=re.vec3();this._synchCamera=function(){var e=r._viewer.camera.eye,t=r._viewer.camera.look,i=r._viewer.camera.up;re.mulVec3Scalar(re.normalizeVec3(re.subVec3(e,t,o)),7),r._zUp?(re.transformVec3(n,o,a),re.transformVec3(n,i,l),s.look=[0,0,0],s.eye=re.transformVec3(n,o,a),s.up=re.transformPoint3(n,i,l)):(s.look=[0,0,0],s.eye=o,s.up=i)},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",(function(e){r._scene.camera.perspective.fov=e}));var u=null;this._onInputMouseMove=this._scene.input.on("mousemove",(function(e){var t=r._scene.pick({canvasPos:e});if(t){if(!u||t.entity.id!==u.id){if(u)r._planes[u.id]&&r._onHoverLeavePlane(u.id);u=t.entity,r._planes[u.id]&&r._onHoverEnterPlane(u.id)}}else u&&(r._onHoverLeavePlane(u.id),u=null)})),this._scene.canvas.canvas.addEventListener("mouseup",this._onCanvasMouseUp=function(){u?r._planes[u.id]&&r._onClickedPlane(u.id):r._onClickedNothing()}),this._scene.canvas.canvas.addEventListener("mouseout",this._onCanvasMouseOut=function(){u&&(r._onHoverLeavePlane(u.id),u=null)}),this.setVisible(i.overviewVisible)}return C(e,[{key:"addSectionPlane",value:function(e){this._planes[e.id]=new vF(this,this._scene,e)}},{key:"setPlaneHighlighted",value:function(e,t){var i=this._planes[e];i&&i.setHighlighted(t)}},{key:"setPlaneSelected",value:function(e,t){var i=this._planes[e];i&&i.setSelected(t)}},{key:"removeSectionPlane",value:function(e){var t=this._planes[e.id];t&&(t.destroy(),delete this._planes[e.id])}},{key:"setVisible",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this._visible=e,this._canvas.style.visibility=e?"visible":"hidden"}},{key:"getVisible",value:function(){return this._visible}},{key:"destroy",value:function(){this._viewer.camera.off(this._onViewerCameraMatrix),this._viewer.camera.off(this._onViewerCameraWorldAxis),this._viewer.camera.perspective.off(this._onViewerCameraFOV),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()}}]),e}(),mF=re.AABB3(),_F=re.vec3(),yF=function(e){g(i,Ue);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(B(this,i),(r=t.call(this,"FaceAlignedSectionPlanesPlugin",e))._freeControls=[],r._sectionPlanes=e.scene.sectionPlanes,r._controls={},r._shownControlId=null,r._dragSensitivity=s.dragSensitivity||1,null!==s.overviewCanvasId&&void 0!==s.overviewCanvasId){var n=document.getElementById(s.overviewCanvasId);n?r._overview=new gF(b(r),{overviewCanvas:n,visible:s.overviewVisible,onHoverEnterPlane:function(e){r._overview.setPlaneHighlighted(e,!0)},onHoverLeavePlane:function(e){r._overview.setPlaneHighlighted(e,!1)},onClickedPlane:function(e){if(r.getShownControl()!==e){r.showControl(e);var t=r.sectionPlanes[e].pos;mF.set(r.viewer.scene.aabb),re.getAABB3Center(mF,_F),mF[0]+=t[0]-_F[0],mF[1]+=t[1]-_F[1],mF[2]+=t[2]-_F[2],mF[3]+=t[0]-_F[0],mF[4]+=t[1]-_F[1],mF[5]+=t[2]-_F[2],r.viewer.cameraFlight.flyTo({aabb:mF,fitFOV:65})}else r.hideControl()},onClickedNothing:function(){r.hideControl()}}):r.warn("Can't find overview canvas: '"+s.overviewCanvasId+"' - will create plugin without overview")}return null===s.controlElementId||void 0===s.controlElementId?r.error("Parameter expected: controlElementId"):(r._controlElement=document.getElementById(s.controlElementId),r._controlElement||r.warn("Can't find control element: '"+s.controlElementId+"' - will create plugin without control element")),r._onSceneSectionPlaneCreated=e.scene.on("sectionPlaneCreated",(function(e){r._sectionPlaneCreated(e)})),r}return C(i,[{key:"setDragSensitivity",value:function(e){this._dragSensitivity=e||1}},{key:"getDragSensitivity",value:function(){return this._dragSensitivity}},{key:"setOverviewVisible",value:function(e){this._overview&&this._overview.setVisible(e)}},{key:"getOverviewVisible",value:function(){if(this._overview)return this._overview.getVisible()}},{key:"sectionPlanes",get:function(){return this._sectionPlanes}},{key:"createSectionPlane",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};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);var t=new Pn(this.viewer.scene,{id:e.id,pos:e.pos,dir:e.dir,active:!0});return t}},{key:"_sectionPlaneCreated",value:function(e){var t=this,i=this._freeControls.length>0?this._freeControls.pop():new fF(this);i._setSectionPlane(e),i.setVisible(!1),this._controls[e.id]=i,this._overview&&this._overview.addSectionPlane(e),e.once("destroyed",(function(){t._sectionPlaneDestroyed(e)}))}},{key:"flipSectionPlanes",value:function(){var e=this.viewer.scene.sectionPlanes;for(var t in e){e[t].flipDir()}}},{key:"showControl",value:function(e){var 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)}},{key:"getShownControl",value:function(){return this._shownControlId}},{key:"hideControl",value:function(){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}},{key:"destroySectionPlane",value:function(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)}},{key:"_sectionPlaneDestroyed",value:function(e){this._overview&&this._overview.removeSectionPlane(e);var t=this._controls[e.id];t&&(t.setVisible(!1),t._setSectionPlane(null),delete this._controls[e.id],this._freeControls.push(t))}},{key:"clear",value:function(){for(var e=Object.keys(this._sectionPlanes),t=0,i=e.length;t0&&void 0!==arguments[0]?arguments[0]:{};B(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getSTL",value:function(e,t,i){e=this._cacheBusterURL(e);var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.responseType="arraybuffer",r.onreadystatechange=function(){4===r.readyState&&(200===r.status?t(r.response):i(r.statusText))},r.send(null)}}]),e}(),wF=re.vec3(),BF=function(){function e(){B(this,e)}return C(e,[{key:"load",value:function(e,t,i,r,s,n){r=r||{};var o=e.viewer.scene.canvas.spinner;o.processes++,e.dataSource.getSTL(i,(function(i){!function(e,t,i,r){try{var s=kF(i);PF(s)?CF(e,s,t,r):MF(e,FF(i),t,r)}catch(e){t.fire("error",e)}}(e,t,i,r);try{var a=kF(i);PF(a)?CF(e,a,t,r):MF(e,FF(i),t,r),o.processes--,we.scheduleTask((function(){t.fire("loaded",!0,!1)})),s&&s()}catch(i){o.processes--,e.error(i),n&&n(i),t.fire("error",i)}}),(function(i){o.processes--,e.error(i),n&&n(i),t.fire("error",i)}))}},{key:"parse",value:function(e,t,i,r){var s=e.viewer.scene.canvas.spinner;s.processes++;try{var n=kF(i);PF(n)?CF(e,n,t,r):MF(e,FF(i),t,r),s.processes--,we.scheduleTask((function(){t.fire("loaded",!0,!1)}))}catch(e){s.processes--,t.fire("error",e)}}}]),e}();function PF(e){var t=new DataView(e);if(84+50*t.getUint32(80,!0)===t.byteLength)return!0;for(var i=[115,111,108,105,100],r=0;r<5;r++)if(i[r]!==t.getUint8(r,!1))return!0;return!1}function CF(e,t,i,r){for(var s,n,o,a,l,u,c,A=new DataView(t),h=A.getUint32(80,!0),d=!1,p=null,f=null,v=null,g=!1,m=0;m<70;m++)1129270351===A.getUint32(m,!1)&&82===A.getUint8(m+4)&&61===A.getUint8(m+5)&&(d=!0,a=[],l=A.getUint8(m+6)/255,u=A.getUint8(m+7)/255,c=A.getUint8(m+8)/255,A.getUint8(m+9));for(var _=new Nn(i,{roughness:.5}),y=[],b=[],x=r.splitMeshes,w=0;w>5&31)/31,o=(E>>10&31)/31):(s=l,n=u,o=c),(x&&s!==p||n!==f||o!==v)&&(null!==p&&(g=!0),p=s,f=n,v=o)}for(var F=1;F<=3;F++){var k=B+12*F;y.push(A.getFloat32(k,!0)),y.push(A.getFloat32(k+4,!0)),y.push(A.getFloat32(k+8,!0)),b.push(P,C,M),d&&a.push(s,n,o,1)}x&&g&&(EF(i,y,b,a,_,r),y=[],b=[],a=a?[]:null,g=!1)}y.length>0&&EF(i,y,b,a,_,r)}function MF(e,t,i,r){for(var s,n,o,a,l,u,c,A=/facet([\s\S]*?)endfacet/g,h=0,d=/[\s]+([+-]?(?:\d+.\d+|\d+.|\d+|.\d+)(?:[eE][+-]?\d+)?)/.source,p=new RegExp("vertex"+d+d+d,"g"),f=new RegExp("normal"+d+d+d,"g"),v=[],g=[];null!==(a=A.exec(t));){for(l=0,u=0,c=a[0];null!==(a=f.exec(c));)s=parseFloat(a[1]),n=parseFloat(a[2]),o=parseFloat(a[3]),u++;for(;null!==(a=p.exec(c));)v.push(parseFloat(a[1]),parseFloat(a[2]),parseFloat(a[3])),g.push(s,n,o),l++;1!==u&&e.error("Error in normal of face "+h),3!==l&&e.error("Error in positions of face "+h),h++}EF(i,v,g,null,new Nn(i,{roughness:.5}),r)}function EF(e,t,i,r,s,n){for(var o=new Int32Array(t.length/3),a=0,l=o.length;a0?i:null,r=r&&r.length>0?r:null,n.smoothNormals&&re.faceToVertexNormals(t,i,n);var u=wF;je(t,t,u);var c=new Ki(e,{primitive:"triangles",positions:t,normals:i,colors:r,indices:o}),A=new mn(e,{origin:0!==u[0]||0!==u[1]||0!==u[2]?u:null,geometry:c,material:s,edges:n.edges});e.addChild(A)}function FF(e){return"string"!=typeof e?function(e){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);for(var t="",i=0,r=e.length;i1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),(r=t.call(this,"STLLoader",e,s))._sceneGraphLoader=new BF,r.dataSource=s.dataSource,r}return C(i,[{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new xF}},{key:"load",value:function(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);var t=new Ln(this.viewer.scene,he.apply(e,{isModel:!0})),i=e.src,r=e.stl;return i||r?(i?this._sceneGraphLoader.load(this,t,i,e):this._sceneGraphLoader.parse(this,t,r,e),t):(this.error("load() param expected: either 'src' or 'stl'"),t)}}]),i}(),DF=function(){function e(){B(this,e)}return C(e,[{key:"createRootNode",value:function(){return document.createElement("ul")}},{key:"createNodeElement",value:function(e,t,i,r,s){var n=document.createElement("li");if(n.id=e.nodeId,e.xrayed&&n.classList.add("xrayed-node"),e.children.length>0){var o=document.createElement("a");o.href="#",o.id="switch-".concat(e.nodeId),o.textContent="+",o.classList.add("plus"),t&&o.addEventListener("click",t),n.appendChild(o)}var a=document.createElement("input");a.id="checkbox-".concat(e.nodeId),a.type="checkbox",a.checked=e.checked,a.style["pointer-events"]="all",i&&a.addEventListener("change",i),n.appendChild(a);var l=document.createElement("span");return l.textContent=e.title,n.appendChild(l),r&&(l.oncontextmenu=r),s&&(l.onclick=s),n}},{key:"createDisabledNodeElement",value:function(e){var t=document.createElement("li"),i=document.createElement("a");i.href="#",i.textContent="!",i.classList.add("warn"),i.classList.add("warning"),t.appendChild(i);var r=document.createElement("span");return r.textContent=e,t.appendChild(r),t}},{key:"addChildren",value:function(e,t){var i=document.createElement("ul");t.forEach((function(e){i.appendChild(e)})),e.parentElement.appendChild(i)}},{key:"expand",value:function(e,t,i){e.classList.remove("plus"),e.classList.add("minus"),e.textContent="-",e.removeEventListener("click",t),e.addEventListener("click",i)}},{key:"collapse",value:function(e,t,i){if(e){var r=e.parentElement;if(r){var s=r.querySelector("ul");s&&(r.removeChild(s),e.classList.remove("minus"),e.classList.add("plus"),e.textContent="+",e.removeEventListener("click",i),e.addEventListener("click",t))}}}},{key:"isExpanded",value:function(e){return void 0!==e.parentElement.getElementsByTagName("li")[0]}},{key:"getId",value:function(e){return e.parentElement.id}},{key:"getIdFromCheckbox",value:function(e){return e.id.replace("checkbox-","")}},{key:"getSwitchElement",value:function(e){return document.getElementById("switch-".concat(e))}},{key:"isChecked",value:function(e){return e.checked}},{key:"setCheckbox",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=document.getElementById("checkbox-".concat(e));r&&(t!==r.checked&&(r.checked=t),i!==r.indeterminate&&(r.indeterminate=i,i&&(r.checked=!1)))}},{key:"setXRayed",value:function(e,t){var i=document.getElementById(e);i&&(t?i.classList.add("xrayed-node"):i.classList.remove("xrayed-node"))}},{key:"setHighlighted",value:function(e,t){var i=document.getElementById(e);i&&(t?(i.scrollIntoView({block:"center"}),i.classList.add("highlighted-node")):i.classList.remove("highlighted-node"))}}]),e}(),SF=[],TF=function(e){g(i,Ue);var t=_(i);function i(e){var r,s,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};B(this,i),(s=t.call(this,"TreeViewPlugin",e)).errors=[],s.valid=!0;var o=n.containerElement||document.getElementById(n.containerElementId);if(!(o instanceof HTMLElement))return s.error("Mandatory config expected: valid containerElementId or containerElement"),y(s);for(var a=0;;a++)if(!SF[a]){SF[a]=b(s),s._index=a,s._id="tree-".concat(a);break}if(s._containerElement=o,s._metaModels={},s._autoAddModels=!1!==n.autoAddModels,s._autoExpandDepth=n.autoExpandDepth||0,s._sortNodes=!1!==n.sortNodes,s._viewer=e,s._rootElement=null,s._muteSceneEvents=!1,s._muteTreeEvents=!1,s._rootNodes=[],s._objectNodes={},s._nodeNodes={},s._rootNames={},s._sortNodes=n.sortNodes,s._pruneEmptyNodes=n.pruneEmptyNodes,s._showListItemElementId=null,s._renderService=n.renderService||new DF,s._showIndeterminate=null!==(r=n.showIndeterminate)&&void 0!==r&&r,!s._renderService)throw new Error("TreeViewPlugin: no render service set");if(s._containerElement.oncontextmenu=function(e){e.preventDefault()},s._onObjectVisibility=s._viewer.scene.on("objectVisibility",(function(e){if(!s._muteSceneEvents){var t=e.id,i=s._objectNodes[t];if(i){var r=e.visible;if(r!==i.checked){s._muteTreeEvents=!0,i.checked=r,r?i.numVisibleEntities++:i.numVisibleEntities--,s._renderService.setCheckbox(i.nodeId,r);for(var n=i.parent;n;){n.checked=r,r?n.numVisibleEntities++:n.numVisibleEntities--;var o=s._showIndeterminate&&n.numVisibleEntities>0&&n.numVisibleEntities0,o),n=n.parent}s._muteTreeEvents=!1}}}})),s._onObjectXrayed=s._viewer.scene.on("objectXRayed",(function(e){if(!s._muteSceneEvents){var t=e.id,i=s._objectNodes[t];if(i){s._muteTreeEvents=!0;var r=e.xrayed;r!==i.xrayed&&(i.xrayed=r,s._renderService.setXRayed(i.nodeId,r),s._muteTreeEvents=!1)}}})),s._switchExpandHandler=function(e){e.preventDefault(),e.stopPropagation();var t=e.target;s._expandSwitchElement(t)},s._switchCollapseHandler=function(e){e.preventDefault(),e.stopPropagation();var t=e.target;s._collapseSwitchElement(t)},s._checkboxChangeHandler=function(e){if(!s._muteTreeEvents){s._muteSceneEvents=!0;var t=e.target,i=s._renderService.isChecked(t),r=s._renderService.getIdFromCheckbox(t),n=s._nodeNodes[r],o=s._viewer.scene.objects,a=0;s._withNodeTree(n,(function(e){var t=e.objectId,r=o[t],n=0===e.children.length;e.numVisibleEntities=i?e.numEntities:0,n&&i!==e.checked&&a++,e.checked=i,s._renderService.setCheckbox(e.nodeId,i),r&&(r.visible=i)}));for(var l=n.parent;l;){l.checked=i,i?l.numVisibleEntities+=a:l.numVisibleEntities-=a;var u=s._showIndeterminate&&l.numVisibleEntities>0&&l.numVisibleEntities0,u),l=l.parent}s._muteSceneEvents=!1}},s._hierarchy=n.hierarchy||"containment",s._autoExpandDepth=n.autoExpandDepth||0,s._autoAddModels){for(var l=Object.keys(s.viewer.metaScene.metaModels),u=0,c=l.length;u1&&void 0!==arguments[1]?arguments[1]:{};if(this._containerElement){var r=this.viewer.scene.models[e];if(!r)throw"Model not found: "+e;var s=this.viewer.metaScene.metaModels[e];s?this._metaModels[e]?this.warn("Model already added: "+e):(this._metaModels[e]=s,i&&i.rootName&&(this._rootNames[e]=i.rootName),r.on("destroyed",(function(){t.removeModel(r.id)})),this._createNodes()):this.error("MetaModel not found: "+e)}}},{key:"removeModel",value:function(e){this._containerElement&&(this._metaModels[e]&&(this._rootNames[e]&&delete this._rootNames[e],delete this._metaModels[e],this._createNodes()))}},{key:"showNode",value:function(e){this.unShowNode();var t=this._objectNodes[e];if(t){this.collapse();var i=t.nodeId,r=this._renderService.getSwitchElement(i);if(r)return this._expandSwitchElement(r),r.scrollIntoView(),!0;var s=[];s.unshift(t);for(var n=t.parent;n;)s.unshift(n),n=n.parent;for(var o=0,a=s.length;o0;return this.valid}},{key:"_validateMetaModelForStoreysHierarchy",value:function(){return!0}},{key:"_createEnabledNodes",value:function(){switch(this._pruneEmptyNodes&&this._findEmptyNodes(),this._hierarchy){case"storeys":this._createStoreysNodes(),0===this._rootNodes.length&&this.error("Failed to build storeys hierarchy");break;case"types":this._createTypesNodes();break;default:this._createContainmentNodes()}this._sortNodes&&this._doSortNodes(),this._synchNodesToEntities(),this._createTrees(),this.expandToDepth(this._autoExpandDepth)}},{key:"_createDisabledNodes",value:function(){var e=this._renderService.createRootNode();this._rootElement=e,this._containerElement.appendChild(e);var t=this._viewer.metaScene.rootMetaObjects;for(var i in t){var r=t[i],s=r.type,n=r.name,o=n&&""!==n&&"Undefined"!==n&&"Default"!==n?n:s,a=this._renderService.createDisabledNodeElement(o);e.appendChild(a)}}},{key:"_findEmptyNodes",value:function(){var e=this._viewer.metaScene.rootMetaObjects;for(var t in e)this._findEmptyNodes2(e[t])}},{key:"_findEmptyNodes2",value:function(e){var t=this.viewer,i=t.scene,r=e.children,s=e.id,n=i.objects[s];if(e._countEntities=0,n&&e._countEntities++,r)for(var o=0,a=r.length;os.aabb[n]?-1:e.aabb[n]r?1:0}},{key:"_synchNodesToEntities",value:function(){for(var e=Object.keys(this.viewer.metaScene.metaObjects),t=this._viewer.metaScene.metaObjects,i=this._viewer.scene.objects,r=0,s=e.length;r0){for(var e=0;e1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),(r=t.call(this,"ViewCull",e))._objectCullStates=UF(e.scene),r._maxTreeDepth=s.maxTreeDepth||8,r._modelInfos={},r._frustum=new Ie,r._kdRoot=null,r._frustumDirty=!1,r._kdTreeDirty=!1,r._onViewMatrix=e.scene.camera.on("viewMatrix",(function(){r._frustumDirty=!0})),r._onProjMatrix=e.scene.camera.on("projMatMatrix",(function(){r._frustumDirty=!0})),r._onModelLoaded=e.scene.on("modelLoaded",(function(e){var t=r.viewer.scene.models[e];t&&r._addModel(t)})),r._onSceneTick=e.scene.on("tick",(function(){r._doCull()})),r}return C(i,[{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"_addModel",value:function(e){var t=this,i={model:e,onDestroyed:e.on("destroyed",(function(){t._removeModel(e)}))};this._modelInfos[e.id]=i,this._kdTreeDirty=!0}},{key:"_removeModel",value:function(e){var t=this._modelInfos[e.id];t&&(t.model.off(t.onDestroyed),delete this._modelInfos[e.id],this._kdTreeDirty=!0)}},{key:"_doCull",value:function(){var e=this._frustumDirty||this._kdTreeDirty;if(this._frustumDirty&&this._buildFrustum(),this._kdTreeDirty&&this._buildKDTree(),e){var t=this._kdRoot;t&&this._visitKDNode(t)}}},{key:"_buildFrustum",value:function(){var e=this.viewer.scene.camera;De(this._frustum,e.viewMatrix,e.projMatrix),this._frustumDirty=!1}},{key:"_buildKDTree",value:function(){var e=this.viewer.scene;this._kdRoot,this._kdRoot={aabb:e.getAABB(),intersection:Ie.INTERSECT};for(var t=0,i=this._objectCullStates.numObjects;t=this._maxTreeDepth)return e.objects=e.objects||[],e.objects.push(i),void re.expandAABB3(e.aabb,s);if(e.left&&re.containsAABB3(e.left.aabb,s))this._insertEntityIntoKDTree(e.left,t,i,r+1);else if(e.right&&re.containsAABB3(e.right.aabb,s))this._insertEntityIntoKDTree(e.right,t,i,r+1);else{var n=e.aabb;OF[0]=n[3]-n[0],OF[1]=n[4]-n[1],OF[2]=n[5]-n[2];var o=0;if(OF[1]>OF[o]&&(o=1),OF[2]>OF[o]&&(o=2),!e.left){var a=n.slice();if(a[o+3]=(n[o]+n[o+3])/2,e.left={aabb:a,intersection:Ie.INTERSECT},re.containsAABB3(a,s))return void this._insertEntityIntoKDTree(e.left,t,i,r+1)}if(!e.right){var l=n.slice();if(l[o]=(n[o]+n[o+3])/2,e.right={aabb:l,intersection:Ie.INTERSECT},re.containsAABB3(l,s))return void this._insertEntityIntoKDTree(e.right,t,i,r+1)}e.objects=e.objects||[],e.objects.push(i),re.expandAABB3(e.aabb,s)}}},{key:"_visitKDNode",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ie.INTERSECT;if(t===Ie.INTERSECT||e.intersects!==t){t===Ie.INTERSECT&&(t=Se(this._frustum,e.aabb),e.intersects=t);var i=t===Ie.OUTSIDE,r=e.objects;if(r&&r.length>0)for(var s=0,n=r.length;s0&&void 0!==arguments[0]?arguments[0]:{};B(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getManifest",value:function(e,t,i){he.loadJSON(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}},{key:"getMetaModel",value:function(e,t,i){he.loadJSON(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}},{key:"getXKT",value:function(e,t,i){var r=function(){};t=t||r,i=i||r;var s=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(s){var n=!!s[2],o=s[3];o=window.decodeURIComponent(o),n&&(o=window.atob(o));try{for(var a=new ArrayBuffer(o.length),l=new Uint8Array(a),u=0;u=0;)e[t]=0}var i=new Uint8Array([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]),r=new Uint8Array([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]),s=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),n=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),o=new Array(576);t(o);var a=new Array(60);t(a);var l=new Array(512);t(l);var u=new Array(256);t(u);var c=new Array(29);t(c);var A,h,d,p=new Array(30);function f(e,t,i,r,s){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=r,this.max_length=s,this.has_stree=e&&e.length}function v(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}t(p);var g=function(e){return e<256?l[e]:l[256+(e>>>7)]},m=function(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},_=function(e,t,i){e.bi_valid>16-i?(e.bi_buf|=t<>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<>>=1,i<<=1}while(--t>0);return i>>>1},x=function(e,t,i){var r,s,n=new Array(16),o=0;for(r=1;r<=15;r++)o=o+i[r-1]<<1,n[r]=o;for(s=0;s<=t;s++){var a=e[2*s+1];0!==a&&(e[2*s]=b(n[a]++,a))}},B=function(e){var t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},P=function(e){e.bi_valid>8?m(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},C=function(e,t,i,r){var s=2*t,n=2*i;return e[s]>1;i>=1;i--)M(e,n,i);s=l;do{i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],M(e,n,1),r=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=r,n[2*s]=n[2*i]+n[2*r],e.depth[s]=(e.depth[i]>=e.depth[r]?e.depth[i]:e.depth[r])+1,n[2*i+1]=n[2*r+1]=s,e.heap[1]=s++,M(e,n,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var i,r,s,n,o,a,l=t.dyn_tree,u=t.max_code,c=t.stat_desc.static_tree,A=t.stat_desc.has_stree,h=t.stat_desc.extra_bits,d=t.stat_desc.extra_base,p=t.stat_desc.max_length,f=0;for(n=0;n<=15;n++)e.bl_count[n]=0;for(l[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;i<573;i++)(n=l[2*l[2*(r=e.heap[i])+1]+1]+1)>p&&(n=p,f++),l[2*r+1]=n,r>u||(e.bl_count[n]++,o=0,r>=d&&(o=h[r-d]),a=l[2*r],e.opt_len+=a*(n+o),A&&(e.static_len+=a*(c[2*r+1]+o)));if(0!==f){do{for(n=p-1;0===e.bl_count[n];)n--;e.bl_count[n]--,e.bl_count[n+1]+=2,e.bl_count[p]--,f-=2}while(f>0);for(n=p;0!==n;n--)for(r=e.bl_count[n];0!==r;)(s=e.heap[--i])>u||(l[2*s+1]!==n&&(e.opt_len+=(n-l[2*s+1])*l[2*s],l[2*s+1]=n),r--)}}(e,t),x(n,u,e.bl_count)},k=function(e,t,i){var r,s,n=-1,o=t[1],a=0,l=7,u=4;for(0===o&&(l=138,u=3),t[2*(i+1)+1]=65535,r=0;r<=i;r++)s=o,o=t[2*(r+1)+1],++a>=7;v<30;v++)for(p[v]=g<<7,e=0;e<1<0?(2===e.strm.data_type&&(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 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0}(e)),F(e,e.l_desc),F(e,e.d_desc),u=function(e){var t;for(k(e,e.dyn_ltree,e.l_desc.max_code),k(e,e.dyn_dtree,e.d_desc.max_code),F(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*n[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),s=e.opt_len+3+7>>>3,(l=e.static_len+3+7>>>3)<=s&&(s=l)):s=l=i+5,i+4<=s&&-1!==t?S(e,t,i,r):4===e.strategy||l===s?(_(e,2+(r?1:0),3),E(e,o,a)):(_(e,4+(r?1:0),3),function(e,t,i,r){var s;for(_(e,t-257,5),_(e,i-1,5),_(e,r-4,4),s=0;s>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(u[i]+256+1)]++,e.dyn_dtree[2*g(t)]++),e.sym_next===e.sym_end},O=function(e){_(e,2,3),y(e,256,o),function(e){16===e.bi_valid?(m(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)},N=function(e,t,i,r){for(var s=65535&e|0,n=e>>>16&65535|0,o=0;0!==i;){i-=o=i>2e3?2e3:i;do{n=n+(s=s+t[r++]|0)|0}while(--o);s%=65521,n%=65521}return s|n<<16|0},Q=new Uint32Array(function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var r=0;r<8;r++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}()),V=function(e,t,i,r){var s=Q,n=r+i;e^=-1;for(var o=r;o>>8^s[255&(e^t[o])];return-1^e},H={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"},j={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_MEM_ERROR:-4,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},G=T,z=L,W=R,K=U,X=O,J=j.Z_NO_FLUSH,Y=j.Z_PARTIAL_FLUSH,Z=j.Z_FULL_FLUSH,q=j.Z_FINISH,$=j.Z_BLOCK,ee=j.Z_OK,te=j.Z_STREAM_END,ie=j.Z_STREAM_ERROR,re=j.Z_DATA_ERROR,se=j.Z_BUF_ERROR,ne=j.Z_DEFAULT_COMPRESSION,oe=j.Z_FILTERED,ae=j.Z_HUFFMAN_ONLY,le=j.Z_RLE,ue=j.Z_FIXED,ce=j.Z_UNKNOWN,Ae=j.Z_DEFLATED,he=258,de=262,pe=42,fe=113,ve=666,ge=function(e,t){return e.msg=H[t],t},me=function(e){return 2*e-(e>4?9:0)},_e=function(e){for(var t=e.length;--t>=0;)e[t]=0},ye=function(e){var t,i,r,s=e.w_size;r=t=e.hash_size;do{i=e.head[--r],e.head[r]=i>=s?i-s:0}while(--t);r=t=s;do{i=e.prev[--r],e.prev[r]=i>=s?i-s:0}while(--t)},be=function(e,t,i){return(t<e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,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))},we=function(e,t){W(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,xe(e.strm)},Be=function(e,t){e.pending_buf[e.pending++]=t},Pe=function(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},Ce=function(e,t,i,r){var s=e.avail_in;return s>r&&(s=r),0===s?0:(e.avail_in-=s,t.set(e.input.subarray(e.next_in,e.next_in+s),i),1===e.state.wrap?e.adler=N(e.adler,t,s,i):2===e.state.wrap&&(e.adler=V(e.adler,t,s,i)),e.next_in+=s,e.total_in+=s,s)},Me=function(e,t){var i,r,s=e.max_chain_length,n=e.strstart,o=e.prev_length,a=e.nice_match,l=e.strstart>e.w_size-de?e.strstart-(e.w_size-de):0,u=e.window,c=e.w_mask,A=e.prev,h=e.strstart+he,d=u[n+o-1],p=u[n+o];e.prev_length>=e.good_match&&(s>>=2),a>e.lookahead&&(a=e.lookahead);do{if(u[(i=t)+o]===p&&u[i+o-1]===d&&u[i]===u[n]&&u[++i]===u[n+1]){n+=2,i++;do{}while(u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&no){if(e.match_start=t,o=r,r>=a)break;d=u[n+o-1],p=u[n+o]}}}while((t=A[t&c])>l&&0!=--s);return o<=e.lookahead?o:e.lookahead},Ee=function(e){var t,i,r,s=e.w_size;do{if(i=e.window_size-e.lookahead-e.strstart,e.strstart>=s+(s-de)&&(e.window.set(e.window.subarray(s,s+s-i),0),e.match_start-=s,e.strstart-=s,e.block_start-=s,e.insert>e.strstart&&(e.insert=e.strstart),ye(e),i+=s),0===e.strm.avail_in)break;if(t=Ce(e.strm,e.window,e.strstart+e.lookahead,i),e.lookahead+=t,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=be(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=be(e,e.ins_h,e.window[r+3-1]),e.prev[r&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=r,r++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookaheade.w_size?e.w_size:e.pending_buf_size-5,o=0,a=e.strm.avail_in;do{if(i=65535,s=e.bi_valid+42>>3,e.strm.avail_out(r=e.strstart-e.block_start)+e.strm.avail_in&&(i=r+e.strm.avail_in),i>s&&(i=s),i>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,xe(e.strm),r&&(r>i&&(r=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+r),e.strm.next_out),e.strm.next_out+=r,e.strm.avail_out-=r,e.strm.total_out+=r,e.block_start+=r,i-=r),i&&(Ce(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i)}while(0===o);return(a-=e.strm.avail_in)&&(a>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=a&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-a,e.strm.next_in),e.strstart),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.block_start=e.strstart),e.high_waters&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,s+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),s>e.strm.avail_in&&(s=e.strm.avail_in),s&&(Ce(e.strm,e.window,e.strstart,s),e.strstart+=s,e.insert+=s>e.w_size-e.insert?e.w_size-e.insert:s),e.high_water>3,n=(s=e.pending_buf_size-s>65535?65535:e.pending_buf_size-s)>e.w_size?e.w_size:s,((r=e.strstart-e.block_start)>=n||(r||t===q)&&t!==J&&0===e.strm.avail_in&&r<=s)&&(i=r>s?s:r,o=t===q&&0===e.strm.avail_in&&i===r?1:0,z(e,e.block_start,i,o),e.block_start+=i,xe(e.strm)),o?3:1)},ke=function(e,t){for(var i,r;;){if(e.lookahead=3&&(e.ins_h=be(e,e.ins_h,e.window[e.strstart+3-1]),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-de&&(e.match_length=Me(e,i)),e.match_length>=3)if(r=K(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=be(e,e.ins_h,e.window[e.strstart+3-1]),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=be(e,e.ins_h,e.window[e.strstart+1]);else r=K(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(r&&(we(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===q?(we(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(we(e,!1),0===e.strm.avail_out)?1:2},Ie=function(e,t){for(var i,r,s;;){if(e.lookahead=3&&(e.ins_h=be(e,e.ins_h,e.window[e.strstart+3-1]),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=2,0!==i&&e.prev_length4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){s=e.strstart+e.lookahead-3,r=K(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=s&&(e.ins_h=be(e,e.ins_h,e.window[e.strstart+3-1]),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=2,e.strstart++,r&&(we(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if((r=K(e,0,e.window[e.strstart-1]))&&we(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(r=K(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===q?(we(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(we(e,!1),0===e.strm.avail_out)?1:2};function De(e,t,i,r,s){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=r,this.func=s}var Se=[new De(0,0,0,0,Fe),new De(4,4,8,4,ke),new De(4,5,16,8,ke),new De(4,6,32,32,ke),new De(4,4,16,16,Ie),new De(8,16,32,32,Ie),new De(8,16,128,128,Ie),new De(8,32,128,256,Ie),new De(32,128,258,1024,Ie),new De(32,258,258,4096,Ie)];function Te(){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=Ae,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 Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),_e(this.dyn_ltree),_e(this.dyn_dtree),_e(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),_e(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),_e(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}var Le=function(e){if(!e)return 1;var t=e.state;return!t||t.strm!==e||t.status!==pe&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==fe&&t.status!==ve?1:0},Re=function(e){if(Le(e))return ge(e,ie);e.total_in=e.total_out=0,e.data_type=ce;var t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?pe:fe,e.adler=2===t.wrap?0:1,t.last_flush=-2,G(t),ee},Ue=function(e){var t,i=Re(e);return i===ee&&((t=e.state).window_size=2*t.w_size,_e(t.head),t.max_lazy_match=Se[t.level].max_lazy,t.good_match=Se[t.level].good_length,t.nice_match=Se[t.level].nice_length,t.max_chain_length=Se[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=2,t.match_available=0,t.ins_h=0),i},Oe=function(e,t,i,r,s,n){if(!e)return ie;var o=1;if(t===ne&&(t=6),r<0?(o=0,r=-r):r>15&&(o=2,r-=16),s<1||s>9||i!==Ae||r<8||r>15||t<0||t>9||n<0||n>ue||8===r&&1!==o)return ge(e,ie);8===r&&(r=9);var a=new Te;return e.state=a,a.strm=e,a.status=pe,a.wrap=o,a.gzhead=null,a.w_bits=r,a.w_size=1<$||t<0)return e?ge(e,ie):ie;var i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===ve&&t!==q)return ge(e,0===e.avail_out?se:ie);var r=i.last_flush;if(i.last_flush=t,0!==i.pending){if(xe(e),0===e.avail_out)return i.last_flush=-1,ee}else if(0===e.avail_in&&me(t)<=me(r)&&t!==q)return ge(e,se);if(i.status===ve&&0!==e.avail_in)return ge(e,se);if(i.status===pe&&0===i.wrap&&(i.status=fe),i.status===pe){var s=Ae+(i.w_bits-8<<4)<<8;if(s|=(i.strategy>=ae||i.level<2?0:i.level<6?1:6===i.level?2:3)<<6,0!==i.strstart&&(s|=32),Pe(i,s+=31-s%31),0!==i.strstart&&(Pe(i,e.adler>>>16),Pe(i,65535&e.adler)),e.adler=1,i.status=fe,xe(e),0!==i.pending)return i.last_flush=-1,ee}if(57===i.status)if(e.adler=0,Be(i,31),Be(i,139),Be(i,8),i.gzhead)Be(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),Be(i,255&i.gzhead.time),Be(i,i.gzhead.time>>8&255),Be(i,i.gzhead.time>>16&255),Be(i,i.gzhead.time>>24&255),Be(i,9===i.level?2:i.strategy>=ae||i.level<2?4:0),Be(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(Be(i,255&i.gzhead.extra.length),Be(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=V(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(Be(i,0),Be(i,0),Be(i,0),Be(i,0),Be(i,0),Be(i,9===i.level?2:i.strategy>=ae||i.level<2?4:0),Be(i,3),i.status=fe,xe(e),0!==i.pending)return i.last_flush=-1,ee;if(69===i.status){if(i.gzhead.extra){for(var n=i.pending,o=(65535&i.gzhead.extra.length)-i.gzindex;i.pending+o>i.pending_buf_size;){var a=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+a),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>n&&(e.adler=V(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex+=a,xe(e),0!==i.pending)return i.last_flush=-1,ee;n=0,o-=a}var l=new Uint8Array(i.gzhead.extra);i.pending_buf.set(l.subarray(i.gzindex,i.gzindex+o),i.pending),i.pending+=o,i.gzhead.hcrc&&i.pending>n&&(e.adler=V(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){var u,c=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>c&&(e.adler=V(e.adler,i.pending_buf,i.pending-c,c)),xe(e),0!==i.pending)return i.last_flush=-1,ee;c=0}u=i.gzindexc&&(e.adler=V(e.adler,i.pending_buf,i.pending-c,c)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){var A,h=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>h&&(e.adler=V(e.adler,i.pending_buf,i.pending-h,h)),xe(e),0!==i.pending)return i.last_flush=-1,ee;h=0}A=i.gzindexh&&(e.adler=V(e.adler,i.pending_buf,i.pending-h,h))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(xe(e),0!==i.pending))return i.last_flush=-1,ee;Be(i,255&e.adler),Be(i,e.adler>>8&255),e.adler=0}if(i.status=fe,xe(e),0!==i.pending)return i.last_flush=-1,ee}if(0!==e.avail_in||0!==i.lookahead||t!==J&&i.status!==ve){var d=0===i.level?Fe(i,t):i.strategy===ae?function(e,t){for(var i;;){if(0===e.lookahead&&(Ee(e),0===e.lookahead)){if(t===J)return 1;break}if(e.match_length=0,i=K(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(we(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===q?(we(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(we(e,!1),0===e.strm.avail_out)?1:2}(i,t):i.strategy===le?function(e,t){for(var i,r,s,n,o=e.window;;){if(e.lookahead<=he){if(Ee(e),e.lookahead<=he&&t===J)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&((r=o[s=e.strstart-1])===o[++s]&&r===o[++s]&&r===o[++s])){n=e.strstart+he;do{}while(r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&se.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=K(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=K(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(we(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===q?(we(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(we(e,!1),0===e.strm.avail_out)?1:2}(i,t):Se[i.level].func(i,t);if(3!==d&&4!==d||(i.status=ve),1===d||3===d)return 0===e.avail_out&&(i.last_flush=-1),ee;if(2===d&&(t===Y?X(i):t!==$&&(z(i,0,0,!1),t===Z&&(_e(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),xe(e),0===e.avail_out))return i.last_flush=-1,ee}return t!==q?ee:i.wrap<=0?te:(2===i.wrap?(Be(i,255&e.adler),Be(i,e.adler>>8&255),Be(i,e.adler>>16&255),Be(i,e.adler>>24&255),Be(i,255&e.total_in),Be(i,e.total_in>>8&255),Be(i,e.total_in>>16&255),Be(i,e.total_in>>24&255)):(Pe(i,e.adler>>>16),Pe(i,65535&e.adler)),xe(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?ee:te)},He=function(e){if(Le(e))return ie;var t=e.state.status;return e.state=null,t===fe?ge(e,re):ee},je=function(e,t){var i=t.length;if(Le(e))return ie;var r=e.state,s=r.wrap;if(2===s||1===s&&r.status!==pe||r.lookahead)return ie;if(1===s&&(e.adler=N(e.adler,t,i,0)),r.wrap=0,i>=r.w_size){0===s&&(_e(r.head),r.strstart=0,r.block_start=0,r.insert=0);var n=new Uint8Array(r.w_size);n.set(t.subarray(i-r.w_size,i),0),t=n,i=r.w_size}var o=e.avail_in,a=e.next_in,l=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,Ee(r);r.lookahead>=3;){var u=r.strstart,c=r.lookahead-2;do{r.ins_h=be(r,r.ins_h,r.window[u+3-1]),r.prev[u&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=u,u++}while(--c);r.strstart=u,r.lookahead=2,Ee(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=2,r.match_available=0,e.next_in=a,e.input=l,e.avail_in=o,r.wrap=s,ee},Ge=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},ze=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var i=t.shift();if(i){if("object"!=w(i))throw new TypeError(i+"must be non-object");for(var r in i)Ge(i,r)&&(e[r]=i[r])}}return e},We=function(e){for(var t=0,i=0,r=e.length;i=252?6:Je>=248?5:Je>=240?4:Je>=224?3:Je>=192?2:1;Xe[254]=Xe[254]=1;var Ye=function(e){if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);var t,i,r,s,n,o=e.length,a=0;for(s=0;s>>6,t[n++]=128|63&i):i<65536?(t[n++]=224|i>>>12,t[n++]=128|i>>>6&63,t[n++]=128|63&i):(t[n++]=240|i>>>18,t[n++]=128|i>>>12&63,t[n++]=128|i>>>6&63,t[n++]=128|63&i);return t},Ze=function(e,t){var i,r,s=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));var n=new Array(2*s);for(r=0,i=0;i4)n[r++]=65533,i+=a-1;else{for(o&=2===a?31:3===a?15:7;a>1&&i1?n[r++]=65533:o<65536?n[r++]=o:(o-=65536,n[r++]=55296|o>>10&1023,n[r++]=56320|1023&o)}}}return function(e,t){if(t<65534&&e.subarray&&Ke)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));for(var i="",r=0;re.length&&(t=e.length);for(var i=t-1;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+Xe[e[i]]>t?i:t},$e=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},et=Object.prototype.toString,tt=j.Z_NO_FLUSH,it=j.Z_SYNC_FLUSH,rt=j.Z_FULL_FLUSH,st=j.Z_FINISH,nt=j.Z_OK,ot=j.Z_STREAM_END,at=j.Z_DEFAULT_COMPRESSION,lt=j.Z_DEFAULT_STRATEGY,ut=j.Z_DEFLATED;function ct(e){this.options=ze({level:at,method:ut,chunkSize:16384,windowBits:15,memLevel:8,strategy:lt},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 $e,this.strm.avail_out=0;var i=Ne(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==nt)throw new Error(H[i]);if(t.header&&Qe(this.strm,t.header),t.dictionary){var r;if(r="string"==typeof t.dictionary?Ye(t.dictionary):"[object ArrayBuffer]"===et.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(i=je(this.strm,r))!==nt)throw new Error(H[i]);this._dict_set=!0}}function At(e,t){var i=new ct(t);if(i.push(e,!0),i.err)throw i.msg||H[i.err];return i.result}ct.prototype.push=function(e,t){var i,r,s=this.strm,n=this.options.chunkSize;if(this.ended)return!1;for(r=t===~~t?t:!0===t?st:tt,"string"==typeof e?s.input=Ye(e):"[object ArrayBuffer]"===et.call(e)?s.input=new Uint8Array(e):s.input=e,s.next_in=0,s.avail_in=s.input.length;;)if(0===s.avail_out&&(s.output=new Uint8Array(n),s.next_out=0,s.avail_out=n),(r===it||r===rt)&&s.avail_out<=6)this.onData(s.output.subarray(0,s.next_out)),s.avail_out=0;else{if((i=Ve(s,r))===ot)return s.next_out>0&&this.onData(s.output.subarray(0,s.next_out)),i=He(this.strm),this.onEnd(i),this.ended=!0,i===nt;if(0!==s.avail_out){if(r>0&&s.next_out>0)this.onData(s.output.subarray(0,s.next_out)),s.avail_out=0;else if(0===s.avail_in)break}else this.onData(s.output)}return!0},ct.prototype.onData=function(e){this.chunks.push(e)},ct.prototype.onEnd=function(e){e===nt&&(this.result=We(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var ht=ct,dt=At,pt=function(e,t){return(t=t||{}).raw=!0,At(e,t)},ft=function(e,t){return(t=t||{}).gzip=!0,At(e,t)},vt=16209,gt=function(e,t){var i,r,s,n,o,a,l,u,c,A,h,d,p,f,v,g,m,_,y,b,x,w,B,P,C=e.state;i=e.next_in,B=e.input,r=i+(e.avail_in-5),s=e.next_out,P=e.output,n=s-(t-e.avail_out),o=s+(e.avail_out-257),a=C.dmax,l=C.wsize,u=C.whave,c=C.wnext,A=C.window,h=C.hold,d=C.bits,p=C.lencode,f=C.distcode,v=(1<>>=_=m>>>24,d-=_,0===(_=m>>>16&255))P[s++]=65535&m;else{if(!(16&_)){if(0==(64&_)){m=p[(65535&m)+(h&(1<<_)-1)];continue t}if(32&_){C.mode=16191;break e}e.msg="invalid literal/length code",C.mode=vt;break e}y=65535&m,(_&=15)&&(d<_&&(h+=B[i++]<>>=_,d-=_),d<15&&(h+=B[i++]<>>=_=m>>>24,d-=_,!(16&(_=m>>>16&255))){if(0==(64&_)){m=f[(65535&m)+(h&(1<<_)-1)];continue i}e.msg="invalid distance code",C.mode=vt;break e}if(b=65535&m,d<(_&=15)&&(h+=B[i++]<a){e.msg="invalid distance too far back",C.mode=vt;break e}if(h>>>=_,d-=_,b>(_=s-n)){if((_=b-_)>u&&C.sane){e.msg="invalid distance too far back",C.mode=vt;break e}if(x=0,w=A,0===c){if(x+=l-_,_2;)P[s++]=w[x++],P[s++]=w[x++],P[s++]=w[x++],y-=3;y&&(P[s++]=w[x++],y>1&&(P[s++]=w[x++]))}else{x=s-b;do{P[s++]=P[x++],P[s++]=P[x++],P[s++]=P[x++],y-=3}while(y>2);y&&(P[s++]=P[x++],y>1&&(P[s++]=P[x++]))}break}}break}}while(i>3,h&=(1<<(d-=y<<3))-1,e.next_in=i,e.next_out=s,e.avail_in=i=1&&0===F[b];b--);if(x>b&&(x=b),0===b)return s[n++]=20971520,s[n++]=20971520,a.bits=1,0;for(y=1;y0&&(0===e||1!==b))return-1;for(k[1]=0,m=1;m<15;m++)k[m+1]=k[m]+F[m];for(_=0;_852||2===e&&C>592)return 1;for(;;){p=m-B,o[_]+1=d?(f=I[o[_]-d],v=E[o[_]-d]):(f=96,v=0),l=1<>B)+(u-=l)]=p<<24|f<<16|v|0}while(0!==u);for(l=1<>=1;if(0!==l?(M&=l-1,M+=l):M=0,_++,0==--F[m]){if(m===b)break;m=t[i+o[_]]}if(m>x&&(M&A)!==c){for(0===B&&(B=x),h+=y,P=1<<(w=m-B);w+B852||2===e&&C>592)return 1;s[c=M&A]=x<<24|w<<16|h-n|0}}return 0!==M&&(s[h+M]=m-B<<24|64<<16|0),a.bits=x,0},wt=j.Z_FINISH,Bt=j.Z_BLOCK,Pt=j.Z_TREES,Ct=j.Z_OK,Mt=j.Z_STREAM_END,Et=j.Z_NEED_DICT,Ft=j.Z_STREAM_ERROR,kt=j.Z_DATA_ERROR,It=j.Z_MEM_ERROR,Dt=j.Z_BUF_ERROR,St=j.Z_DEFLATED,Tt=16180,Lt=16190,Rt=16191,Ut=16192,Ot=16194,Nt=16199,Qt=16200,Vt=16206,Ht=16209,jt=function(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)};function Gt(){this.strm=null,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 Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}var zt,Wt,Kt=function(e){if(!e)return 1;var t=e.state;return!t||t.strm!==e||t.mode16211?1:0},Xt=function(e){if(Kt(e))return Ft;var t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=Tt,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,Ct},Jt=function(e){if(Kt(e))return Ft;var t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,Xt(e)},Yt=function(e,t){var i;if(Kt(e))return Ft;var r=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?Ft:(null!==r.window&&r.wbits!==t&&(r.window=null),r.wrap=i,r.wbits=t,Jt(e))},Zt=function(e,t){if(!e)return Ft;var i=new Gt;e.state=i,i.strm=e,i.window=null,i.mode=Tt;var r=Yt(e,t);return r!==Ct&&(e.state=null),r},qt=!0,$t=function(e){if(qt){zt=new Int32Array(512),Wt=new Int32Array(32);for(var 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(xt(1,e.lens,0,288,zt,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;xt(2,e.lens,0,32,Wt,0,e.work,{bits:5}),qt=!1}e.lencode=zt,e.lenbits=9,e.distcode=Wt,e.distbits=5},ei=function(e,t,i,r){var s,n=e.state;return null===n.window&&(n.wsize=1<=n.wsize?(n.window.set(t.subarray(i-n.wsize,i),0),n.wnext=0,n.whave=n.wsize):((s=n.wsize-n.wnext)>r&&(s=r),n.window.set(t.subarray(i-r,i-r+s),n.wnext),(r-=s)?(n.window.set(t.subarray(i-r,i),0),n.wnext=r,n.whave=n.wsize):(n.wnext+=s,n.wnext===n.wsize&&(n.wnext=0),n.whave>>8&255,i.check=V(i.check,M,2,0),u=0,c=0,i.mode=16181;break}if(i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&u)<<8)+(u>>8))%31){e.msg="incorrect header check",i.mode=Ht;break}if((15&u)!==St){e.msg="unknown compression method",i.mode=Ht;break}if(c-=4,x=8+(15&(u>>>=4)),0===i.wbits&&(i.wbits=x),x>15||x>i.wbits){e.msg="invalid window size",i.mode=Ht;break}i.dmax=1<>8&1),512&i.flags&&4&i.wrap&&(M[0]=255&u,M[1]=u>>>8&255,i.check=V(i.check,M,2,0)),u=0,c=0,i.mode=16182;case 16182:for(;c<32;){if(0===a)break e;a--,u+=r[n++]<>>8&255,M[2]=u>>>16&255,M[3]=u>>>24&255,i.check=V(i.check,M,4,0)),u=0,c=0,i.mode=16183;case 16183:for(;c<16;){if(0===a)break e;a--,u+=r[n++]<>8),512&i.flags&&4&i.wrap&&(M[0]=255&u,M[1]=u>>>8&255,i.check=V(i.check,M,2,0)),u=0,c=0,i.mode=16184;case 16184:if(1024&i.flags){for(;c<16;){if(0===a)break e;a--,u+=r[n++]<>>8&255,i.check=V(i.check,M,2,0)),u=0,c=0}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&i.flags&&((d=i.length)>a&&(d=a),d&&(i.head&&(x=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(r.subarray(n,n+d),x)),512&i.flags&&4&i.wrap&&(i.check=V(i.check,r,d,n)),a-=d,n+=d,i.length-=d),i.length))break e;i.length=0,i.mode=16186;case 16186:if(2048&i.flags){if(0===a)break e;d=0;do{x=r[n+d++],i.head&&x&&i.length<65536&&(i.head.name+=String.fromCharCode(x))}while(x&&d>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=Rt;break;case 16189:for(;c<32;){if(0===a)break e;a--,u+=r[n++]<>>=7&c,c-=7&c,i.mode=Vt;break}for(;c<3;){if(0===a)break e;a--,u+=r[n++]<>>=1)){case 0:i.mode=16193;break;case 1:if($t(i),i.mode=Nt,t===Pt){u>>>=2,c-=2;break e}break;case 2:i.mode=16196;break;case 3:e.msg="invalid block type",i.mode=Ht}u>>>=2,c-=2;break;case 16193:for(u>>>=7&c,c-=7&c;c<32;){if(0===a)break e;a--,u+=r[n++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=Ht;break}if(i.length=65535&u,u=0,c=0,i.mode=Ot,t===Pt)break e;case Ot:i.mode=16195;case 16195:if(d=i.length){if(d>a&&(d=a),d>l&&(d=l),0===d)break e;s.set(r.subarray(n,n+d),o),a-=d,n+=d,l-=d,o+=d,i.length-=d;break}i.mode=Rt;break;case 16196:for(;c<14;){if(0===a)break e;a--,u+=r[n++]<>>=5,c-=5,i.ndist=1+(31&u),u>>>=5,c-=5,i.ncode=4+(15&u),u>>>=4,c-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=Ht;break}i.have=0,i.mode=16197;case 16197:for(;i.have>>=3,c-=3}for(;i.have<19;)i.lens[E[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,B={bits:i.lenbits},w=xt(0,i.lens,0,19,i.lencode,0,i.work,B),i.lenbits=B.bits,w){e.msg="invalid code lengths set",i.mode=Ht;break}i.have=0,i.mode=16198;case 16198:for(;i.have>>16&255,m=65535&C,!((v=C>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<>>=v,c-=v,i.lens[i.have++]=m;else{if(16===m){for(P=v+2;c>>=v,c-=v,0===i.have){e.msg="invalid bit length repeat",i.mode=Ht;break}x=i.lens[i.have-1],d=3+(3&u),u>>>=2,c-=2}else if(17===m){for(P=v+3;c>>=v)),u>>>=3,c-=3}else{for(P=v+7;c>>=v)),u>>>=7,c-=7}if(i.have+d>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=Ht;break}for(;d--;)i.lens[i.have++]=x}}if(i.mode===Ht)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=Ht;break}if(i.lenbits=9,B={bits:i.lenbits},w=xt(1,i.lens,0,i.nlen,i.lencode,0,i.work,B),i.lenbits=B.bits,w){e.msg="invalid literal/lengths set",i.mode=Ht;break}if(i.distbits=6,i.distcode=i.distdyn,B={bits:i.distbits},w=xt(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,B),i.distbits=B.bits,w){e.msg="invalid distances set",i.mode=Ht;break}if(i.mode=Nt,t===Pt)break e;case Nt:i.mode=Qt;case Qt:if(a>=6&&l>=258){e.next_out=o,e.avail_out=l,e.next_in=n,e.avail_in=a,i.hold=u,i.bits=c,gt(e,h),o=e.next_out,s=e.output,l=e.avail_out,n=e.next_in,r=e.input,a=e.avail_in,u=i.hold,c=i.bits,i.mode===Rt&&(i.back=-1);break}for(i.back=0;g=(C=i.lencode[u&(1<>>16&255,m=65535&C,!((v=C>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<>_)])>>>16&255,m=65535&C,!(_+(v=C>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<>>=_,c-=_,i.back+=_}if(u>>>=v,c-=v,i.back+=v,i.length=m,0===g){i.mode=16205;break}if(32&g){i.back=-1,i.mode=Rt;break}if(64&g){e.msg="invalid literal/length code",i.mode=Ht;break}i.extra=15&g,i.mode=16201;case 16201:if(i.extra){for(P=i.extra;c>>=i.extra,c-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=16202;case 16202:for(;g=(C=i.distcode[u&(1<>>16&255,m=65535&C,!((v=C>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<>_)])>>>16&255,m=65535&C,!(_+(v=C>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<>>=_,c-=_,i.back+=_}if(u>>>=v,c-=v,i.back+=v,64&g){e.msg="invalid distance code",i.mode=Ht;break}i.offset=m,i.extra=15&g,i.mode=16203;case 16203:if(i.extra){for(P=i.extra;c>>=i.extra,c-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=Ht;break}i.mode=16204;case 16204:if(0===l)break e;if(d=h-l,i.offset>d){if((d=i.offset-d)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=Ht;break}d>i.wnext?(d-=i.wnext,p=i.wsize-d):p=i.wnext-d,d>i.length&&(d=i.length),f=i.window}else f=s,p=o-i.offset,d=i.length;d>l&&(d=l),l-=d,i.length-=d;do{s[o++]=f[p++]}while(--d);0===i.length&&(i.mode=Qt);break;case 16205:if(0===l)break e;s[o++]=i.length,l--,i.mode=Qt;break;case Vt:if(i.wrap){for(;c<32;){if(0===a)break e;a--,u|=r[n++]<=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 $e,this.strm.avail_out=0;var i=ii(this.strm,t.windowBits);if(i!==Ai)throw new Error(H[i]);if(this.header=new ai,ni(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=Ye(t.dictionary):"[object ArrayBuffer]"===li.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=oi(this.strm,t.dictionary))!==Ai))throw new Error(H[i])}function mi(e,t){var i=new gi(t);if(i.push(e),i.err)throw i.msg||H[i.err];return i.result}gi.prototype.push=function(e,t){var i,r,s,n=this.strm,o=this.options.chunkSize,a=this.options.dictionary;if(this.ended)return!1;for(r=t===~~t?t:!0===t?ci:ui,"[object ArrayBuffer]"===li.call(e)?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;){for(0===n.avail_out&&(n.output=new Uint8Array(o),n.next_out=0,n.avail_out=o),(i=ri(n,r))===di&&a&&((i=oi(n,a))===Ai?i=ri(n,r):i===fi&&(i=di));n.avail_in>0&&i===hi&&n.state.wrap>0&&0!==e[n.next_in];)ti(n),i=ri(n,r);switch(i){case pi:case fi:case di:case vi:return this.onEnd(i),this.ended=!0,!1}if(s=n.avail_out,n.next_out&&(0===n.avail_out||i===hi))if("string"===this.options.to){var l=qe(n.output,n.next_out),u=n.next_out-l,c=Ze(n.output,l);n.next_out=u,n.avail_out=o-u,u&&n.output.set(n.output.subarray(l,l+u),0),this.onData(c)}else this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out));if(i!==Ai||0!==s){if(i===hi)return i=si(this.strm),this.onEnd(i),this.ended=!0,!0;if(0===n.avail_in)break}}return!0},gi.prototype.onData=function(e){this.chunks.push(e)},gi.prototype.onEnd=function(e){e===Ai&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=We(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var _i=function(e,t){return(t=t||{}).raw=!0,mi(e,t)},yi=ht,bi=dt,xi=pt,wi=ft,Bi=gi,Pi=mi,Ci=_i,Mi=mi,Ei=j,Fi={Deflate:yi,deflate:bi,deflateRaw:xi,gzip:wi,Inflate:Bi,inflate:Pi,inflateRaw:Ci,ungzip:Mi,constants:Ei};e.Deflate=yi,e.Inflate=Bi,e.constants=Ei,e.default=Fi,e.deflate=bi,e.deflateRaw=xi,e.gzip=wi,e.inflate=Pi,e.inflateRaw=Ci,e.ungzip=Mi,Object.defineProperty(e,"__esModule",{value:!0})}));var VF=Object.freeze({__proto__:null}),HF=window.pako||VF;HF.inflate||(HF=HF.default);var jF,GF=(jF=new Float32Array(3),function(e){return jF[0]=e[0]/255,jF[1]=e[1]/255,jF[2]=e[2]/255,jF});var zF={version:1,parse:function(e,t,i,r,s,n){var o=function(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]}}(i),a=function(e){return{positions:new Uint16Array(HF.inflate(e.positions).buffer),normals:new Int8Array(HF.inflate(e.normals).buffer),indices:new Uint32Array(HF.inflate(e.indices).buffer),edgeIndices:new Uint32Array(HF.inflate(e.edgeIndices).buffer),meshPositions:new Uint32Array(HF.inflate(e.meshPositions).buffer),meshIndices:new Uint32Array(HF.inflate(e.meshIndices).buffer),meshEdgesIndices:new Uint32Array(HF.inflate(e.meshEdgesIndices).buffer),meshColors:new Uint8Array(HF.inflate(e.meshColors).buffer),entityIDs:HF.inflate(e.entityIDs,{to:"string"}),entityMeshes:new Uint32Array(HF.inflate(e.entityMeshes).buffer),entityIsObjects:new Uint8Array(HF.inflate(e.entityIsObjects).buffer),positionsDecodeMatrix:new Float32Array(HF.inflate(e.positionsDecodeMatrix).buffer)}}(o);!function(e,t,i,r,s,n){n.getNextId(),r.positionsCompression="precompressed",r.normalsCompression="precompressed";for(var o=i.positions,a=i.normals,l=i.indices,u=i.edgeIndices,c=i.meshPositions,A=i.meshIndices,h=i.meshEdgesIndices,d=i.meshColors,p=JSON.parse(i.entityIDs),f=i.entityMeshes,v=i.entityIsObjects,g=c.length,m=f.length,_=0;_v[t]?1:0}));for(var E=0;E1||(F[R]=k)}for(var U=0;U1,V=$F(g.subarray(4*O,4*O+3)),H=g[4*O+3]/255,j=a.subarray(d[O],N?a.length:d[O+1]),G=l.subarray(d[O],N?l.length:d[O+1]),z=u.subarray(p[O],N?u.length:p[O+1]),W=c.subarray(f[O],N?c.length:f[O+1]),K=A.subarray(v[O],v[O]+16);if(Q){var X="".concat(o,"-geometry.").concat(O);r.createGeometry({id:X,primitive:"triangles",positionsCompressed:j,normalsCompressed:G,indices:z,edgeIndices:W,positionsDecodeMatrix:K})}else{var J="".concat(o,"-").concat(O);_[F[O]],r.createMesh(he.apply({},{id:J,primitive:"triangles",positionsCompressed:j,normalsCompressed:G,indices:z,edgeIndices:W,positionsDecodeMatrix:K,color:V,opacity:H}))}}for(var Y=0,Z=0;Z1){var oe="".concat(o,"-instance.").concat(Y++),ae="".concat(o,"-geometry.").concat(ne),le=16*b[Z],ue=h.subarray(le,le+16);r.createMesh(he.apply({},{id:oe,geometryId:ae,matrix:ue})),re.push(oe)}else re.push(ne)}re.length>0&&r.createEntity(he.apply({},{id:ee,isObject:!0,meshIds:re}))}}(0,0,a,r,0,n)}},tk=window.pako||VF;tk.inflate||(tk=tk.default);var ik=function(){var e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();var rk={version:5,parse:function(e,t,i,r,s,n){var o=function(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]}}(i),a=function(e){return{positions:new Float32Array(tk.inflate(e.positions).buffer),normals:new Int8Array(tk.inflate(e.normals).buffer),indices:new Uint32Array(tk.inflate(e.indices).buffer),edgeIndices:new Uint32Array(tk.inflate(e.edgeIndices).buffer),matrices:new Float32Array(tk.inflate(e.matrices).buffer),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(tk.inflate(e.eachPrimitivePositionsAndNormalsPortion).buffer),eachPrimitiveIndicesPortion:new Uint32Array(tk.inflate(e.eachPrimitiveIndicesPortion).buffer),eachPrimitiveEdgeIndicesPortion:new Uint32Array(tk.inflate(e.eachPrimitiveEdgeIndicesPortion).buffer),eachPrimitiveColor:new Uint8Array(tk.inflate(e.eachPrimitiveColor).buffer),primitiveInstances:new Uint32Array(tk.inflate(e.primitiveInstances).buffer),eachEntityId:tk.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(tk.inflate(e.eachEntityPrimitiveInstancesPortion).buffer),eachEntityMatricesPortion:new Uint32Array(tk.inflate(e.eachEntityMatricesPortion).buffer)}}(o);!function(e,t,i,r,s,n){var o=n.getNextId();r.positionsCompression="disabled",r.normalsCompression="precompressed";for(var a=i.positions,l=i.normals,u=i.indices,c=i.edgeIndices,A=i.matrices,h=i.eachPrimitivePositionsAndNormalsPortion,d=i.eachPrimitiveIndicesPortion,p=i.eachPrimitiveEdgeIndicesPortion,f=i.eachPrimitiveColor,v=i.primitiveInstances,g=JSON.parse(i.eachEntityId),m=i.eachEntityPrimitiveInstancesPortion,_=i.eachEntityMatricesPortion,y=h.length,b=v.length,x=new Uint8Array(y),w=g.length,B=0;B1||(P[D]=C)}for(var S=0;S1,R=ik(f.subarray(4*S,4*S+3)),U=f[4*S+3]/255,O=a.subarray(h[S],T?a.length:h[S+1]),N=l.subarray(h[S],T?l.length:h[S+1]),Q=u.subarray(d[S],T?u.length:d[S+1]),V=c.subarray(p[S],T?c.length:p[S+1]);if(L){var H="".concat(o,"-geometry.").concat(S);r.createGeometry({id:H,primitive:"triangles",positionsCompressed:O,normalsCompressed:N,indices:Q,edgeIndices:V})}else{var j=S;g[P[S]],r.createMesh(he.apply({},{id:j,primitive:"triangles",positionsCompressed:O,normalsCompressed:N,indices:Q,edgeIndices:V,color:R,opacity:U}))}}for(var G=0,z=0;z1){var ee="instance."+G++,te="geometry"+$,ie=16*_[z],re=A.subarray(ie,ie+16);r.createMesh(he.apply({},{id:ee,geometryId:te,matrix:re})),Z.push(ee)}else Z.push($)}Z.length>0&&r.createEntity(he.apply({},{id:X,isObject:!0,meshIds:Z}))}}(0,0,a,r,0,n)}},sk=window.pako||VF;sk.inflate||(sk=sk.default);var nk,ok=(nk=new Float32Array(3),function(e){return nk[0]=e[0]/255,nk[1]=e[1]/255,nk[2]=e[2]/255,nk});var ak={version:6,parse:function(e,t,i,r,s,n){var o=function(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],matrices:e[4],reusedPrimitivesDecodeMatrix:e[5],eachPrimitivePositionsAndNormalsPortion:e[6],eachPrimitiveIndicesPortion:e[7],eachPrimitiveEdgeIndicesPortion:e[8],eachPrimitiveColorAndOpacity:e[9],primitiveInstances:e[10],eachEntityId:e[11],eachEntityPrimitiveInstancesPortion:e[12],eachEntityMatricesPortion:e[13],eachTileAABB:e[14],eachTileEntitiesPortion:e[15]}}(i),a=function(e){function t(e,t){return 0===e.length?[]:sk.inflate(e,t).buffer}return{positions:new Uint16Array(t(e.positions)),normals:new Int8Array(t(e.normals)),indices:new Uint32Array(t(e.indices)),edgeIndices:new Uint32Array(t(e.edgeIndices)),matrices:new Float32Array(t(e.matrices)),reusedPrimitivesDecodeMatrix:new Float32Array(t(e.reusedPrimitivesDecodeMatrix)),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(t(e.eachPrimitivePositionsAndNormalsPortion)),eachPrimitiveIndicesPortion:new Uint32Array(t(e.eachPrimitiveIndicesPortion)),eachPrimitiveEdgeIndicesPortion:new Uint32Array(t(e.eachPrimitiveEdgeIndicesPortion)),eachPrimitiveColorAndOpacity:new Uint8Array(t(e.eachPrimitiveColorAndOpacity)),primitiveInstances:new Uint32Array(t(e.primitiveInstances)),eachEntityId:sk.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(t(e.eachEntityPrimitiveInstancesPortion)),eachEntityMatricesPortion:new Uint32Array(t(e.eachEntityMatricesPortion)),eachTileAABB:new Float64Array(t(e.eachTileAABB)),eachTileEntitiesPortion:new Uint32Array(t(e.eachTileEntitiesPortion))}}(o);!function(e,t,i,r,s,n){for(var o=n.getNextId(),a=i.positions,l=i.normals,u=i.indices,c=i.edgeIndices,A=i.matrices,h=i.reusedPrimitivesDecodeMatrix,d=i.eachPrimitivePositionsAndNormalsPortion,p=i.eachPrimitiveIndicesPortion,f=i.eachPrimitiveEdgeIndicesPortion,v=i.eachPrimitiveColorAndOpacity,g=i.primitiveInstances,m=JSON.parse(i.eachEntityId),_=i.eachEntityPrimitiveInstancesPortion,y=i.eachEntityMatricesPortion,b=i.eachTileAABB,x=i.eachTileEntitiesPortion,w=d.length,B=g.length,P=m.length,C=x.length,M=new Uint32Array(w),E=0;E1,ie=ee===w-1,se=a.subarray(d[ee],ie?a.length:d[ee+1]),ne=l.subarray(d[ee],ie?l.length:d[ee+1]),oe=u.subarray(p[ee],ie?u.length:p[ee+1]),ae=c.subarray(f[ee],ie?c.length:f[ee+1]),le=ok(v.subarray(4*ee,4*ee+3)),ue=v[4*ee+3]/255,ce=n.getNextId();if(te){var Ae="".concat(o,"-geometry.").concat(D,".").concat(ee);N[Ae]||(r.createGeometry({id:Ae,primitive:"triangles",positionsCompressed:se,indices:oe,edgeIndices:ae,positionsDecodeMatrix:h}),N[Ae]=!0),r.createMesh(he.apply(Z,{id:ce,geometryId:Ae,origin:k,matrix:G,color:le,opacity:ue})),X.push(ce)}else r.createMesh(he.apply(Z,{id:ce,origin:k,primitive:"triangles",positionsCompressed:se,normalsCompressed:ne,indices:oe,edgeIndices:ae,positionsDecodeMatrix:O,color:le,opacity:ue})),X.push(ce)}X.length>0&&r.createEntity(he.apply(Y,{id:H,isObject:!0,meshIds:X}))}}}(e,t,a,r,0,n)}},lk=window.pako||VF;lk.inflate||(lk=lk.default);var uk=function(){var 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 ck(e){for(var t=[],i=0,r=e.length;i1,ne=ie===M-1,oe=uk(x.subarray(6*te,6*te+3)),ae=x[6*te+3]/255,le=x[6*te+4]/255,ue=x[6*te+5]/255,ce=n.getNextId();if(se){var Ae=b[te],de=h.slice(Ae,Ae+16),pe="".concat(o,"-geometry.").concat(R,".").concat(ie);if(!j[pe]){var fe=void 0,ve=void 0,ge=void 0,me=void 0,_e=void 0,ye=void 0;switch(p[ie]){case 0:fe="solid",ve=a.subarray(f[ie],ne?a.length:f[ie+1]),ge=l.subarray(v[ie],ne?l.length:v[ie+1]),_e=c.subarray(m[ie],ne?c.length:m[ie+1]),ye=A.subarray(_[ie],ne?A.length:_[ie+1]);break;case 1:fe="surface",ve=a.subarray(f[ie],ne?a.length:f[ie+1]),ge=l.subarray(v[ie],ne?l.length:v[ie+1]),_e=c.subarray(m[ie],ne?c.length:m[ie+1]),ye=A.subarray(_[ie],ne?A.length:_[ie+1]);break;case 2:fe="points",ve=a.subarray(f[ie],ne?a.length:f[ie+1]),me=ck(u.subarray(g[ie],ne?u.length:g[ie+1]));break;case 3:fe="lines",ve=a.subarray(f[ie],ne?a.length:f[ie+1]),_e=c.subarray(m[ie],ne?c.length:m[ie+1]);break;default:continue}r.createGeometry({id:pe,primitive:fe,positionsCompressed:ve,normalsCompressed:ge,colors:me,indices:_e,edgeIndices:ye,positionsDecodeMatrix:d}),j[pe]=!0}r.createMesh(he.apply($,{id:ce,geometryId:pe,origin:T,matrix:de,color:oe,metallic:le,roughness:ue,opacity:ae})),Y.push(ce)}else{var be=void 0,xe=void 0,we=void 0,Be=void 0,Pe=void 0,Ce=void 0;switch(p[ie]){case 0:be="solid",xe=a.subarray(f[ie],ne?a.length:f[ie+1]),we=l.subarray(v[ie],ne?l.length:v[ie+1]),Pe=c.subarray(m[ie],ne?c.length:m[ie+1]),Ce=A.subarray(_[ie],ne?A.length:_[ie+1]);break;case 1:be="surface",xe=a.subarray(f[ie],ne?a.length:f[ie+1]),we=l.subarray(v[ie],ne?l.length:v[ie+1]),Pe=c.subarray(m[ie],ne?c.length:m[ie+1]),Ce=A.subarray(_[ie],ne?A.length:_[ie+1]);break;case 2:be="points",xe=a.subarray(f[ie],ne?a.length:f[ie+1]),Be=ck(u.subarray(g[ie],ne?u.length:g[ie+1]));break;case 3:be="lines",xe=a.subarray(f[ie],ne?a.length:f[ie+1]),Pe=c.subarray(m[ie],ne?c.length:m[ie+1]);break;default:continue}r.createMesh(he.apply($,{id:ce,origin:T,primitive:be,positionsCompressed:xe,normalsCompressed:we,colors:Be,indices:Pe,edgeIndices:Ce,positionsDecodeMatrix:H,color:oe,metallic:le,roughness:ue,opacity:ae})),Y.push(ce)}}Y.length>0&&r.createEntity(he.apply(q,{id:W,isObject:!0,meshIds:Y}))}}}(e,t,a,r,0,n)}},hk=window.pako||VF;hk.inflate||(hk=hk.default);var dk=re.vec4(),pk=re.vec4();var fk=function(){var 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 vk(e){for(var t=[],i=0,r=e.length;i1,ye=me===S-1,be=fk(M.subarray(6*ge,6*ge+3)),xe=M[6*ge+3]/255,we=M[6*ge+4]/255,Be=M[6*ge+5]/255,Pe=n.getNextId();if(_e){var Ce=C[ge],Me=g.slice(Ce,Ce+16),Ee="".concat(o,"-geometry.").concat(Y,".").concat(me),Fe=J[Ee];if(!Fe){Fe={batchThisMesh:!t.reuseGeometries};var ke=!1;switch(_[me]){case 0:Fe.primitiveName="solid",Fe.geometryPositions=h.subarray(y[me],ye?h.length:y[me+1]),Fe.geometryNormals=d.subarray(b[me],ye?d.length:b[me+1]),Fe.geometryIndices=f.subarray(w[me],ye?f.length:w[me+1]),Fe.geometryEdgeIndices=v.subarray(B[me],ye?v.length:B[me+1]),ke=Fe.geometryPositions.length>0&&Fe.geometryIndices.length>0;break;case 1:Fe.primitiveName="surface",Fe.geometryPositions=h.subarray(y[me],ye?h.length:y[me+1]),Fe.geometryNormals=d.subarray(b[me],ye?d.length:b[me+1]),Fe.geometryIndices=f.subarray(w[me],ye?f.length:w[me+1]),Fe.geometryEdgeIndices=v.subarray(B[me],ye?v.length:B[me+1]),ke=Fe.geometryPositions.length>0&&Fe.geometryIndices.length>0;break;case 2:Fe.primitiveName="points",Fe.geometryPositions=h.subarray(y[me],ye?h.length:y[me+1]),Fe.geometryColors=vk(p.subarray(x[me],ye?p.length:x[me+1])),ke=Fe.geometryPositions.length>0;break;case 3:Fe.primitiveName="lines",Fe.geometryPositions=h.subarray(y[me],ye?h.length:y[me+1]),Fe.geometryIndices=f.subarray(w[me],ye?f.length:w[me+1]),ke=Fe.geometryPositions.length>0&&Fe.geometryIndices.length>0;break;default:continue}if(ke||(Fe=null),Fe&&(Fe.geometryPositions.length,Fe.batchThisMesh)){Fe.decompressedPositions=new Float32Array(Fe.geometryPositions.length);for(var Ie=Fe.geometryPositions,De=Fe.decompressedPositions,Se=0,Te=Ie.length;Se0&&je.length>0;break;case 1:Ne="surface",Qe=h.subarray(y[me],ye?h.length:y[me+1]),Ve=d.subarray(b[me],ye?d.length:b[me+1]),je=f.subarray(w[me],ye?f.length:w[me+1]),Ge=v.subarray(B[me],ye?v.length:B[me+1]),ze=Qe.length>0&&je.length>0;break;case 2:Ne="points",Qe=h.subarray(y[me],ye?h.length:y[me+1]),He=vk(p.subarray(x[me],ye?p.length:x[me+1])),ze=Qe.length>0;break;case 3:Ne="lines",Qe=h.subarray(y[me],ye?h.length:y[me+1]),je=f.subarray(w[me],ye?f.length:w[me+1]),ze=Qe.length>0&&je.length>0;break;default:continue}ze&&(r.createMesh(he.apply(fe,{id:Pe,origin:K,primitive:Ne,positionsCompressed:Qe,normalsCompressed:Ve,colorsCompressed:He,indices:je,edgeIndices:Ge,positionsDecodeMatrix:ie,color:be,metallic:we,roughness:Be,opacity:xe})),Ae.push(Pe))}}Ae.length>0&&r.createEntity(he.apply(pe,{id:ae,isObject:!0,meshIds:Ae}))}}}(e,t,a,r,s,n)}},mk=window.pako||VF;mk.inflate||(mk=mk.default);var _k=re.vec4(),yk=re.vec4();var bk=function(){var e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();var xk={version:9,parse:function(e,t,i,r,s,n){var o=function(e){return{metadata:e[0],positions:e[1],normals:e[2],colors:e[3],indices:e[4],edgeIndices:e[5],matrices:e[6],reusedGeometriesDecodeMatrix:e[7],eachGeometryPrimitiveType:e[8],eachGeometryPositionsPortion:e[9],eachGeometryNormalsPortion:e[10],eachGeometryColorsPortion:e[11],eachGeometryIndicesPortion:e[12],eachGeometryEdgeIndicesPortion:e[13],eachMeshGeometriesPortion:e[14],eachMeshMatricesPortion:e[15],eachMeshMaterial:e[16],eachEntityId:e[17],eachEntityMeshesPortion:e[18],eachTileAABB:e[19],eachTileEntitiesPortion:e[20]}}(i),a=function(e){function t(e,t){return 0===e.length?[]:mk.inflate(e,t).buffer}return{metadata:JSON.parse(mk.inflate(e.metadata,{to:"string"})),positions:new Uint16Array(t(e.positions)),normals:new Int8Array(t(e.normals)),colors:new Uint8Array(t(e.colors)),indices:new Uint32Array(t(e.indices)),edgeIndices:new Uint32Array(t(e.edgeIndices)),matrices:new Float32Array(t(e.matrices)),reusedGeometriesDecodeMatrix:new Float32Array(t(e.reusedGeometriesDecodeMatrix)),eachGeometryPrimitiveType:new Uint8Array(t(e.eachGeometryPrimitiveType)),eachGeometryPositionsPortion:new Uint32Array(t(e.eachGeometryPositionsPortion)),eachGeometryNormalsPortion:new Uint32Array(t(e.eachGeometryNormalsPortion)),eachGeometryColorsPortion:new Uint32Array(t(e.eachGeometryColorsPortion)),eachGeometryIndicesPortion:new Uint32Array(t(e.eachGeometryIndicesPortion)),eachGeometryEdgeIndicesPortion:new Uint32Array(t(e.eachGeometryEdgeIndicesPortion)),eachMeshGeometriesPortion:new Uint32Array(t(e.eachMeshGeometriesPortion)),eachMeshMatricesPortion:new Uint32Array(t(e.eachMeshMatricesPortion)),eachMeshMaterial:new Uint8Array(t(e.eachMeshMaterial)),eachEntityId:JSON.parse(mk.inflate(e.eachEntityId,{to:"string"})),eachEntityMeshesPortion:new Uint32Array(t(e.eachEntityMeshesPortion)),eachTileAABB:new Float64Array(t(e.eachTileAABB)),eachTileEntitiesPortion:new Uint32Array(t(e.eachTileEntitiesPortion))}}(o);!function(e,t,i,r,s,n){var o=n.getNextId(),a=i.metadata,l=i.positions,u=i.normals,c=i.colors,A=i.indices,h=i.edgeIndices,d=i.matrices,p=i.reusedGeometriesDecodeMatrix,f=i.eachGeometryPrimitiveType,v=i.eachGeometryPositionsPortion,g=i.eachGeometryNormalsPortion,m=i.eachGeometryColorsPortion,_=i.eachGeometryIndicesPortion,y=i.eachGeometryEdgeIndicesPortion,b=i.eachMeshGeometriesPortion,x=i.eachMeshMatricesPortion,w=i.eachMeshMaterial,B=i.eachEntityId,P=i.eachEntityMeshesPortion,C=i.eachTileAABB,M=i.eachTileEntitiesPortion,E=v.length,F=b.length,k=P.length,I=M.length;s&&s.loadData(a,{includeTypes:t.includeTypes,excludeTypes:t.excludeTypes,globalizeObjectIds:t.globalizeObjectIds});for(var D=new Uint32Array(E),S=0;S1,ae=ne===E-1,le=bk(w.subarray(6*se,6*se+3)),ue=w[6*se+3]/255,ce=w[6*se+4]/255,Ae=w[6*se+5]/255,de=n.getNextId();if(oe){var pe=x[se],fe=d.slice(pe,pe+16),ve="".concat(o,"-geometry.").concat(O,".").concat(ne),ge=U[ve];if(!ge){ge={batchThisMesh:!t.reuseGeometries};var me=!1;switch(f[ne]){case 0:ge.primitiveName="solid",ge.geometryPositions=l.subarray(v[ne],ae?l.length:v[ne+1]),ge.geometryNormals=u.subarray(g[ne],ae?u.length:g[ne+1]),ge.geometryIndices=A.subarray(_[ne],ae?A.length:_[ne+1]),ge.geometryEdgeIndices=h.subarray(y[ne],ae?h.length:y[ne+1]),me=ge.geometryPositions.length>0&&ge.geometryIndices.length>0;break;case 1:ge.primitiveName="surface",ge.geometryPositions=l.subarray(v[ne],ae?l.length:v[ne+1]),ge.geometryNormals=u.subarray(g[ne],ae?u.length:g[ne+1]),ge.geometryIndices=A.subarray(_[ne],ae?A.length:_[ne+1]),ge.geometryEdgeIndices=h.subarray(y[ne],ae?h.length:y[ne+1]),me=ge.geometryPositions.length>0&&ge.geometryIndices.length>0;break;case 2:ge.primitiveName="points",ge.geometryPositions=l.subarray(v[ne],ae?l.length:v[ne+1]),ge.geometryColors=c.subarray(m[ne],ae?c.length:m[ne+1]),me=ge.geometryPositions.length>0;break;case 3:ge.primitiveName="lines",ge.geometryPositions=l.subarray(v[ne],ae?l.length:v[ne+1]),ge.geometryIndices=A.subarray(_[ne],ae?A.length:_[ne+1]),me=ge.geometryPositions.length>0&&ge.geometryIndices.length>0;break;default:continue}if(me||(ge=null),ge&&(ge.geometryPositions.length,ge.batchThisMesh)){ge.decompressedPositions=new Float32Array(ge.geometryPositions.length),ge.transformedAndRecompressedPositions=new Uint16Array(ge.geometryPositions.length);for(var _e=ge.geometryPositions,ye=ge.decompressedPositions,be=0,xe=_e.length;be0&&Ie.length>0;break;case 1:Me="surface",Ee=l.subarray(v[ne],ae?l.length:v[ne+1]),Fe=u.subarray(g[ne],ae?u.length:g[ne+1]),Ie=A.subarray(_[ne],ae?A.length:_[ne+1]),De=h.subarray(y[ne],ae?h.length:y[ne+1]),Se=Ee.length>0&&Ie.length>0;break;case 2:Me="points",Ee=l.subarray(v[ne],ae?l.length:v[ne+1]),ke=c.subarray(m[ne],ae?c.length:m[ne+1]),Se=Ee.length>0;break;case 3:Me="lines",Ee=l.subarray(v[ne],ae?l.length:v[ne+1]),Ie=A.subarray(_[ne],ae?A.length:_[ne+1]),Se=Ee.length>0&&Ie.length>0;break;default:continue}Se&&(r.createMesh(he.apply(te,{id:de,origin:L,primitive:Me,positionsCompressed:Ee,normalsCompressed:Fe,colorsCompressed:ke,indices:Ie,edgeIndices:De,positionsDecodeMatrix:G,color:le,metallic:ce,roughness:Ae,opacity:ue})),q.push(de))}}q.length>0&&r.createEntity(he.apply(ee,{id:X,isObject:!0,meshIds:q}))}}}(e,t,a,r,s,n)}},wk=window.pako||VF;wk.inflate||(wk=wk.default);var Bk=re.vec4(),Pk=re.vec4();var Ck=function(){var 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 Mk(e,t){var i=[];if(t.length>1)for(var r=0,s=t.length-1;r1)for(var n=0,o=e.length/3-1;n0,W=9*V,K=1===c[W+0],X=c[W+1];c[W+2],c[W+3];var J=c[W+4],Y=c[W+5],Z=c[W+6],q=c[W+7],$=c[W+8];if(z){var ee=new Uint8Array(l.subarray(j,G)).buffer,te="".concat(o,"-texture-").concat(V);if(K)r.createTexture({id:te,buffers:[ee],minFilter:J,magFilter:Y,wrapS:Z,wrapT:q,wrapR:$});else{var ie=new Blob([ee],{type:10001===X?"image/jpeg":10002===X?"image/png":"image/gif"}),se=(window.URL||window.webkitURL).createObjectURL(ie),ne=document.createElement("img");ne.src=se,r.createTexture({id:te,image:ne,minFilter:J,magFilter:Y,wrapS:Z,wrapT:q,wrapR:$})}}}for(var oe=0;oe=0?"".concat(o,"-texture-").concat(ue):null,normalsTextureId:Ae>=0?"".concat(o,"-texture-").concat(Ae):null,metallicRoughnessTextureId:ce>=0?"".concat(o,"-texture-").concat(ce):null,emissiveTextureId:de>=0?"".concat(o,"-texture-").concat(de):null,occlusionTextureId:pe>=0?"".concat(o,"-texture-").concat(pe):null})}for(var fe=new Uint32Array(U),ve=0;ve1,je=Ve===U-1,Ge=F[Qe],ze=Ge>=0?"".concat(o,"-textureSet-").concat(Ge):null,We=Ck(k.subarray(6*Qe,6*Qe+3)),Ke=k[6*Qe+3]/255,Xe=k[6*Qe+4]/255,Je=k[6*Qe+5]/255,Ye=n.getNextId();if(He){var Ze=E[Qe],qe=m.slice(Ze,Ze+16),$e="".concat(o,"-geometry.").concat(be,".").concat(Ve),et=ye[$e];if(!et){et={batchThisMesh:!t.reuseGeometries};var tt=!1;switch(y[Ve]){case 0:et.primitiveName="solid",et.geometryPositions=A.subarray(b[Ve],je?A.length:b[Ve+1]),et.geometryNormals=h.subarray(x[Ve],je?h.length:x[Ve+1]),et.geometryUVs=p.subarray(B[Ve],je?p.length:B[Ve+1]),et.geometryIndices=f.subarray(P[Ve],je?f.length:P[Ve+1]),et.geometryEdgeIndices=v.subarray(C[Ve],je?v.length:C[Ve+1]),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;case 1:et.primitiveName="surface",et.geometryPositions=A.subarray(b[Ve],je?A.length:b[Ve+1]),et.geometryNormals=h.subarray(x[Ve],je?h.length:x[Ve+1]),et.geometryUVs=p.subarray(B[Ve],je?p.length:B[Ve+1]),et.geometryIndices=f.subarray(P[Ve],je?f.length:P[Ve+1]),et.geometryEdgeIndices=v.subarray(C[Ve],je?v.length:C[Ve+1]),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;case 2:et.primitiveName="points",et.geometryPositions=A.subarray(b[Ve],je?A.length:b[Ve+1]),et.geometryColors=d.subarray(w[Ve],je?d.length:w[Ve+1]),tt=et.geometryPositions.length>0;break;case 3:et.primitiveName="lines",et.geometryPositions=A.subarray(b[Ve],je?A.length:b[Ve+1]),et.geometryIndices=f.subarray(P[Ve],je?f.length:P[Ve+1]),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;case 4:et.primitiveName="lines",et.geometryPositions=A.subarray(b[Ve],je?A.length:b[Ve+1]),et.geometryIndices=Mk(et.geometryPositions,f.subarray(P[Ve],je?f.length:P[Ve+1])),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;default:continue}if(tt||(et=null),et&&(et.geometryPositions.length,et.batchThisMesh)){et.decompressedPositions=new Float32Array(et.geometryPositions.length),et.transformedAndRecompressedPositions=new Uint16Array(et.geometryPositions.length);for(var it=et.geometryPositions,rt=et.decompressedPositions,st=0,nt=it.length;st0&&ft.length>0;break;case 1:ct="surface",At=A.subarray(b[Ve],je?A.length:b[Ve+1]),ht=h.subarray(x[Ve],je?h.length:x[Ve+1]),dt=p.subarray(B[Ve],je?p.length:B[Ve+1]),ft=f.subarray(P[Ve],je?f.length:P[Ve+1]),vt=v.subarray(C[Ve],je?v.length:C[Ve+1]),gt=At.length>0&&ft.length>0;break;case 2:ct="points",At=A.subarray(b[Ve],je?A.length:b[Ve+1]),pt=d.subarray(w[Ve],je?d.length:w[Ve+1]),gt=At.length>0;break;case 3:ct="lines",At=A.subarray(b[Ve],je?A.length:b[Ve+1]),ft=f.subarray(P[Ve],je?f.length:P[Ve+1]),gt=At.length>0&&ft.length>0;break;case 4:ct="lines",ft=Mk(At=A.subarray(b[Ve],je?A.length:b[Ve+1]),f.subarray(P[Ve],je?f.length:P[Ve+1])),gt=At.length>0&&ft.length>0;break;default:continue}gt&&(r.createMesh(he.apply(Oe,{id:Ye,textureSetId:ze,origin:me,primitive:ct,positionsCompressed:At,normalsCompressed:ht,uv:dt&&dt.length>0?dt:null,colorsCompressed:pt,indices:ft,edgeIndices:vt,positionsDecodeMatrix:Me,color:We,metallic:Xe,roughness:Je,opacity:Ke})),Le.push(Ye))}}Le.length>0&&r.createEntity(he.apply(Ue,{id:Ie,isObject:!0,meshIds:Le}))}}}(e,t,a,r,s,n)}},Fk=re.vec4(),kk=re.vec4();var Ik=function(){var 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 Dk(e,t){var i=[];if(t.length>1)for(var r=0,s=t.length-1;r1)for(var n=0,o=e.length/3-1;n1)for(var u=new Uint8Array(e,o,a),c=l/2,A=u.length/l,h=0;h0,W=9*V,K=1===c[W+0],X=c[W+1];c[W+2],c[W+3];var J=c[W+4],Y=c[W+5],Z=c[W+6],q=c[W+7],$=c[W+8];if(z){var ee=new Uint8Array(l.subarray(j,G)).buffer,te="".concat(o,"-texture-").concat(V);if(K)r.createTexture({id:te,buffers:[ee],minFilter:J,magFilter:Y,wrapS:Z,wrapT:q,wrapR:$});else{var ie=new Blob([ee],{type:10001===X?"image/jpeg":10002===X?"image/png":"image/gif"}),se=(window.URL||window.webkitURL).createObjectURL(ie),ne=document.createElement("img");ne.src=se,r.createTexture({id:te,image:ne,minFilter:J,magFilter:Y,wrapS:Z,wrapT:q,wrapR:$})}}}for(var oe=0;oe=0?"".concat(o,"-texture-").concat(ue):null,normalsTextureId:Ae>=0?"".concat(o,"-texture-").concat(Ae):null,metallicRoughnessTextureId:ce>=0?"".concat(o,"-texture-").concat(ce):null,emissiveTextureId:de>=0?"".concat(o,"-texture-").concat(de):null,occlusionTextureId:pe>=0?"".concat(o,"-texture-").concat(pe):null})}for(var fe=new Uint32Array(U),ve=0;ve1,je=Ve===U-1,Ge=F[Qe],ze=Ge>=0?"".concat(o,"-textureSet-").concat(Ge):null,We=Ik(k.subarray(6*Qe,6*Qe+3)),Ke=k[6*Qe+3]/255,Xe=k[6*Qe+4]/255,Je=k[6*Qe+5]/255,Ye=n.getNextId();if(He){var Ze=E[Qe],qe=m.slice(Ze,Ze+16),$e="".concat(o,"-geometry.").concat(be,".").concat(Ve),et=ye[$e];if(!et){et={batchThisMesh:!t.reuseGeometries};var tt=!1;switch(y[Ve]){case 0:et.primitiveName="solid",et.geometryPositions=A.subarray(b[Ve],je?A.length:b[Ve+1]),et.geometryNormals=h.subarray(x[Ve],je?h.length:x[Ve+1]),et.geometryUVs=p.subarray(B[Ve],je?p.length:B[Ve+1]),et.geometryIndices=f.subarray(P[Ve],je?f.length:P[Ve+1]),et.geometryEdgeIndices=v.subarray(C[Ve],je?v.length:C[Ve+1]),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;case 1:et.primitiveName="surface",et.geometryPositions=A.subarray(b[Ve],je?A.length:b[Ve+1]),et.geometryNormals=h.subarray(x[Ve],je?h.length:x[Ve+1]),et.geometryUVs=p.subarray(B[Ve],je?p.length:B[Ve+1]),et.geometryIndices=f.subarray(P[Ve],je?f.length:P[Ve+1]),et.geometryEdgeIndices=v.subarray(C[Ve],je?v.length:C[Ve+1]),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;case 2:et.primitiveName="points",et.geometryPositions=A.subarray(b[Ve],je?A.length:b[Ve+1]),et.geometryColors=d.subarray(w[Ve],je?d.length:w[Ve+1]),tt=et.geometryPositions.length>0;break;case 3:et.primitiveName="lines",et.geometryPositions=A.subarray(b[Ve],je?A.length:b[Ve+1]),et.geometryIndices=f.subarray(P[Ve],je?f.length:P[Ve+1]),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;case 4:et.primitiveName="lines",et.geometryPositions=A.subarray(b[Ve],je?A.length:b[Ve+1]),et.geometryIndices=Dk(et.geometryPositions,f.subarray(P[Ve],je?f.length:P[Ve+1])),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;default:continue}if(tt||(et=null),et&&(et.geometryPositions.length,et.batchThisMesh)){et.decompressedPositions=new Float32Array(et.geometryPositions.length),et.transformedAndRecompressedPositions=new Uint16Array(et.geometryPositions.length);for(var it=et.geometryPositions,rt=et.decompressedPositions,st=0,nt=it.length;st0&&ft.length>0;break;case 1:ct="surface",At=A.subarray(b[Ve],je?A.length:b[Ve+1]),ht=h.subarray(x[Ve],je?h.length:x[Ve+1]),dt=p.subarray(B[Ve],je?p.length:B[Ve+1]),ft=f.subarray(P[Ve],je?f.length:P[Ve+1]),vt=v.subarray(C[Ve],je?v.length:C[Ve+1]),gt=At.length>0&&ft.length>0;break;case 2:ct="points",At=A.subarray(b[Ve],je?A.length:b[Ve+1]),pt=d.subarray(w[Ve],je?d.length:w[Ve+1]),gt=At.length>0;break;case 3:ct="lines",At=A.subarray(b[Ve],je?A.length:b[Ve+1]),ft=f.subarray(P[Ve],je?f.length:P[Ve+1]),gt=At.length>0&&ft.length>0;break;case 4:ct="lines",ft=Dk(At=A.subarray(b[Ve],je?A.length:b[Ve+1]),f.subarray(P[Ve],je?f.length:P[Ve+1])),gt=At.length>0&&ft.length>0;break;default:continue}gt&&(r.createMesh(he.apply(Oe,{id:Ye,textureSetId:ze,origin:me,primitive:ct,positionsCompressed:At,normalsCompressed:ht,uv:dt&&dt.length>0?dt:null,colorsCompressed:pt,indices:ft,edgeIndices:vt,positionsDecodeMatrix:Me,color:We,metallic:Xe,roughness:Je,opacity:Ke})),Le.push(Ye))}}Le.length>0&&r.createEntity(he.apply(Ue,{id:Ie,isObject:!0,meshIds:Le}))}}}(e,t,o,r,s,n)}},Tk={};Tk[zF.version]=zF,Tk[XF.version]=XF,Tk[ZF.version]=ZF,Tk[ek.version]=ek,Tk[rk.version]=rk,Tk[ak.version]=ak,Tk[Ak.version]=Ak,Tk[gk.version]=gk,Tk[xk.version]=xk,Tk[Ek.version]=Ek,Tk[Sk.version]=Sk;var Lk=function(e){g(r,Ue);var t,i=_(r);function r(e){var t,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return B(this,r),(t=i.call(this,"XKTLoader",e,s))._maxGeometryBatchSize=s.maxGeometryBatchSize,t.textureTranscoder=s.textureTranscoder,t.dataSource=s.dataSource,t.objectDefaults=s.objectDefaults,t.includeTypes=s.includeTypes,t.excludeTypes=s.excludeTypes,t.excludeUnclassifiedObjects=s.excludeUnclassifiedObjects,t.reuseGeometries=s.reuseGeometries,t}return C(r,[{key:"supportedVersions",get:function(){return Object.keys(Tk)}},{key:"textureTranscoder",get:function(){return this._textureTranscoder},set:function(e){this._textureTranscoder=e}},{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new QF}},{key:"objectDefaults",get:function(){return this._objectDefaults},set:function(e){this._objectDefaults=e||UE}},{key:"includeTypes",get:function(){return this._includeTypes},set:function(e){this._includeTypes=e}},{key:"excludeTypes",get:function(){return this._excludeTypes},set:function(e){this._excludeTypes=e}},{key:"excludeUnclassifiedObjects",get:function(){return this._excludeUnclassifiedObjects},set:function(e){this._excludeUnclassifiedObjects=!!e}},{key:"globalizeObjectIds",get:function(){return this._globalizeObjectIds},set:function(e){this._globalizeObjectIds=!!e}},{key:"reuseGeometries",get:function(){return this._reuseGeometries},set:function(e){this._reuseGeometries=!1!==e}},{key:"load",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(t.id&&this.viewer.scene.components[t.id]&&(this.error("Component with this ID already exists in viewer: "+t.id+" - will autogenerate this ID"),delete t.id),!(t.src||t.xkt||t.manifestSrc||t.manifest))return this.error("load() param expected: src, xkt, manifestSrc or manifestData"),c;var i={},r=t.includeTypes||this._includeTypes,s=t.excludeTypes||this._excludeTypes,n=t.objectDefaults||this._objectDefaults;if(i.reuseGeometries=null!==t.reuseGeometries&&void 0!==t.reuseGeometries?t.reuseGeometries:!1!==this._reuseGeometries,r){i.includeTypesMap={};for(var o=0,a=r.length;o=t.length?n():e._dataSource.getMetaModel("".concat(m).concat(t[a]),(function(t){h.loadData(t,{includeTypes:r,excludeTypes:s,globalizeObjectIds:i.globalizeObjectIds}),a++,e.scheduleTask(l,200)}),o)}()},y=function(r,s,n){var o=0;!function a(){c.destroyed||o>=r.length?s():e._dataSource.getXKT("".concat(m).concat(r[o]),(function(r){e._parseModel(r,t,i,c,null,v),c.preFinalize(),o++,e.scheduleTask(a,200)}),n)}()},b=function(r,s,n){var o=0;!function a(){c.destroyed||o>=r.length?s():e._dataSource.getXKT("".concat(m).concat(r[o]),(function(r){e._parseModel(r,t,i,c,h,v),c.preFinalize(),o++,e.scheduleTask(a,200)}),n)}()};if(t.manifest){var x=t.manifest,w=x.xktFiles;if(!w||0===w.length)return void p("load(): Failed to load model manifest - manifest not valid");var B=x.metaModelFiles;B?_(B,(function(){y(w,d,p)}),p):b(w,d,p)}else this._dataSource.getManifest(t.manifestSrc,(function(e){if(!c.destroyed){var t=e.xktFiles;if(t&&0!==t.length){var i=e.metaModelFiles;i?_(i,(function(){y(t,d,p)}),p):b(t,d,p)}else p("load(): Failed to load model manifest - manifest not valid")}}),p)}return c}},{key:"_loadModel",value:function(e,t,i,r,s,n,o,a){var l=this;this._dataSource.getXKT(t.src,(function(e){l._parseModel(e,t,i,r,s,n),r.preFinalize(),o()}),a)}},{key:"_parseModel",value:(t=u(a().mark((function e(t,i,r,s,n,o){var l,u,c,A,h,d,p,f,v;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!s.destroyed){e.next=2;break}return e.abrupt("return");case 2:if(l=new DataView(t),u=new Uint8Array(t),c=l.getUint32(0,!0),A=Tk[c]){e.next=9;break}return this.error("Unsupported .XKT file version: "+c+" - this XKTLoaderPlugin supports versions "+Object.keys(Tk)),e.abrupt("return");case 9:if(!A.parseArrayBuffer){e.next=12;break}return A.parseArrayBuffer(this.viewer,r,t,s,n,o),e.abrupt("return");case 12:for(h=l.getUint32(4,!0),d=[],p=4*(h+2),f=0;fe.size)throw new RangeError("offset:"+t+", length:"+i+", size:"+e.size);return e.slice?e.slice(t,t+i):e.webkitSlice?e.webkitSlice(t,t+i):e.mozSlice?e.mozSlice(t,t+i):e.msSlice?e.msSlice(t,t+i):void 0}(e,t,i))}catch(e){s(e)}}}function p(){}function f(e){var i,r=this;r.init=function(e){i=new Blob([],{type:o}),e()},r.writeUint8Array=function(e,r){i=new Blob([i,t?e:e.buffer],{type:o}),r()},r.getData=function(t,r){var s=new FileReader;s.onload=function(e){t(e.target.result)},s.onerror=r,s.readAsText(i,e)}}function v(t){var i=this,r="",s="";i.init=function(e){r+="data:"+(t||"")+";base64,",e()},i.writeUint8Array=function(t,i){var n,o=s.length,a=s;for(s="",n=0;n<3*Math.floor((o+t.length)/3)-o;n++)a+=String.fromCharCode(t[n]);for(;n2?r+=e.btoa(a):s=a,i()},i.getData=function(t){t(r+e.btoa(s))}}function g(e){var i,r=this;r.init=function(t){i=new Blob([],{type:e}),t()},r.writeUint8Array=function(r,s){i=new Blob([i,t?r:r.buffer],{type:e}),s()},r.getData=function(e){e(i)}}function m(e,t,i,r,s,o,a,l,u,c){var A,h,d,p=0,f=t.sn;function v(){e.removeEventListener("message",g,!1),l(h,d)}function g(t){var i=t.data,s=i.data,n=i.error;if(n)return n.toString=function(){return"Error: "+this.message},void u(n);if(i.sn===f)switch("number"==typeof i.codecTime&&(e.codecTime+=i.codecTime),"number"==typeof i.crcTime&&(e.crcTime+=i.crcTime),i.type){case"append":s?(h+=s.length,r.writeUint8Array(s,(function(){m()}),c)):m();break;case"flush":d=i.crc,s?(h+=s.length,r.writeUint8Array(s,(function(){v()}),c)):v();break;case"progress":a&&a(A+i.loaded,o);break;case"importScripts":case"newTask":case"echo":break;default:console.warn("zip.js:launchWorkerProcess: unknown message: ",i)}}function m(){(A=p*n)<=o?i.readUint8Array(s+A,Math.min(n,o-A),(function(i){a&&a(A,o);var r=0===A?t:{sn:f};r.type="append",r.data=i;try{e.postMessage(r,[i.buffer])}catch(t){e.postMessage(r)}p++}),u):e.postMessage({sn:f,type:"flush"})}h=0,e.addEventListener("message",g,!1),m()}function _(e,t,i,r,s,o,l,u,c,A){var h,d=0,p=0,f="input"===o,v="output"===o,g=new a;!function o(){var a;if((h=d*n)127?s[i-128]:String.fromCharCode(i);return r}function x(e){return decodeURIComponent(escape(e))}function w(e){var t,i="";for(t=0;t>16,i=65535&e;try{return new Date(1980+((65024&t)>>9),((480&t)>>5)-1,31&t,(63488&i)>>11,(2016&i)>>5,2*(31&i),0)}catch(e){}}(e.lastModDateRaw),1!=(1&e.bitFlag)?((r||8!=(8&e.bitFlag))&&(e.crc32=t.view.getUint32(i+10,!0),e.compressedSize=t.view.getUint32(i+14,!0),e.uncompressedSize=t.view.getUint32(i+18,!0)),4294967295!==e.compressedSize&&4294967295!==e.uncompressedSize?(e.filenameLength=t.view.getUint16(i+22,!0),e.extraFieldLength=t.view.getUint16(i+24,!0)):s("File is using Zip64 (4gb+ file size).")):s("File contains encrypted entry.")}function P(t,n,o){var a=0;function l(){}l.prototype.getData=function(r,n,l,c){var A=this;function h(e,t){c&&!function(e){var t=u(4);return t.view.setUint32(0,e),A.crc32==t.view.getUint32(0)}(t)?o("CRC failed."):r.getData((function(e){n(e)}))}function d(e){o(e||s)}function p(e){o(e||"Error while writing file data.")}t.readUint8Array(A.offset,30,(function(s){var n,f=u(s.length,s);1347093252==f.view.getUint32(0)?(B(A,f,4,!1,o),n=A.offset+30+A.filenameLength+A.extraFieldLength,r.init((function(){0===A.compressionMethod?y(A._worker,a++,t,r,n,A.compressedSize,c,h,l,d,p):function(t,i,r,s,n,o,a,l,u,c,A){var h=a?"output":"none";e.zip.useWebWorkers?m(t,{sn:i,codecClass:"Inflater",crcType:h},r,s,n,o,u,l,c,A):_(new e.zip.Inflater,r,s,n,o,h,u,l,c,A)}(A._worker,a++,t,r,n,A.compressedSize,c,h,l,d,p)}),p)):o(i)}),d)};var c={getEntries:function(e){var s=this._worker;!function(e){t.size<22?o(i):s(22,(function(){s(Math.min(65558,t.size),(function(){o(i)}))}));function s(i,s){t.readUint8Array(t.size-i,i,(function(t){for(var i=t.length-22;i>=0;i--)if(80===t[i]&&75===t[i+1]&&5===t[i+2]&&6===t[i+3])return void e(new DataView(t.buffer,i,22));s()}),(function(){o(r)}))}}((function(n){var a,c;a=n.getUint32(16,!0),c=n.getUint16(8,!0),a<0||a>=t.size?o(i):t.readUint8Array(a,t.size-a,(function(t){var r,n,a,A,h=0,d=[],p=u(t.length,t);for(r=0;r>>8^i[255&(t^e[r])];this.crc=t},a.prototype.get=function(){return~this.crc},a.prototype.table=function(){var e,t,i,r=[];for(e=0;e<256;e++){for(i=e,t=0;t<8;t++)1&i?i=i>>>1^3988292384:i>>>=1;r[e]=i}return r}(),l.prototype.append=function(e,t){return e},l.prototype.flush=function(){},A.prototype=new c,A.prototype.constructor=A,h.prototype=new c,h.prototype.constructor=h,d.prototype=new c,d.prototype.constructor=d,p.prototype.getData=function(e){e(this.data)},f.prototype=new p,f.prototype.constructor=f,v.prototype=new p,v.prototype.constructor=v,g.prototype=new p,g.prototype.constructor=g;var F={deflater:["z-worker.js","deflate.js"],inflater:["z-worker.js","inflate.js"]};function k(t,i,r){if(null===e.zip.workerScripts||null===e.zip.workerScriptsPath){var s;if(e.zip.workerScripts){if(s=e.zip.workerScripts[t],!Array.isArray(s))return void r(new Error("zip.workerScripts."+t+" is not an array!"));s=function(e){var t=document.createElement("a");return e.map((function(e){return t.href=e,t.href}))}(s)}else(s=F[t].slice(0))[0]=(e.zip.workerScriptsPath||"")+s[0];var n=new Worker(s[0]);n.codecTime=n.crcTime=0,n.postMessage({type:"importScripts",scripts:s.slice(1)}),n.addEventListener("message",(function e(t){var s=t.data;if(s.error)return n.terminate(),void r(s.error);"importScripts"===s.type&&(n.removeEventListener("message",e),n.removeEventListener("error",o),i(n))})),n.addEventListener("error",o)}else r(new Error("Either zip.workerScripts or zip.workerScriptsPath may be set, not both."));function o(e){n.terminate(),r(e)}}function I(e){console.error(e)}e.zip={Reader:c,Writer:p,BlobReader:d,Data64URIReader:h,TextReader:A,BlobWriter:g,Data64URIWriter:v,TextWriter:f,createReader:function(e,t,i){i=i||I,e.init((function(){P(e,t,i)}),i)},createWriter:function(e,t,i,r){i=i||I,r=!!r,e.init((function(){E(e,t,i,r)}),i)},useWebWorkers:!0,workerScriptsPath:null,workerScripts:null}}(Uk);var Ok=Uk.zip;!function(e){var t,i,r=e.Reader,s=e.Writer;try{i=0===new Blob([new DataView(new ArrayBuffer(0))]).size}catch(e){}function n(e){var t=this;function i(i,r){var s;t.data?i():((s=new XMLHttpRequest).addEventListener("load",(function(){t.size||(t.size=Number(s.getResponseHeader("Content-Length"))||Number(s.response.byteLength)),t.data=new Uint8Array(s.response),i()}),!1),s.addEventListener("error",r,!1),s.open("GET",e),s.responseType="arraybuffer",s.send())}t.size=0,t.init=function(r,s){if(function(e){var t=document.createElement("a");return t.href=e,"http:"===t.protocol||"https:"===t.protocol}(e)){var n=new XMLHttpRequest;n.addEventListener("load",(function(){t.size=Number(n.getResponseHeader("Content-Length")),t.size?r():i(r,s)}),!1),n.addEventListener("error",s,!1),n.open("HEAD",e),n.send()}else i(r,s)},t.readUint8Array=function(e,r,s,n){i((function(){s(new Uint8Array(t.data.subarray(e,e+r)))}),n)}}function o(e){var t=this;t.size=0,t.init=function(i,r){var s=new XMLHttpRequest;s.addEventListener("load",(function(){t.size=Number(s.getResponseHeader("Content-Length")),"bytes"==s.getResponseHeader("Accept-Ranges")?i():r("HTTP Range not supported.")}),!1),s.addEventListener("error",r,!1),s.open("HEAD",e),s.send()},t.readUint8Array=function(t,i,r,s){!function(t,i,r,s){var n=new XMLHttpRequest;n.open("GET",e),n.responseType="arraybuffer",n.setRequestHeader("Range","bytes="+t+"-"+(t+i-1)),n.addEventListener("load",(function(){r(n.response)}),!1),n.addEventListener("error",s,!1),n.send()}(t,i,(function(e){r(new Uint8Array(e))}),s)}}function a(e){var t=this;t.size=0,t.init=function(i,r){t.size=e.byteLength,i()},t.readUint8Array=function(t,i,r,s){r(new Uint8Array(e.slice(t,t+i)))}}function l(){var e,t=this;t.init=function(t,i){e=new Uint8Array,t()},t.writeUint8Array=function(t,i,r){var s=new Uint8Array(e.length+t.length);s.set(e),s.set(t,e.length),e=s,i()},t.getData=function(t){t(e.buffer)}}function u(e,t){var r,s=this;s.init=function(t,i){e.createWriter((function(e){r=e,t()}),i)},s.writeUint8Array=function(e,s,n){var o=new Blob([i?e:e.buffer],{type:t});r.onwrite=function(){r.onwrite=null,s()},r.onerror=n,r.write(o)},s.getData=function(t){e.file(t)}}n.prototype=new r,n.prototype.constructor=n,o.prototype=new r,o.prototype.constructor=o,a.prototype=new r,a.prototype.constructor=a,l.prototype=new s,l.prototype.constructor=l,u.prototype=new s,u.prototype.constructor=u,e.FileWriter=u,e.HttpReader=n,e.HttpRangeReader=o,e.ArrayBufferReader=a,e.ArrayBufferWriter=l,e.fs&&((t=e.fs.ZipDirectoryEntry).prototype.addHttpContent=function(i,r,s){return function(i,r,s,n){if(i.directory)return n?new t(i.fs,r,s,i):new e.fs.ZipFileEntry(i.fs,r,s,i);throw"Parent entry is not a directory."}(this,i,{data:r,Reader:s?o:n})},t.prototype.importHttpContent=function(e,t,i,r){this.importZip(t?new o(e):new n(e),i,r)},e.fs.FS.prototype.importHttpContent=function(e,i,r,s){this.entries=[],this.root=new t(this),this.root.importHttpContent(e,i,r,s)})}(Ok);var Nk=["4.2"],Qk=function(){function e(t){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};B(this,e),this.supportedSchemas=Nk,this._xrayOpacity=.7,this._src=null,this._options=i,this.viewpoint=null,i.workerScriptsPath?(Ok.workerScriptsPath=i.workerScriptsPath,this.src=i.src,this.xrayOpacity=.7,this.displayEffect=i.displayEffect,this.createMetaModel=i.createMetaModel):t.error("Config expected: workerScriptsPath")}return C(e,[{key:"load",value:function(e,t,i,r,s,n){switch(r.materialType){case"MetallicMaterial":t._defaultMaterial=new Nn(t,{baseColor:[1,1,1],metallic:.6,roughness:.6});break;case"SpecularMaterial":t._defaultMaterial=new Hn(t,{diffuse:[1,1,1],specular:re.vec3([1,1,1]),glossiness:.5});break;default:t._defaultMaterial=new qi(t,{reflectivity:.75,shiness:100,diffuse:[1,1,1]})}t._wireframeMaterial=new Rn(t,{color:[0,0,0],lineWidth:2});var o=t.scene.canvas.spinner;o.processes++,Vk(e,t,i,r,(function(){o.processes--,s&&s(),t.fire("loaded",!0,!1)}),(function(e){o.processes--,t.error(e),n&&n(e),t.fire("error",e)}),(function(e){console.log("Error, Will Robinson: "+e)}))}}]),e}(),Vk=function(e,t,i,r,s,n){!function(e,t,i){var r=new Jk;r.load(e,(function(){t(r)}),(function(e){i("Error loading ZIP archive: "+e)}))}(i,(function(i){Hk(e,i,r,t,s,n)}),n)},Hk=function(){return function(t,i,r,s,n){var o={plugin:t,zip:i,edgeThreshold:30,materialType:r.materialType,scene:s.scene,modelNode:s,info:{references:{}},materials:{}};r.createMetaModel&&(o.metaModelData={modelId:s.id,metaObjects:[{name:s.id,type:"Default",id:s.id}]}),s.scene.loading++,function(t,i){t.zip.getFile("Manifest.xml",(function(r,s){for(var n=s.children,o=0,a=n.length;o0){for(var o=n.trim().split(" "),a=new Int16Array(o.length),l=0,u=0,c=o.length;u0){i.primitive="triangles";for(var n=[],o=0,a=s.length;o=t.length)i();else{var a=t[n].id,l=a.lastIndexOf(":");l>0&&(a=a.substring(l+1));var u=a.lastIndexOf("#");u>0&&(a=a.substring(0,u)),r[a]?s(n+1):function(e,t,i){e.zip.getFile(t,(function(t,r){!function(e,t,i){for(var r,s=t.children,n=0,o=s.length;n0)for(var r=0,s=t.length;r1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),r=t.call(this,"XML3DLoader",e,s),s.workerScriptsPath?(r._workerScriptsPath=s.workerScriptsPath,r._loader=new Qk(b(r),s),r.supportedSchemas=r._loader.supportedSchemas,r):(r.error("Config expected: workerScriptsPath"),y(r))}return C(i,[{key:"load",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e.workerScriptsPath=this._workerScriptsPath,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);var t=new Ln(this.viewer.scene,he.apply(e,{isModel:!0})),i=e.src;return i?(this._loader.load(this,t,i,e),t):(this.error("load() param expected: src"),t)}}]),i}(),qk=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};B(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getIFC",value:function(e,t,i){e=this._cacheBusterURL(e);var r=function(){};t=t||r,i=i||r;var s=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(s){var n=!!s[2],o=s[3];o=window.decodeURIComponent(o),n&&(o=window.atob(o));try{for(var a=new ArrayBuffer(o.length),l=new Uint8Array(a),u=0;u1&&void 0!==arguments[1]?arguments[1]:{};if(B(this,i),(r=t.call(this,"ifcLoader",e,s)).dataSource=s.dataSource,r.objectDefaults=s.objectDefaults,r.includeTypes=s.includeTypes,r.excludeTypes=s.excludeTypes,r.excludeUnclassifiedObjects=s.excludeUnclassifiedObjects,!s.WebIFC)throw"Parameter expected: WebIFC";if(!s.IfcAPI)throw"Parameter expected: IfcAPI";return r._webIFC=s.WebIFC,r._ifcAPI=s.IfcAPI,r}return C(i,[{key:"supportedVersions",get:function(){return["2x3","4"]}},{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new qk}},{key:"objectDefaults",get:function(){return this._objectDefaults},set:function(e){this._objectDefaults=e||UE}},{key:"includeTypes",get:function(){return this._includeTypes},set:function(e){this._includeTypes=e}},{key:"excludeTypes",get:function(){return this._excludeTypes},set:function(e){this._excludeTypes=e}},{key:"excludeUnclassifiedObjects",get:function(){return this._excludeUnclassifiedObjects},set:function(e){this._excludeUnclassifiedObjects=!!e}},{key:"globalizeObjectIds",get:function(){return this._globalizeObjectIds},set:function(e){this._globalizeObjectIds=!!e}},{key:"load",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};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);var t=new Qh(this.viewer.scene,he.apply(e,{isModel:!0}));if(!e.src&&!e.ifc)return this.error("load() param expected: src or IFC"),t;var i={autoNormals:!0};if(!1!==e.loadMetadata){var r=e.includeTypes||this._includeTypes,s=e.excludeTypes||this._excludeTypes,n=e.objectDefaults||this._objectDefaults;if(r){i.includeTypesMap={};for(var o=0,a=r.length;o0){for(var l=n.Name.value,u=[],c=0,A=a.length;c0&&void 0!==arguments[0]?arguments[0]:{};B(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getLAS",value:function(e,t,i){e=this._cacheBusterURL(e);var r=function(){};t=t||r,i=i||r;var s=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(s){var n=!!s[2],o=s[3];o=window.decodeURIComponent(o),n&&(o=window.atob(o));try{for(var a=new ArrayBuffer(o.length),l=new Uint8Array(a),u=0;u1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),(r=t.call(this,"lasLoader",e,s)).dataSource=s.dataSource,r.skip=s.skip,r.fp64=s.fp64,r.colorDepth=s.colorDepth,r}return C(i,[{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new eI}},{key:"skip",get:function(){return this._skip},set:function(e){this._skip=e||1}},{key:"fp64",get:function(){return this._fp64},set:function(e){this._fp64=!!e}},{key:"colorDepth",get:function(){return this._colorDepth},set:function(e){this._colorDepth=e||"auto"}},{key:"load",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.id&&this.viewer.scene.components[t.id]&&(this.error("Component with this ID already exists in viewer: "+t.id+" - will autogenerate this ID"),delete t.id);var i=new Qh(this.viewer.scene,he.apply(t,{maxGeometryBatchSize:5e5,isModel:!0}));if(!t.src&&!t.las)return this.error("load() param expected: src or las"),i;var r={las:{skip:this._skip,fp64:this._fp64,colorDepth:this._colorDepth}};if(t.src)this._loadModel(t.src,t,r,i);else{var s=this.viewer.scene.canvas.spinner;s.processes++,this._parseModel(t.las,t,r,i).then((function(){s.processes--}),(function(t){s.processes--,e.error(t),i.fire("error",t)}))}return i}},{key:"_loadModel",value:function(e,t,i,r){var s=this,n=this.viewer.scene.canvas.spinner;n.processes++,this._dataSource.getLAS(t.src,(function(e){s._parseModel(e,t,i,r).then((function(){n.processes--}),(function(e){n.processes--,s.error(e),r.fire("error",e)}))}),(function(e){n.processes--,s.error(e),r.fire("error",e)}))}},{key:"_parseModel",value:function(e,t,i,r){var s=this;function n(e){var i=e.value;if(t.rotateX&&i)for(var r=0,s=i.length;r=e.length)return[e];for(var i=[],r=0;r0&&void 0!==arguments[0]?arguments[0]:{};B(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getCityJSON",value:function(e,t,i){he.loadJSON(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}}]),e}();function cI(e,t,i){i=i||2;var r,s,n,o,a,l,u,c=t&&t.length,A=c?t[0]*i:e.length,h=AI(e,0,A,i,!0),d=[];if(!h||h.next===h.prev)return d;if(c&&(h=function(e,t,i,r){var s,n,o,a=[];for(s=0,n=t.length;s80*i){r=n=e[0],s=o=e[1];for(var p=i;pn&&(n=a),l>o&&(o=l);u=0!==(u=Math.max(n-r,o-s))?1/u:0}return dI(h,d,i,r,s,u),d}function AI(e,t,i,r,s){var n,o;if(s===LI(e,t,i,r)>0)for(n=t;n=t;n-=r)o=DI(n,e[n],e[n+1],o);return o&&CI(o,o.next)&&(SI(o),o=o.next),o}function hI(e,t){if(!e)return e;t||(t=e);var i,r=e;do{if(i=!1,r.steiner||!CI(r,r.next)&&0!==PI(r.prev,r,r.next))r=r.next;else{if(SI(r),(r=t=r.prev)===r.next)break;i=!0}}while(i||r!==t);return t}function dI(e,t,i,r,s,n,o){if(e){!o&&n&&function(e,t,i,r){var s=e;do{null===s.z&&(s.z=bI(s.x,s.y,t,i,r)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next}while(s!==e);s.prevZ.nextZ=null,s.prevZ=null,function(e){var t,i,r,s,n,o,a,l,u=1;do{for(i=e,e=null,n=null,o=0;i;){for(o++,r=i,a=0,t=0;t0||l>0&&r;)0!==a&&(0===l||!r||i.z<=r.z)?(s=i,i=i.nextZ,a--):(s=r,r=r.nextZ,l--),n?n.nextZ=s:e=s,s.prevZ=n,n=s;i=r}n.nextZ=null,u*=2}while(o>1)}(s)}(e,r,s,n);for(var a,l,u=e;e.prev!==e.next;)if(a=e.prev,l=e.next,n?fI(e,r,s,n):pI(e))t.push(a.i/i),t.push(e.i/i),t.push(l.i/i),SI(e),e=l.next,u=l.next;else if((e=l)===u){o?1===o?dI(e=vI(hI(e),t,i),t,i,r,s,n,2):2===o&&gI(e,t,i,r,s,n):dI(hI(e),t,i,r,s,n,1);break}}}function pI(e){var t=e.prev,i=e,r=e.next;if(PI(t,i,r)>=0)return!1;for(var s=e.next.next;s!==e.prev;){if(wI(t.x,t.y,i.x,i.y,r.x,r.y,s.x,s.y)&&PI(s.prev,s,s.next)>=0)return!1;s=s.next}return!0}function fI(e,t,i,r){var s=e.prev,n=e,o=e.next;if(PI(s,n,o)>=0)return!1;for(var a=s.xn.x?s.x>o.x?s.x:o.x:n.x>o.x?n.x:o.x,c=s.y>n.y?s.y>o.y?s.y:o.y:n.y>o.y?n.y:o.y,A=bI(a,l,t,i,r),h=bI(u,c,t,i,r),d=e.prevZ,p=e.nextZ;d&&d.z>=A&&p&&p.z<=h;){if(d!==e.prev&&d!==e.next&&wI(s.x,s.y,n.x,n.y,o.x,o.y,d.x,d.y)&&PI(d.prev,d,d.next)>=0)return!1;if(d=d.prevZ,p!==e.prev&&p!==e.next&&wI(s.x,s.y,n.x,n.y,o.x,o.y,p.x,p.y)&&PI(p.prev,p,p.next)>=0)return!1;p=p.nextZ}for(;d&&d.z>=A;){if(d!==e.prev&&d!==e.next&&wI(s.x,s.y,n.x,n.y,o.x,o.y,d.x,d.y)&&PI(d.prev,d,d.next)>=0)return!1;d=d.prevZ}for(;p&&p.z<=h;){if(p!==e.prev&&p!==e.next&&wI(s.x,s.y,n.x,n.y,o.x,o.y,p.x,p.y)&&PI(p.prev,p,p.next)>=0)return!1;p=p.nextZ}return!0}function vI(e,t,i){var r=e;do{var s=r.prev,n=r.next.next;!CI(s,n)&&MI(s,r,r.next,n)&&kI(s,n)&&kI(n,s)&&(t.push(s.i/i),t.push(r.i/i),t.push(n.i/i),SI(r),SI(r.next),r=e=n),r=r.next}while(r!==e);return hI(r)}function gI(e,t,i,r,s,n){var o=e;do{for(var a=o.next.next;a!==o.prev;){if(o.i!==a.i&&BI(o,a)){var l=II(o,a);return o=hI(o,o.next),l=hI(l,l.next),dI(o,t,i,r,s,n),void dI(l,t,i,r,s,n)}a=a.next}o=o.next}while(o!==e)}function mI(e,t){return e.x-t.x}function _I(e,t){if(t=function(e,t){var i,r=t,s=e.x,n=e.y,o=-1/0;do{if(n<=r.y&&n>=r.next.y&&r.next.y!==r.y){var a=r.x+(n-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(a<=s&&a>o){if(o=a,a===s){if(n===r.y)return r;if(n===r.next.y)return r.next}i=r.x=r.x&&r.x>=c&&s!==r.x&&wI(ni.x||r.x===i.x&&yI(i,r)))&&(i=r,h=l)),r=r.next}while(r!==u);return i}(e,t),t){var i=II(t,e);hI(t,t.next),hI(i,i.next)}}function yI(e,t){return PI(e.prev,e,t.prev)<0&&PI(t.next,e,e.next)<0}function bI(e,t,i,r,s){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-i)*s)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*s)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function xI(e){var t=e,i=e;do{(t.x=0&&(e-o)*(r-a)-(i-o)*(t-a)>=0&&(i-o)*(n-a)-(s-o)*(r-a)>=0}function BI(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){var i=e;do{if(i.i!==e.i&&i.next.i!==e.i&&i.i!==t.i&&i.next.i!==t.i&&MI(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}(e,t)&&(kI(e,t)&&kI(t,e)&&function(e,t){var i=e,r=!1,s=(e.x+t.x)/2,n=(e.y+t.y)/2;do{i.y>n!=i.next.y>n&&i.next.y!==i.y&&s<(i.next.x-i.x)*(n-i.y)/(i.next.y-i.y)+i.x&&(r=!r),i=i.next}while(i!==e);return r}(e,t)&&(PI(e.prev,e,t.prev)||PI(e,t.prev,t))||CI(e,t)&&PI(e.prev,e,e.next)>0&&PI(t.prev,t,t.next)>0)}function PI(e,t,i){return(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y)}function CI(e,t){return e.x===t.x&&e.y===t.y}function MI(e,t,i,r){var s=FI(PI(e,t,i)),n=FI(PI(e,t,r)),o=FI(PI(i,r,e)),a=FI(PI(i,r,t));return s!==n&&o!==a||(!(0!==s||!EI(e,i,t))||(!(0!==n||!EI(e,r,t))||(!(0!==o||!EI(i,e,r))||!(0!==a||!EI(i,t,r)))))}function EI(e,t,i){return t.x<=Math.max(e.x,i.x)&&t.x>=Math.min(e.x,i.x)&&t.y<=Math.max(e.y,i.y)&&t.y>=Math.min(e.y,i.y)}function FI(e){return e>0?1:e<0?-1:0}function kI(e,t){return PI(e.prev,e,e.next)<0?PI(e,t,e.next)>=0&&PI(e,e.prev,t)>=0:PI(e,t,e.prev)<0||PI(e,e.next,t)<0}function II(e,t){var i=new TI(e.i,e.x,e.y),r=new TI(t.i,t.x,t.y),s=e.next,n=t.prev;return e.next=t,t.prev=e,i.next=s,s.prev=i,r.next=i,i.prev=r,n.next=r,r.prev=n,r}function DI(e,t,i,r){var s=new TI(e,t,i);return r?(s.next=r.next,s.prev=r,r.next.prev=s,r.next=s):(s.prev=s,s.next=s),s}function SI(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function TI(e,t,i){this.i=e,this.x=t,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function LI(e,t,i,r){for(var s=0,n=t,o=i-r;n0&&(r+=e[s-1].length,i.holes.push(r))}return i};var RI=re.vec2(),UI=re.vec3(),OI=re.vec3(),NI=re.vec3(),QI=function(e){g(i,Ue);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),(r=t.call(this,"cityJSONLoader",e,s)).dataSource=s.dataSource,r}return C(i,[{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new uI}},{key:"load",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};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);var t=new Qh(this.viewer.scene,he.apply(e,{isModel:!0,edges:!0}));if(!e.src&&!e.cityJSON)return this.error("load() param expected: src or cityJSON"),t;var i={};if(e.src)this._loadModel(e.src,e,i,t);else{var r=this.viewer.scene.canvas.spinner;r.processes++,this._parseModel(e.cityJSON,e,i,t),r.processes--}return t}},{key:"_loadModel",value:function(e,t,i,r){var s=this,n=this.viewer.scene.canvas.spinner;n.processes++,this._dataSource.getCityJSON(t.src,(function(e){s._parseModel(e,t,i,r),n.processes--}),(function(e){n.processes--,s.error(e),r.fire("error",e)}))}},{key:"_parseModel",value:function(e,t,i,r){if(!r.destroyed){var s=e.transform?this._transformVertices(e.vertices,e.transform,i.rotateX):e.vertices,n=t.stats||{};n.sourceFormat=e.type||"CityJSON",n.schemaVersion=e.version||"",n.title="",n.author="",n.created="",n.numMetaObjects=0,n.numPropertySets=0,n.numObjects=0,n.numGeometries=0,n.numTriangles=0,n.numVertices=0;var o=!1!==t.loadMetadata,a=o?{id:re.createUUID(),name:"Model",type:"Model"}:null,l=o?{id:"",projectId:"",author:"",createdAt:"",schema:e.version||"",creatingApplication:"",metaObjects:[a],propertySets:[]}:null,u={data:e,vertices:s,sceneModel:r,loadMetadata:o,metadata:l,rootMetaObject:a,nextId:0,stats:n};if(this._parseCityJSON(u),r.finalize(),o){var c=r.id;this.viewer.metaScene.createMetaModel(c,u.metadata,i)}r.scene.once("tick",(function(){r.destroyed||(r.scene.fire("modelLoaded",r.id),r.fire("loaded",!0,!1))}))}}},{key:"_transformVertices",value:function(e,t,i){for(var r=[],s=t.scale||re.vec3([1,1,1]),n=t.translate||re.vec3([0,0,0]),o=0,a=0;o0){for(var u=[],c=0,A=t.geometry.length;c0){var _=g[m[0]];if(void 0!==_.value)d=v[_.value];else{var y=_.values;if(y){p=[];for(var b=0,x=y.length;b0&&(r.createEntity({id:i,meshIds:u,isObject:!0}),e.stats.numObjects++)}}},{key:"_parseGeometrySurfacesWithOwnMaterials",value:function(e,t,i,r){switch(t.type){case"MultiPoint":case"MultiLineString":break;case"MultiSurface":case"CompositeSurface":var s=t.boundaries;this._parseSurfacesWithOwnMaterials(e,i,s,r);break;case"Solid":for(var n=t.boundaries,o=0;o0&&c.push(u.length);var f=this._extractLocalIndices(e,a[p],A,d);u.push.apply(u,h(f))}if(3===u.length)d.indices.push(u[0]),d.indices.push(u[1]),d.indices.push(u[2]);else if(u.length>3){for(var v=[],g=0;g0&&o.indices.length>0){var f=""+e.nextId++;s.createMesh({id:f,primitive:"triangles",positions:o.positions,indices:o.indices,color:i&&i.diffuseColor?i.diffuseColor:[.8,.8,.8],opacity:1}),r.push(f),e.stats.numGeometries++,e.stats.numVertices+=o.positions.length/3,e.stats.numTriangles+=o.indices.length/3}}},{key:"_parseSurfacesWithSharedMaterial",value:function(e,t,i,r){for(var s=e.vertices,n=0;n0&&a.push(o.length);var u=this._extractLocalIndices(e,t[n][l],i,r);o.push.apply(o,h(u))}if(3===o.length)r.indices.push(o[0]),r.indices.push(o[1]),r.indices.push(o[2]);else if(o.length>3){for(var c=[],A=0;A0&&void 0!==arguments[0]?arguments[0]:{};B(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getDotBIM",value:function(e,t,i){he.loadJSON(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}}]),e}(),HI=function(e){g(i,Ue);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),(r=t.call(this,"DotBIMLoader",e,s)).dataSource=s.dataSource,r.objectDefaults=s.objectDefaults,r}return C(i,[{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new VI}},{key:"objectDefaults",get:function(){return this._objectDefaults},set:function(e){this._objectDefaults=e||UE}},{key:"load",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.id&&this.viewer.scene.components[t.id]&&(this.error("Component with this ID already exists in viewer: "+t.id+" - will autogenerate this ID"),delete t.id);var i=new Qh(this.viewer.scene,he.apply(t,{isModel:!0,backfaces:t.backfaces,dtxEnabled:t.dtxEnabled,rotation:t.rotation,origin:t.origin})),r=i.id;if(!t.src&&!t.dotBIM)return this.error("load() param expected: src or dotBIM"),i;var s,n,o=t.objectDefaults||this._objectDefaults||UE;if(t.includeTypes){s={};for(var a=0,l=t.includeTypes.length;a=0?c:2*Math.PI-c}return s0||o>0||a>0))}}(),n=[],o=(r?t:t.slice(0).reverse()).map((function(e){return{idx:e}}));o.forEach((function(e,t){e.prev=o[(t-1+o.length)%o.length],e.next=o[(t+1)%o.length]}));for(var a=re.vec2(),l=re.vec2();o.length>2;){for(var u=0,c=function(){if(u>=o.length)throw"isCCW = ".concat(r,"; earIdx = ").concat(u,"; len = ").concat(o.length);var t=o[u],i=e[t.prev.idx],n=e[t.idx],c=e[t.next.idx];if(re.subVec2(i,n,a),re.subVec2(c,n,l),a[0]*l[1]-a[1]*l[0]>=0&&o.every((function(r){return r===t||r===t.prev||r===t.next||!s(e[r.idx],i,n,c)})))return"break";++u};;){if("break"===c())break}var A=o[u];o.splice(u,1),n.push([A.idx,A.next.idx,A.prev.idx]),A.prev.next=A.next,A.next.prev=A.prev}return[e,n,r]},zI=function(e,t){var i=e.canvas.canvas,r=i.parentNode,s=document.createElement("div");r.insertBefore(s,i);var n=5;s.style.background=t,s.style.border="2px solid white",s.style.margin="0 0",s.style.zIndex="100",s.style.position="absolute",s.style.pointerEvents="none",s.style.display="none";var o=new ot(e,{}),a=function(e){return e+"px"},l=function(){var e=o.canvasPos.slice();lt(i,r,e),s.style.left=a(e[0]-3-n/2),s.style.top=a(e[1]-3-n/2),s.style.borderRadius=a(2*n),s.style.width=a(n),s.style.height=a(n)},u=e.camera.on("viewMatrix",l),c=e.camera.on("projMatrix",l);return{update:function(e){e&&(o.worldPos=e,l()),s.style.display=e?"":"none"},setHighlighted:function(e){n=e?10:5,l()},getCanvasPos:function(){return o.canvasPos},getWorldPos:function(){return o.worldPos},destroy:function(){s.parentNode.removeChild(s),e.camera.off(u),e.camera.off(c),o.destroy()}}},WI=function(e,t,i){var r=null,s=function(s){if(s){r&&r.destroy();try{var n,o,a=GI(s.map((function(e){return[e[0],e[2]]}))),l=A(a,2),u=l[0],c=l[1],d=(n=[]).concat.apply(n,h(u.map((function(e){return[e[0],s[0][1],e[1]]})))),p=(o=[]).concat.apply(o,h(c));r=new mn(e,{pickable:!1,geometry:new Ki(e,{positions:d,indices:p,normals:re.buildNormals(d,p)}),material:new qi(e,{alpha:void 0!==i?i:.5,backfaces:!0,diffuse:jI(t)})})}catch(e){r=null}}r&&(r.visible=!!s)};return s(null),{updateBase:s,destroy:function(){return r&&r.destroy()}}},KI=function(e,t){return function(i,r,s){var n=e.scene,o=n.canvas.canvas,a=function(e,t){return t[0]=e.clientX,t[1]=e.clientY,lt(o.ownerDocument.documentElement,o,t),t},l=function(e){var i=re.vec3(),r=re.vec3();return re.canvasPosToWorldRay(o,n.camera.viewMatrix,n.camera.projMatrix,n.camera.projection,e,i,r),t(i,r)},u=!1,c=function(){u=!1},A=function(){c(),o.removeEventListener("mousedown",d),o.removeEventListener("mousemove",p),e.cameraControl.off(f),o.removeEventListener("mouseup",v)},h=re.vec2(),d=function(e){1===e.which&&(a(e,h),u=!0)};o.addEventListener("mousedown",d);var p=function(e){var t=a(e,re.vec2());u&&re.distVec2(h,t)>20&&(c(),i())};o.addEventListener("mousemove",p);var f=e.cameraControl.on("rayMove",(function(e){var t=e.canvasPos;r(t,l(t))})),v=function(e){if(1===e.which&&u){A();var t=a(e,re.vec2());s(t,l(t))}};return o.addEventListener("mouseup",v),A}},XI=function(e,t,i,r){var s=-(re.dotVec3(i,t)-e)/re.dotVec3(r,t),n=re.vec3();return re.mulVec3Scalar(r,s,n),re.addVec3(i,n,n),n},JI=function(e){g(i,Ce);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(B(this,i),(r=t.call(this,e.viewer.scene,s)).plugin=e,r._container=s.container,!r._container)throw"config missing: container";return r._eventSubs={},r.plugin.viewer.scene,r._geometry=s.geometry,s.onMouseOver,s.onMouseLeave,s.onContextMenu,r._alpha="alpha"in s&&void 0!==s.alpha?s.alpha:.5,r.color=s.color,r._visible=!0,r._rebuildMesh(),r}return C(i,[{key:"_rebuildMesh",value:function(){var e,t=this.plugin.viewer.scene,i=this._geometry.planeCoordinates.slice(),r=this._geometry.height<0,s=this._geometry.altitude+(r?this._geometry.height:0),n=this._geometry.height*(r?-1:1),o=A(GI(i),3),a=o[0],l=o[1],u=o[2],d=[],p=[],f=function(e){var t,i=d.length,r=c(a);try{for(r.s();!(t=r.n()).done;){var o=t.value;d.push([o[0],s+(e?n:0),o[1]])}}catch(e){r.e(e)}finally{r.f()}var u,A=c(l);try{for(A.s();!(u=A.n()).done;){var f=u.value;p.push.apply(p,h((e?f:f.slice(0).reverse()).map((function(e){return e+i}))))}}catch(e){A.e(e)}finally{A.f()}};f(!1),f(!0);for(var v=function(e){var t=a[e],i=a[(a.length+e+(u?1:-1))%a.length],r=s,o=s+n,l=d.length;d.push([t[0],r,t[1]],[i[0],r,i[1]],[i[0],o,i[1]],[t[0],o,t[1]]),p.push.apply(p,h([0,1,2,0,2,3].map((function(e){return e+l}))))},g=0;gb?1:0;x|=C,w.push(C)}switch(x){case 0:case 1:m.push(y);break;case 2:break;case 3:for(var M=[],E=0;E=3&&m.push(M)}}}catch(e){_.e(e)}finally{_.f()}i=m}}catch(e){d.e(e)}finally{d.f()}if(0===i.length)return null;var U,O=re.vec3([0,0,0]),N=new Set,Q=c(i);try{for(Q.s();!(U=Q.n()).done;){var V,H=c(U.value);try{for(H.s();!(V=H.n()).done;){var j=V.value,G=j.map((function(e){return e.toFixed(3)})).join(":");N.has(G)||(N.add(G),re.addVec3(O,j,O))}}catch(e){H.e(e)}finally{H.f()}}}catch(e){Q.e(e)}finally{Q.f()}return re.mulVec3Scalar(O,1/N.size,O),O}},{key:"center",get:function(){return this._center}},{key:"altitude",get:function(){return this._geometry.altitude},set:function(e){this._geometry.altitude=e,this._rebuildMesh()}},{key:"height",get:function(){return this._geometry.height},set:function(e){this._geometry.height=e,this._rebuildMesh()}},{key:"highlighted",get:function(){return this._highlighted},set:function(e){this._highlighted=e,this._zoneMesh&&(this._zoneMesh.highlighted=e)}},{key:"color",get:function(){return this._color},set:function(e){this._color=e,this._zoneMesh&&(this._zoneMesh.material.diffuse=jI(this._color))}},{key:"alpha",get:function(){return this._alpha},set:function(e){this._alpha=e,this._zoneMesh&&(this._zoneMesh.material.alpha=this._alpha)}},{key:"edges",get:function(){return this._edges},set:function(e){this._edges=e,this._zoneMesh&&(this._zoneMesh.edges=this._edges)}},{key:"visible",get:function(){return this._visible},set:function(e){this._visible=!!e,this._zoneMesh.visible=this._visible,this._needUpdate()}},{key:"getJSON",value:function(){return{id:this.id,geometry:this._geometry,alpha:this._alpha,color:this._color}}},{key:"duplicate",value:function(){return this.plugin.createZone({id:re.createUUID(),geometry:{planeCoordinates:this._geometry.planeCoordinates.map((function(e){return e.slice()})),altitude:this._geometry.altitude,height:this._geometry.height},alpha:this._alpha,color:this._color})}},{key:"destroy",value:function(){this._zoneMesh.destroy(),f(x(i.prototype),"destroy",this).call(this)}}]),i}(),YI=function(e){g(i,Ce);var t=_(i);function i(e,r,s){var n;return B(this,i),(n=t.call(this,e.viewer.scene)).zonesPlugin=e,n.pointerLens=r.pointerLens,n.createSelect3dPoint=s,n._deactivate=null,n}return C(i,[{key:"active",get:function(){return!!this._deactivate}},{key:"activate",value:function(e,t,i,r){if(!this._deactivate){if("object"===w(e)&&null!==e){var s=e,n=function(e,t){if(e in s)return s[e];if(void 0!==t)return t;throw"config missing: "+e};e=n("altitude"),t=n("height"),i=n("color","#008000"),r=n("alpha",.5)}var o=this.zonesPlugin,a=o.viewer,l=a.scene,u=this,c=this.createSelect3dPoint(a,(function(t,i){return XI(e,re.vec3([0,1,0]),t,i)}));!function s(){var n=WI(l,i,r),a=function(e,t,i,r,s,n){var o=zI(e,t),a=zI(e,t),l=i?function(e){i.visible=!!e,e&&(i.canvasPos=e)}:function(){},u=r((function(){l(null),o.update(null)}),(function(e,t){l(e),o.update(t)}),(function(e,t){o.update(t),u=r((function(){l(null),a.update(null),s(null)}),(function(e,i){l(e),a.update(i),s(re.distVec3(t,i)>.01&&[t,i])}),(function(e,i){a.update(i),o.destroy(),a.destroy(),l(null),n([t,i])}))}));return{deactivate:function(){u(),o.destroy(),a.destroy(),l(null)}}}(l,i,u.pointerLens,c,(function(e){if(e){var t=e[0],i=e[1],r=function(e){return Math.min(t[e],i[e])},s=function(e){return Math.max(t[e],i[e])},o=r(0),a=r(1),l=r(2),u=s(0);s(1);var c=s(2);n.updateBase([[o,a,c],[u,a,c],[u,a,l],[o,a,l]])}else n.updateBase(null)}),(function(a){n.destroy();var l=function(e,t,i,r,s,n,o){var a=function(i){return Math.min(e[i],t[i])},l=function(i){return Math.max(e[i],t[i])},u=a(0),c=a(2),A=l(0),h=l(2);return o.createZone({id:re.createUUID(),geometry:{planeCoordinates:[[u,h],[A,h],[A,c],[u,c]],altitude:i,height:r},alpha:n,color:s})}(a[0],a[1],e,t,i,r,o),c=!0;u._deactivate=function(){c=!1},u.fire("zoneEnd",l),c&&s()})).deactivate;u._deactivate=function(){a(),n.destroy()}}()}}},{key:"deactivate",value:function(){this._deactivate&&(this._deactivate(),this._deactivate=null)}},{key:"destroy",value:function(){this.deactivate(),f(x(i.prototype),"destroy",this).call(this)}}]),i}(),ZI=function(e){g(i,YI);var t=_(i);function i(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),t.call(this,e,r,(function(e,t){return KI(e,t)}))}return C(i)}(),qI=function(e){g(i,YI);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};B(this,i);var n=new Re(e.viewer);return(r=t.call(this,e,s,(function(e,t){return ht(e,n,t)}))).pointerCircle=n,r}return C(i,[{key:"destroy",value:function(){this.pointerCircle.destroy(),f(x(i.prototype),"destroy",this).call(this)}}]),i}(),$I=function(e){g(i,Ue);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),(r=t.call(this,"Zones",e))._pointerLens=s.pointerLens,r._container=s.container||document.body,r._zones=[],r.defaultColor=void 0!==s.defaultColor?s.defaultColor:"#00BBFF",r.zIndex=s.zIndex||1e4,r._onMouseOver=function(e,t){r.fire("mouseOver",{plugin:b(r),zone:t,event:e})},r._onMouseLeave=function(e,t){r.fire("mouseLeave",{plugin:b(r),zone:t,event:e})},r._onContextMenu=function(e,t){r.fire("contextMenu",{plugin:b(r),zone:t,event:e})},r}return C(i,[{key:"createZone",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.viewer.scene.components[t.id]&&(this.error("Viewer scene component with this ID already exists: "+t.id),delete t.id);var i=new JI(this,{id:t.id,plugin:this,container:this._container,geometry:t.geometry,alpha:t.alpha,color:t.color,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._zones.push(i),i.on("destroyed",(function(){var t=e._zones.indexOf(i);t>=0&&e._zones.splice(t,1)})),this.fire("zoneCreated",i),i}},{key:"zones",get:function(){return this._zones}},{key:"destroy",value:function(){f(x(i.prototype),"destroy",this).call(this)}}]),i}(),eD=function(e,t,i,r,s,n,o,a,l){var u,c=n?function(e){n.visible=!!e,e&&(n.canvasPos=e)}:function(){},A=[function(){return c(null)}],h=WI(e,r,s);return A.push((function(){return h.destroy()})),function n(d){var p=zI(e,r),f=d.length>0&&function(e,t,i){var r=e.canvas.canvas,s=new ot(e,{});s.worldPos=i;var n=new ot(e,{}),o=r.ownerDocument.body,a=new dt(o,{color:t,thickness:1,thicknessClickable:6});a.setVisible(!1);var l=function(){var e=s.canvasPos.slice(),t=n.canvasPos.slice();lt(r,o,e),lt(r,o,t),a.setStartAndEnd(e[0],e[1],t[0],t[1])},u=e.camera.on("viewMatrix",l),c=e.camera.on("projMatrix",l);return{update:function(e){e&&(n.worldPos=e,l()),a.setVisible(!!e)},destroy:function(){e.camera.off(u),e.camera.off(c),s.destroy(),n.destroy(),a.destroy()}}}(e,r,d[d.length-1].getWorldPos());A.push((function(){p.destroy(),f&&f.destroy()}));var v=d.length>0&&d[0],g=function(e){var t=v&&v.getCanvasPos();return t&&re.distVec2(t,e)<10&&{canvasPos:t,worldPos:v.getWorldPos()}},m=function(){var e=function(e,t,i){return t[0]<=Math.max(e[0],i[0])&&t[0]>=Math.min(e[0],i[0])&&t[1]<=Math.max(e[1],i[1])&&t[1]>=Math.min(e[1],i[1])},t=function(e,t,i){var r=(t[1]-e[1])*(i[0]-t[0])-(t[0]-e[0])*(i[1]-t[1]);return 0===r?0:r>0?1:2};return function(i,r){for(var s=i[i.length-2],n=i[i.length-1],o=r?1:0;o2?d.map((function(e){return e.getWorldPos()})):null)}),(function(e,t){var i=d.length>2&&g(e);if(v&&v.setHighlighted(!!i),c(i?i.canvasPos:e),p.update(!i&&t),f&&f.update(i?i.worldPos:t),d.length>=2){var r=d.map((function(e){return e.getWorldPos()})).concat(i?[]:[t]),s=m(r.map((function(e){return[e[0],e[2]]})),i);h.updateBase(s?null:r)}else h.updateBase(null)}),(function(e,a){var u=d.length>2&&g(e),c=d.map((function(e){return e.getWorldPos()})).concat(u?[]:[a]);h.updateBase(c);var v=c.map((function(e){return[e[0],e[2]]}));d.length>2&&m(v,u)?(A.pop()(),n(d)):u?(p.update(a),A.forEach((function(e){return e()})),l(o.createZone({id:re.createUUID(),geometry:{planeCoordinates:v,altitude:t,height:i},alpha:s,color:r}))):(p.update(a),f&&f.update(a),n(d.concat(p)))}))}([]),{closeSurface:function(){throw"TODO"},deactivate:function(){u(),A.forEach((function(e){return e()}))}}},tD=function(e){g(i,Ce);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),(r=t.call(this,e.viewer.scene)).zonesPlugin=e,r.pointerLens=s.pointerLens,r._action=null,r}return C(i,[{key:"active",get:function(){return!!this._action}},{key:"activate",value:function(e,t,i,r){if("object"===w(e)&&null!==e){var s=e,n=function(e,t){if(e in s)return s[e];if(void 0!==t)return t;throw"config missing: "+e};e=n("altitude"),t=n("height"),i=n("color","#008000"),r=n("alpha",.5)}if(!this._action){var o=this.zonesPlugin,a=o.viewer,l=a.scene,u=this,c=KI(a,(function(t,i){return XI(e,re.vec3([0,1,0]),t,i)}));!function s(){u._action=eD(l,e,t,i,r,u.pointerLens,o,c,(function(e){var t=!0;u._action={deactivate:function(){t=!1}},u.fire("zoneEnd",e),t&&s()}))}()}}},{key:"deactivate",value:function(){this._action&&(this._action.deactivate(),this._action=null)}},{key:"destroy",value:function(){this.deactivate(),f(x(i.prototype),"destroy",this).call(this)}}]),i}(),iD=function(e){g(i,Ce);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),(r=t.call(this,e.viewer.scene)).zonesPlugin=e,r.pointerLens=s.pointerLens,r.pointerCircle=new Re(e.viewer),r._action=null,r}return C(i,[{key:"active",get:function(){return!!this._action}},{key:"activate",value:function(e,t,i,r){if("object"===w(e)&&null!==e){var s=e,n=function(e,t){if(e in s)return s[e];if(void 0!==t)return t;throw"config missing: "+e};e=n("altitude"),t=n("height"),i=n("color","#008000"),r=n("alpha",.5)}if(!this._action){var o=this.zonesPlugin,a=o.viewer,l=a.scene,u=this,c=ht(a,this.pointerCircle,(function(t,i){return XI(e,re.vec3([0,1,0]),t,i)}));!function s(){u._action=eD(l,e,t,i,r,u.pointerLens,o,c,(function(e){var t=!0;u._action={deactivate:function(){t=!1}},u.fire("zoneEnd",e),t&&s()}))}()}}},{key:"deactivate",value:function(){this._action&&(this._action.deactivate(),this._action=null)}},{key:"destroy",value:function(){this.deactivate(),f(x(i.prototype),"destroy",this).call(this)}}]),i}(),rD=function(e){g(i,Ce);var t=_(i);function i(e,r,s,n){var o;B(this,i);var a=e.plugin.viewer,l=a.scene;o=t.call(this,l);var u=e._geometry.altitude,c=e._geometry.planeCoordinates.map((function(t){var i=l.canvas.canvas.ownerDocument.body,r=new ut(l,{},i,{fillColor:e._color});return r.worldPos=re.vec3([t[0],u,t[1]]),r.on("worldPos",(function(){t[0]=r.worldPos[0],t[1]=r.worldPos[2];try{e._rebuildMesh()}catch(t){e._zoneMesh&&(e._zoneMesh.destroy(),e._zoneMesh=null)}})),r})),A=At({viewer:a,handleMouseEvents:s,handleTouchEvents:n,pointerLens:r&&r.pointerLens,dots:c,ray2WorldPos:function(e,t){return XI(u,re.vec3([0,1,0]),e,t)},onEnd:function(t,i){return e._zoneMesh&&o.fire("edited"),!!e._zoneMesh}}),h=function(){A(),c.forEach((function(e){return e.destroy()}))},d=e.on("destroyed",h);return o._deactivate=function(){e.off("destroyed",d),h()},o}return C(i,[{key:"deactivate",value:function(){this._deactivate(),f(x(i.prototype),"destroy",this).call(this)}}]),i}(),sD=function(e){g(i,rD);var t=_(i);function i(e,r){return B(this,i),t.call(this,e,r,!0,!1)}return C(i)}(),nD=function(e){g(i,rD);var t=_(i);function i(e,r){return B(this,i),t.call(this,e,r,!1,!0)}return C(i)}(),oD=function(e){g(i,Ce);var t=_(i);function i(e,r,s,n){var o;B(this,i);var a=e.plugin.viewer,l=a.scene,u=l.canvas.canvas,c=b(o=t.call(this,l)),A=e._geometry.altitude,d=r&&r.pointerLens,p=d?function(e){d.visible=!!e,e&&(d.canvasPos=e)}:function(){},f=function(e){var t,i,r=re.vec3(),s=re.vec3();return re.canvasPosToWorldRay(u,l.camera.viewMatrix,l.camera.projMatrix,l.camera.projection,e,r,s),t=r,i=s,XI(A,re.vec3([0,1,0]),t,i)},v=function(e,t){return t[0]=e.clientX,t[1]=e.clientY,lt(u.ownerDocument.documentElement,u,t),t},g=function(e,t){var i=function(e){e.preventDefault(),t(e)};return u.addEventListener(e,i),function(){return u.removeEventListener(e,i)}},m=function(){},_=function(t,i,r,s){var n,o,l,A,h=s(t),d=v(h,re.vec2()),_=a.scene.pick({canvasPos:d,includeEntities:[e._zoneMesh.id]});if((_&&_.entity&&_.entity.zone)===e){m(),u.style.cursor="move",a.cameraControl.active=!1;var y=(n=e._geometry.planeCoordinates.map((function(e){return e.slice()})),o=f(d),l=re.vec2([o[0],o[2]]),A=re.vec2(),function(t){var i=f(t);A[0]=i[0],A[1]=i[2],re.subVec2(l,A,A),e._geometry.planeCoordinates.forEach((function(e,t){re.subVec2(n[t],A,e)}));try{e._rebuildMesh()}catch(t){e._zoneMesh&&(e._zoneMesh.destroy(),e._zoneMesh=null)}}),b=g(i,(function(e){var t=s(e);if(t){var i=v(t,re.vec2());y(i),p(i)}})),x=g(r,(function(e){var t=s(e);if(t){var i=v(t,re.vec2());y(i),p(null),m(),c.fire("translated")}}));m=function(){m=function(){},u.style.cursor="default",a.cameraControl.active=!0,b(),x()}}},y=[];s&&y.push(g("mousedown",(function(e){1===e.which&&_(e,"mousemove","mouseup",(function(e){return 1===e.which&&e}))}))),n&&y.push(g("touchstart",(function(e){if(1===e.touches.length){var t=e.touches[0].identifier;_(e,"touchmove","touchend",(function(e){return h(e.changedTouches).find((function(e){return e.identifier===t}))}))}})));var x=function(){m(),y.forEach((function(e){return e()})),p(null)},w=e.on("destroyed",x);return o._deactivate=function(){e.off("destroyed",w),x()},o}return C(i,[{key:"deactivate",value:function(){this._deactivate(),f(x(i.prototype),"destroy",this).call(this)}}]),i}(),aD=function(e){g(i,oD);var t=_(i);function i(e,r){return B(this,i),t.call(this,e,r,!0,!1)}return C(i)}(),lD=function(e){g(i,oD);var t=_(i);function i(e,r){return B(this,i),t.call(this,e,r,!1,!0)}return C(i)}();export{Ur as AlphaFormat,Li as AmbientLight,wt as AngleMeasurementEditMouseControl,Bt as AngleMeasurementEditTouchControl,mt as AngleMeasurementsControl,_t as AngleMeasurementsMouseControl,yt as AngleMeasurementsPlugin,bt as AngleMeasurementsTouchControl,Ft as AnnotationsPlugin,Bn as AxisGizmoPlugin,Kh as BCFViewpointsPlugin,po as Bitmap,Mr as ByteType,Od as CameraMemento,md as CameraPath,Pd as CameraPathAnimation,QI as CityJSONLoaderPlugin,pr as ClampToEdgeWrapping,Ce as Component,Cs as CompressedMediaType,wa as Configs,J as ContextMenu,jd as CubicBezierCurve,fd as Curve,sh as DefaultLoadingManager,Hr as DepthFormat,jr as DepthStencilFormat,Ti as DirLight,ad as DistanceMeasurementEditControl,ld as DistanceMeasurementEditMouseControl,ud as DistanceMeasurementEditTouchControl,rd as DistanceMeasurementsControl,sd as DistanceMeasurementsMouseControl,nd as DistanceMeasurementsPlugin,od as DistanceMeasurementsTouchControl,ut as Dot3D,VI as DotBIMDefaultDataSource,HI as DotBIMLoaderPlugin,ir as EdgeMaterial,er as EmphasisMaterial,yF as FaceAlignedSectionPlanesPlugin,cd as FastNavPlugin,Dr as FloatType,qn as Fresnel,Ie as Frustum,ke as FrustumPlane,ws as GIFMediaType,Ad as GLTFDefaultDataSource,OE as GLTFLoaderPlugin,Sr as HalfFloatType,kd as ImagePlane,kr as IntType,Bs as JPEGMediaType,ch as KTX2TextureTranscoder,aI as LASLoaderPlugin,Rn as LambertMaterial,Rd as LightMap,Hh as LineSet,bs as LinearEncoding,br as LinearFilter,Pr as LinearMipMapLinearFilter,wr as LinearMipMapNearestFilter,Br as LinearMipmapLinearFilter,xr as LinearMipmapNearestFilter,nh as Loader,rh as LoadingManager,hd as LocaleService,Vr as LuminanceAlphaFormat,Qr as LuminanceFormat,G as Map,ot as Marker,Te as MarqueePicker,Le as MarqueePickerMouseControl,mn as Mesh,Mo as MeshSurfaceArea,_o as MeshVolume,Nn as MetallicMaterial,fr as MirroredRepeatWrapping,Qd as ModelMemento,HE as NavCubePlugin,vr as NearestFilter,yr as NearestMipMapLinearFilter,gr as NearestMipMapNearestFilter,_r as NearestMipmapLinearFilter,mr as NearestMipmapNearestFilter,Ln as Node,qE as OBJLoaderPlugin,ne as ObjectsKdTree3,Hd as ObjectsMemento,Ps as PNGMediaType,Gd as Path,Wd as PerformanceModel,qi as PhongMaterial,Ut as PickResult,Ue as Plugin,Id as PointLight,Re as PointerCircle,Y as PointerLens,zd as QuadraticBezierCurve,oe as Queue,Nr as RGBAFormat,Xr as RGBAIntegerFormat,gs as RGBA_ASTC_10x10_Format,ps as RGBA_ASTC_10x5_Format,fs as RGBA_ASTC_10x6_Format,vs as RGBA_ASTC_10x8_Format,ms as RGBA_ASTC_12x10_Format,_s as RGBA_ASTC_12x12_Format,os as RGBA_ASTC_4x4_Format,as as RGBA_ASTC_5x4_Format,ls as RGBA_ASTC_5x5_Format,us as RGBA_ASTC_6x5_Format,cs as RGBA_ASTC_6x6_Format,As as RGBA_ASTC_8x5_Format,hs as RGBA_ASTC_8x6_Format,ds as RGBA_ASTC_8x8_Format,ys as RGBA_BPTC_Format,ns as RGBA_ETC2_EAC_Format,is as RGBA_PVRTC_2BPPV1_Format,ts as RGBA_PVRTC_4BPPV1_Format,Yr as RGBA_S3TC_DXT1_Format,Zr as RGBA_S3TC_DXT3_Format,qr as RGBA_S3TC_DXT5_Format,Or as RGBFormat,rs as RGB_ETC1_Format,ss as RGB_ETC2_Format,es as RGB_PVRTC_2BPPV1_Format,$r as RGB_PVRTC_4BPPV1_Format,Jr as RGB_S3TC_DXT1_Format,Wr as RGFormat,Kr as RGIntegerFormat,Ki as ReadableGeometry,Gr as RedFormat,zr as RedIntegerFormat,Ld as ReflectionMap,dr as RepeatWrapping,xF as STLDefaultDataSource,IF as STLLoaderPlugin,Qh as SceneModel,Do as SceneModelMesh,Ih as SceneModelTransform,Pn as SectionPlane,oF as SectionPlanesPlugin,Er as ShortType,Kd as Skybox,bF as SkyboxesPlugin,Hn as SpecularMaterial,vd as SplineCurve,Ud as SpriteMarker,hF as StoreyViewsPlugin,Zn as Texture,Xd as TextureTranscoder,TF as TreeViewPlugin,Cr as UnsignedByteType,Rr as UnsignedInt248Type,Ir as UnsignedIntType,Tr as UnsignedShort4444Type,Lr as UnsignedShort5551Type,Fr as UnsignedShortType,to as VBOGeometry,NF as ViewCullPlugin,Ub as Viewer,$k as WebIFCLoaderPlugin,lh as WorkerPool,QF as XKTDefaultDataSource,Lk as XKTLoaderPlugin,Zk as XML3DLoaderPlugin,rD as ZoneEditControl,sD as ZoneEditMouseControl,nD as ZoneEditTouchControl,oD as ZoneTranslateControl,aD as ZoneTranslateMouseControl,lD as ZoneTranslateTouchControl,ZI as ZonesMouseControl,$I as ZonesPlugin,tD as ZonesPolysurfaceMouseControl,iD as ZonesPolysurfaceTouchControl,qI as ZonesTouchControl,ct as activateDraggableDot,At as activateDraggableDots,Xi as buildBoxGeometry,no as buildBoxLinesGeometry,oo as buildBoxLinesGeometryFromAABB,yn as buildCylinderGeometry,ao as buildGridGeometry,ho as buildLineGeometry,lo as buildPlaneGeometry,co as buildPolylineGeometry,Ao as buildPolylineGeometryFromCurve,bn as buildSphereGeometry,uo as buildTorusGeometry,wn as buildVectorTextGeometry,Ve as createRTCViewMat,Se as frustumIntersectsAABB3,hh as getKTX2TextureTranscoder,ze as getPlaneRTCPos,fo as isTriangleMeshSolid,ro as load3DSGeometry,so as loadOBJGeometry,re as math,Eo as meshSurfaceArea,yo as meshVolume,Ge as rtcToWorldPos,xs as sRGBEncoding,De as setFrustum,ae as stats,ht as touchPointSelector,lt as transformToNode,he as utils,He as worldToRTCPos,je as worldToRTCPositions}; +***************************************************************************** */var Op=function(e,t){return Op=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},Op(e,t)};function Np(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}Op(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}var Qp=function(){return Qp=Object.assign||function(e){for(var t,i=1,r=arguments.length;i0&&s[s.length-1])||6!==n[0]&&2!==n[0])){o=0;continue}if(3===n[0]&&(!s||n[1]>s[0]&&n[1]=55296&&s<=56319&&i>10),o%1024+56320)),(s+1===i||r.length>16384)&&(n+=String.fromCharCode.apply(String,r),r.length=0)}return n},Xp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Jp="undefined"==typeof Uint8Array?[]:new Uint8Array(256),Yp=0;Yp=0){if(e<55296||e>56319&&e<=65535)return t=((t=this.index[e>>5])<<2)+(31&e),this.data[t];if(e<=65535)return t=((t=this.index[2048+(e-55296>>5)])<<2)+(31&e),this.data[t];if(e>11),t=this.index[t],t+=e>>5&63,t=((t=this.index[t])<<2)+(31&e),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},e}(),rf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",sf="undefined"==typeof Uint8Array?[]:new Uint8Array(256),nf=0;nf>4,c[l++]=(15&r)<<4|s>>2,c[l++]=(3&s)<<6|63&n;return u}(e),o=Array.isArray(n)?function(e){for(var t=e.length,i=[],r=0;r0;){var o=r[--n];if(Array.isArray(e)?-1!==e.indexOf(o):e===o)for(var a=i;a<=r.length;){var l;if((l=r[++a])===t)return!0;if(l!==of)break}if(o!==of)break}return!1},Qf=function(e,t){for(var i=e;i>=0;){var r=t[i];if(r!==of)return r;i--}return 0},Vf=function(e,t,i,r,s){if(0===i[r])return"×";var n=r-1;if(Array.isArray(s)&&!0===s[n])return"×";var o=n-1,a=n+1,l=t[n],u=o>=0?t[o]:0,c=t[a];if(2===l&&3===c)return"×";if(-1!==Sf.indexOf(l))return"!";if(-1!==Sf.indexOf(c))return"×";if(-1!==Tf.indexOf(c))return"×";if(8===Qf(n,t))return"÷";if(11===If.get(e[n]))return"×";if((l===bf||l===xf)&&11===If.get(e[a]))return"×";if(7===l||7===c)return"×";if(9===l)return"×";if(-1===[of,af,lf].indexOf(l)&&9===c)return"×";if(-1!==[uf,cf,Af,ff,_f].indexOf(c))return"×";if(Qf(n,t)===pf)return"×";if(Nf(23,pf,n,t))return"×";if(Nf([uf,cf],df,n,t))return"×";if(Nf(12,12,n,t))return"×";if(l===of)return"÷";if(23===l||23===c)return"×";if(16===c||16===l)return"÷";if(-1!==[af,lf,df].indexOf(c)||14===l)return"×";if(36===u&&-1!==Of.indexOf(l))return"×";if(l===_f&&36===c)return"×";if(c===hf)return"×";if(-1!==Df.indexOf(c)&&l===vf||-1!==Df.indexOf(l)&&c===vf)return"×";if(l===mf&&-1!==[Pf,bf,xf].indexOf(c)||-1!==[Pf,bf,xf].indexOf(l)&&c===gf)return"×";if(-1!==Df.indexOf(l)&&-1!==Lf.indexOf(c)||-1!==Lf.indexOf(l)&&-1!==Df.indexOf(c))return"×";if(-1!==[mf,gf].indexOf(l)&&(c===vf||-1!==[pf,lf].indexOf(c)&&t[a+1]===vf)||-1!==[pf,lf].indexOf(l)&&c===vf||l===vf&&-1!==[vf,_f,ff].indexOf(c))return"×";if(-1!==[vf,_f,ff,uf,cf].indexOf(c))for(var A=n;A>=0;){if((h=t[A])===vf)return"×";if(-1===[_f,ff].indexOf(h))break;A--}if(-1!==[mf,gf].indexOf(c))for(A=-1!==[uf,cf].indexOf(l)?o:n;A>=0;){var h;if((h=t[A])===vf)return"×";if(-1===[_f,ff].indexOf(h))break;A--}if(Cf===l&&-1!==[Cf,Mf,wf,Bf].indexOf(c)||-1!==[Mf,wf].indexOf(l)&&-1!==[Mf,Ef].indexOf(c)||-1!==[Ef,Bf].indexOf(l)&&c===Ef)return"×";if(-1!==Uf.indexOf(l)&&-1!==[hf,gf].indexOf(c)||-1!==Uf.indexOf(c)&&l===mf)return"×";if(-1!==Df.indexOf(l)&&-1!==Df.indexOf(c))return"×";if(l===ff&&-1!==Df.indexOf(c))return"×";if(-1!==Df.concat(vf).indexOf(l)&&c===pf&&-1===kf.indexOf(e[a])||-1!==Df.concat(vf).indexOf(c)&&l===cf)return"×";if(41===l&&41===c){for(var d=i[n],p=1;d>0&&41===t[--d];)p++;if(p%2!=0)return"×"}return l===bf&&c===xf?"×":"÷"},Hf=function(e,t){t||(t={lineBreak:"normal",wordBreak:"normal"});var i=function(e,t){void 0===t&&(t="strict");var i=[],r=[],s=[];return e.forEach((function(e,n){var o=If.get(e);if(o>50?(s.push(!0),o-=50):s.push(!1),-1!==["normal","auto","loose"].indexOf(t)&&-1!==[8208,8211,12316,12448].indexOf(e))return r.push(n),i.push(16);if(4===o||11===o){if(0===n)return r.push(n),i.push(yf);var a=i[n-1];return-1===Rf.indexOf(a)?(r.push(r[n-1]),i.push(a)):(r.push(n),i.push(yf))}return r.push(n),31===o?i.push("strict"===t?df:Pf):o===Ff||29===o?i.push(yf):43===o?e>=131072&&e<=196605||e>=196608&&e<=262141?i.push(Pf):i.push(yf):void i.push(o)})),[r,i,s]}(e,t.lineBreak),r=i[0],s=i[1],n=i[2];"break-all"!==t.wordBreak&&"break-word"!==t.wordBreak||(s=s.map((function(e){return-1!==[vf,yf,Ff].indexOf(e)?Pf:e})));var o="keep-all"===t.wordBreak?n.map((function(t,i){return t&&e[i]>=19968&&e[i]<=40959})):void 0;return[r,s,o]},jf=function(){function e(e,t,i,r){this.codePoints=e,this.required="!"===t,this.start=i,this.end=r}return e.prototype.slice=function(){return Kp.apply(void 0,this.codePoints.slice(this.start,this.end))},e}(),Gf=function(e){return e>=48&&e<=57},zf=function(e){return Gf(e)||e>=65&&e<=70||e>=97&&e<=102},Wf=function(e){return 10===e||9===e||32===e},Kf=function(e){return function(e){return function(e){return e>=97&&e<=122}(e)||function(e){return e>=65&&e<=90}(e)}(e)||function(e){return e>=128}(e)||95===e},Xf=function(e){return Kf(e)||Gf(e)||45===e},Jf=function(e){return e>=0&&e<=8||11===e||e>=14&&e<=31||127===e},Yf=function(e,t){return 92===e&&10!==t},Zf=function(e,t,i){return 45===e?Kf(t)||Yf(t,i):!!Kf(e)||!(92!==e||!Yf(e,t))},qf=function(e,t,i){return 43===e||45===e?!!Gf(t)||46===t&&Gf(i):Gf(46===e?t:e)},$f=function(e){var t=0,i=1;43!==e[t]&&45!==e[t]||(45===e[t]&&(i=-1),t++);for(var r=[];Gf(e[t]);)r.push(e[t++]);var s=r.length?parseInt(Kp.apply(void 0,r),10):0;46===e[t]&&t++;for(var n=[];Gf(e[t]);)n.push(e[t++]);var o=n.length,a=o?parseInt(Kp.apply(void 0,n),10):0;69!==e[t]&&101!==e[t]||t++;var l=1;43!==e[t]&&45!==e[t]||(45===e[t]&&(l=-1),t++);for(var u=[];Gf(e[t]);)u.push(e[t++]);var c=u.length?parseInt(Kp.apply(void 0,u),10):0;return i*(s+a*Math.pow(10,-o))*Math.pow(10,l*c)},ev={type:2},tv={type:3},iv={type:4},rv={type:13},sv={type:8},nv={type:21},ov={type:9},av={type:10},lv={type:11},uv={type:12},cv={type:14},Av={type:23},hv={type:1},dv={type:25},pv={type:24},fv={type:26},vv={type:27},gv={type:28},mv={type:29},_v={type:31},yv={type:32},bv=function(){function e(){this._value=[]}return e.prototype.write=function(e){this._value=this._value.concat(Wp(e))},e.prototype.read=function(){for(var e=[],t=this.consumeToken();t!==yv;)e.push(t),t=this.consumeToken();return e},e.prototype.consumeToken=function(){var e=this.consumeCodePoint();switch(e){case 34:return this.consumeStringToken(34);case 35:var t=this.peekCodePoint(0),i=this.peekCodePoint(1),r=this.peekCodePoint(2);if(Xf(t)||Yf(i,r)){var s=Zf(t,i,r)?2:1;return{type:5,value:this.consumeName(),flags:s}}break;case 36:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),rv;break;case 39:return this.consumeStringToken(39);case 40:return ev;case 41:return tv;case 42:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),cv;break;case 43:if(qf(e,this.peekCodePoint(0),this.peekCodePoint(1)))return this.reconsumeCodePoint(e),this.consumeNumericToken();break;case 44:return iv;case 45:var n=e,o=this.peekCodePoint(0),a=this.peekCodePoint(1);if(qf(n,o,a))return this.reconsumeCodePoint(e),this.consumeNumericToken();if(Zf(n,o,a))return this.reconsumeCodePoint(e),this.consumeIdentLikeToken();if(45===o&&62===a)return this.consumeCodePoint(),this.consumeCodePoint(),pv;break;case 46:if(qf(e,this.peekCodePoint(0),this.peekCodePoint(1)))return this.reconsumeCodePoint(e),this.consumeNumericToken();break;case 47:if(42===this.peekCodePoint(0))for(this.consumeCodePoint();;){var l=this.consumeCodePoint();if(42===l&&47===(l=this.consumeCodePoint()))return this.consumeToken();if(-1===l)return this.consumeToken()}break;case 58:return fv;case 59:return vv;case 60:if(33===this.peekCodePoint(0)&&45===this.peekCodePoint(1)&&45===this.peekCodePoint(2))return this.consumeCodePoint(),this.consumeCodePoint(),dv;break;case 64:var u=this.peekCodePoint(0),c=this.peekCodePoint(1),A=this.peekCodePoint(2);if(Zf(u,c,A))return{type:7,value:this.consumeName()};break;case 91:return gv;case 92:if(Yf(e,this.peekCodePoint(0)))return this.reconsumeCodePoint(e),this.consumeIdentLikeToken();break;case 93:return mv;case 61:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),sv;break;case 123:return lv;case 125:return uv;case 117:case 85:var h=this.peekCodePoint(0),d=this.peekCodePoint(1);return 43!==h||!zf(d)&&63!==d||(this.consumeCodePoint(),this.consumeUnicodeRangeToken()),this.reconsumeCodePoint(e),this.consumeIdentLikeToken();case 124:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),ov;if(124===this.peekCodePoint(0))return this.consumeCodePoint(),nv;break;case 126:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),av;break;case-1:return yv}return Wf(e)?(this.consumeWhiteSpace(),_v):Gf(e)?(this.reconsumeCodePoint(e),this.consumeNumericToken()):Kf(e)?(this.reconsumeCodePoint(e),this.consumeIdentLikeToken()):{type:6,value:Kp(e)}},e.prototype.consumeCodePoint=function(){var e=this._value.shift();return void 0===e?-1:e},e.prototype.reconsumeCodePoint=function(e){this._value.unshift(e)},e.prototype.peekCodePoint=function(e){return e>=this._value.length?-1:this._value[e]},e.prototype.consumeUnicodeRangeToken=function(){for(var e=[],t=this.consumeCodePoint();zf(t)&&e.length<6;)e.push(t),t=this.consumeCodePoint();for(var i=!1;63===t&&e.length<6;)e.push(t),t=this.consumeCodePoint(),i=!0;if(i)return{type:30,start:parseInt(Kp.apply(void 0,e.map((function(e){return 63===e?48:e}))),16),end:parseInt(Kp.apply(void 0,e.map((function(e){return 63===e?70:e}))),16)};var r=parseInt(Kp.apply(void 0,e),16);if(45===this.peekCodePoint(0)&&zf(this.peekCodePoint(1))){this.consumeCodePoint(),t=this.consumeCodePoint();for(var s=[];zf(t)&&s.length<6;)s.push(t),t=this.consumeCodePoint();return{type:30,start:r,end:parseInt(Kp.apply(void 0,s),16)}}return{type:30,start:r,end:r}},e.prototype.consumeIdentLikeToken=function(){var e=this.consumeName();return"url"===e.toLowerCase()&&40===this.peekCodePoint(0)?(this.consumeCodePoint(),this.consumeUrlToken()):40===this.peekCodePoint(0)?(this.consumeCodePoint(),{type:19,value:e}):{type:20,value:e}},e.prototype.consumeUrlToken=function(){var e=[];if(this.consumeWhiteSpace(),-1===this.peekCodePoint(0))return{type:22,value:""};var t=this.peekCodePoint(0);if(39===t||34===t){var i=this.consumeStringToken(this.consumeCodePoint());return 0===i.type&&(this.consumeWhiteSpace(),-1===this.peekCodePoint(0)||41===this.peekCodePoint(0))?(this.consumeCodePoint(),{type:22,value:i.value}):(this.consumeBadUrlRemnants(),Av)}for(;;){var r=this.consumeCodePoint();if(-1===r||41===r)return{type:22,value:Kp.apply(void 0,e)};if(Wf(r))return this.consumeWhiteSpace(),-1===this.peekCodePoint(0)||41===this.peekCodePoint(0)?(this.consumeCodePoint(),{type:22,value:Kp.apply(void 0,e)}):(this.consumeBadUrlRemnants(),Av);if(34===r||39===r||40===r||Jf(r))return this.consumeBadUrlRemnants(),Av;if(92===r){if(!Yf(r,this.peekCodePoint(0)))return this.consumeBadUrlRemnants(),Av;e.push(this.consumeEscapedCodePoint())}else e.push(r)}},e.prototype.consumeWhiteSpace=function(){for(;Wf(this.peekCodePoint(0));)this.consumeCodePoint()},e.prototype.consumeBadUrlRemnants=function(){for(;;){var e=this.consumeCodePoint();if(41===e||-1===e)return;Yf(e,this.peekCodePoint(0))&&this.consumeEscapedCodePoint()}},e.prototype.consumeStringSlice=function(e){for(var t="";e>0;){var i=Math.min(5e4,e);t+=Kp.apply(void 0,this._value.splice(0,i)),e-=i}return this._value.shift(),t},e.prototype.consumeStringToken=function(e){for(var t="",i=0;;){var r=this._value[i];if(-1===r||void 0===r||r===e)return{type:0,value:t+=this.consumeStringSlice(i)};if(10===r)return this._value.splice(0,i),hv;if(92===r){var s=this._value[i+1];-1!==s&&void 0!==s&&(10===s?(t+=this.consumeStringSlice(i),i=-1,this._value.shift()):Yf(r,s)&&(t+=this.consumeStringSlice(i),t+=Kp(this.consumeEscapedCodePoint()),i=-1))}i++}},e.prototype.consumeNumber=function(){var e=[],t=4,i=this.peekCodePoint(0);for(43!==i&&45!==i||e.push(this.consumeCodePoint());Gf(this.peekCodePoint(0));)e.push(this.consumeCodePoint());i=this.peekCodePoint(0);var r=this.peekCodePoint(1);if(46===i&&Gf(r))for(e.push(this.consumeCodePoint(),this.consumeCodePoint()),t=8;Gf(this.peekCodePoint(0));)e.push(this.consumeCodePoint());i=this.peekCodePoint(0),r=this.peekCodePoint(1);var s=this.peekCodePoint(2);if((69===i||101===i)&&((43===r||45===r)&&Gf(s)||Gf(r)))for(e.push(this.consumeCodePoint(),this.consumeCodePoint()),t=8;Gf(this.peekCodePoint(0));)e.push(this.consumeCodePoint());return[$f(e),t]},e.prototype.consumeNumericToken=function(){var e=this.consumeNumber(),t=e[0],i=e[1],r=this.peekCodePoint(0),s=this.peekCodePoint(1),n=this.peekCodePoint(2);return Zf(r,s,n)?{type:15,number:t,flags:i,unit:this.consumeName()}:37===r?(this.consumeCodePoint(),{type:16,number:t,flags:i}):{type:17,number:t,flags:i}},e.prototype.consumeEscapedCodePoint=function(){var e=this.consumeCodePoint();if(zf(e)){for(var t=Kp(e);zf(this.peekCodePoint(0))&&t.length<6;)t+=Kp(this.consumeCodePoint());Wf(this.peekCodePoint(0))&&this.consumeCodePoint();var i=parseInt(t,16);return 0===i||function(e){return e>=55296&&e<=57343}(i)||i>1114111?65533:i}return-1===e?65533:e},e.prototype.consumeName=function(){for(var e="";;){var t=this.consumeCodePoint();if(Xf(t))e+=Kp(t);else{if(!Yf(t,this.peekCodePoint(0)))return this.reconsumeCodePoint(t),e;e+=Kp(this.consumeEscapedCodePoint())}}},e}(),xv=function(){function e(e){this._tokens=e}return e.create=function(t){var i=new bv;return i.write(t),new e(i.read())},e.parseValue=function(t){return e.create(t).parseComponentValue()},e.parseValues=function(t){return e.create(t).parseComponentValues()},e.prototype.parseComponentValue=function(){for(var e=this.consumeToken();31===e.type;)e=this.consumeToken();if(32===e.type)throw new SyntaxError("Error parsing CSS component value, unexpected EOF");this.reconsumeToken(e);var t=this.consumeComponentValue();do{e=this.consumeToken()}while(31===e.type);if(32===e.type)return t;throw new SyntaxError("Error parsing CSS component value, multiple values found when expecting only one")},e.prototype.parseComponentValues=function(){for(var e=[];;){var t=this.consumeComponentValue();if(32===t.type)return e;e.push(t),e.push()}},e.prototype.consumeComponentValue=function(){var e=this.consumeToken();switch(e.type){case 11:case 28:case 2:return this.consumeSimpleBlock(e.type);case 19:return this.consumeFunction(e)}return e},e.prototype.consumeSimpleBlock=function(e){for(var t={type:e,values:[]},i=this.consumeToken();;){if(32===i.type||Iv(i,e))return t;this.reconsumeToken(i),t.values.push(this.consumeComponentValue()),i=this.consumeToken()}},e.prototype.consumeFunction=function(e){for(var t={name:e.value,values:[],type:18};;){var i=this.consumeToken();if(32===i.type||3===i.type)return t;this.reconsumeToken(i),t.values.push(this.consumeComponentValue())}},e.prototype.consumeToken=function(){var e=this._tokens.shift();return void 0===e?yv:e},e.prototype.reconsumeToken=function(e){this._tokens.unshift(e)},e}(),wv=function(e){return 15===e.type},Bv=function(e){return 17===e.type},Pv=function(e){return 20===e.type},Cv=function(e){return 0===e.type},Mv=function(e,t){return Pv(e)&&e.value===t},Ev=function(e){return 31!==e.type},Fv=function(e){return 31!==e.type&&4!==e.type},kv=function(e){var t=[],i=[];return e.forEach((function(e){if(4===e.type){if(0===i.length)throw new Error("Error parsing function args, zero tokens for arg");return t.push(i),void(i=[])}31!==e.type&&i.push(e)})),i.length&&t.push(i),t},Iv=function(e,t){return 11===t&&12===e.type||(28===t&&29===e.type||2===t&&3===e.type)},Dv=function(e){return 17===e.type||15===e.type},Sv=function(e){return 16===e.type||Dv(e)},Tv=function(e){return e.length>1?[e[0],e[1]]:[e[0]]},Lv={type:17,number:0,flags:4},Rv={type:16,number:50,flags:4},Uv={type:16,number:100,flags:4},Ov=function(e,t,i){var r=e[0],s=e[1];return[Nv(r,t),Nv(void 0!==s?s:r,i)]},Nv=function(e,t){if(16===e.type)return e.number/100*t;if(wv(e))switch(e.unit){case"rem":case"em":return 16*e.number;default:return e.number}return e.number},Qv=function(e,t){if(15===t.type)switch(t.unit){case"deg":return Math.PI*t.number/180;case"grad":return Math.PI/200*t.number;case"rad":return t.number;case"turn":return 2*Math.PI*t.number}throw new Error("Unsupported angle type")},Vv=function(e){return 15===e.type&&("deg"===e.unit||"grad"===e.unit||"rad"===e.unit||"turn"===e.unit)},Hv=function(e){switch(e.filter(Pv).map((function(e){return e.value})).join(" ")){case"to bottom right":case"to right bottom":case"left top":case"top left":return[Lv,Lv];case"to top":case"bottom":return jv(0);case"to bottom left":case"to left bottom":case"right top":case"top right":return[Lv,Uv];case"to right":case"left":return jv(90);case"to top left":case"to left top":case"right bottom":case"bottom right":return[Uv,Uv];case"to bottom":case"top":return jv(180);case"to top right":case"to right top":case"left bottom":case"bottom left":return[Uv,Lv];case"to left":case"right":return jv(270)}return 0},jv=function(e){return Math.PI*e/180},Gv=function(e,t){if(18===t.type){var i=qv[t.name];if(void 0===i)throw new Error('Attempting to parse an unsupported color function "'+t.name+'"');return i(e,t.values)}if(5===t.type){if(3===t.value.length){var r=t.value.substring(0,1),s=t.value.substring(1,2),n=t.value.substring(2,3);return Kv(parseInt(r+r,16),parseInt(s+s,16),parseInt(n+n,16),1)}if(4===t.value.length){r=t.value.substring(0,1),s=t.value.substring(1,2),n=t.value.substring(2,3);var o=t.value.substring(3,4);return Kv(parseInt(r+r,16),parseInt(s+s,16),parseInt(n+n,16),parseInt(o+o,16)/255)}if(6===t.value.length){r=t.value.substring(0,2),s=t.value.substring(2,4),n=t.value.substring(4,6);return Kv(parseInt(r,16),parseInt(s,16),parseInt(n,16),1)}if(8===t.value.length){r=t.value.substring(0,2),s=t.value.substring(2,4),n=t.value.substring(4,6),o=t.value.substring(6,8);return Kv(parseInt(r,16),parseInt(s,16),parseInt(n,16),parseInt(o,16)/255)}}if(20===t.type){var a=eg[t.value.toUpperCase()];if(void 0!==a)return a}return eg.TRANSPARENT},zv=function(e){return 0==(255&e)},Wv=function(e){var t=255&e,i=255&e>>8,r=255&e>>16,s=255&e>>24;return t<255?"rgba("+s+","+r+","+i+","+t/255+")":"rgb("+s+","+r+","+i+")"},Kv=function(e,t,i,r){return(e<<24|t<<16|i<<8|Math.round(255*r)<<0)>>>0},Xv=function(e,t){if(17===e.type)return e.number;if(16===e.type){var i=3===t?1:255;return 3===t?e.number/100*i:Math.round(e.number/100*i)}return 0},Jv=function(e,t){var i=t.filter(Fv);if(3===i.length){var r=i.map(Xv),s=r[0],n=r[1],o=r[2];return Kv(s,n,o,1)}if(4===i.length){var a=i.map(Xv),l=(s=a[0],n=a[1],o=a[2],a[3]);return Kv(s,n,o,l)}return 0};function Yv(e,t,i){return i<0&&(i+=1),i>=1&&(i-=1),i<1/6?(t-e)*i*6+e:i<.5?t:i<2/3?6*(t-e)*(2/3-i)+e:e}var Zv=function(e,t){var i=t.filter(Fv),r=i[0],s=i[1],n=i[2],o=i[3],a=(17===r.type?jv(r.number):Qv(e,r))/(2*Math.PI),l=Sv(s)?s.number/100:0,u=Sv(n)?n.number/100:0,c=void 0!==o&&Sv(o)?Nv(o,1):1;if(0===l)return Kv(255*u,255*u,255*u,1);var A=u<=.5?u*(l+1):u+l-u*l,h=2*u-A,d=Yv(h,A,a+1/3),p=Yv(h,A,a),f=Yv(h,A,a-1/3);return Kv(255*d,255*p,255*f,c)},qv={hsl:Zv,hsla:Zv,rgb:Jv,rgba:Jv},$v=function(e,t){return Gv(e,xv.create(t).parseComponentValue())},eg={ALICEBLUE:4042850303,ANTIQUEWHITE:4209760255,AQUA:16777215,AQUAMARINE:2147472639,AZURE:4043309055,BEIGE:4126530815,BISQUE:4293182719,BLACK:255,BLANCHEDALMOND:4293643775,BLUE:65535,BLUEVIOLET:2318131967,BROWN:2771004159,BURLYWOOD:3736635391,CADETBLUE:1604231423,CHARTREUSE:2147418367,CHOCOLATE:3530104575,CORAL:4286533887,CORNFLOWERBLUE:1687547391,CORNSILK:4294499583,CRIMSON:3692313855,CYAN:16777215,DARKBLUE:35839,DARKCYAN:9145343,DARKGOLDENROD:3095837695,DARKGRAY:2846468607,DARKGREEN:6553855,DARKGREY:2846468607,DARKKHAKI:3182914559,DARKMAGENTA:2332068863,DARKOLIVEGREEN:1433087999,DARKORANGE:4287365375,DARKORCHID:2570243327,DARKRED:2332033279,DARKSALMON:3918953215,DARKSEAGREEN:2411499519,DARKSLATEBLUE:1211993087,DARKSLATEGRAY:793726975,DARKSLATEGREY:793726975,DARKTURQUOISE:13554175,DARKVIOLET:2483082239,DEEPPINK:4279538687,DEEPSKYBLUE:12582911,DIMGRAY:1768516095,DIMGREY:1768516095,DODGERBLUE:512819199,FIREBRICK:2988581631,FLORALWHITE:4294635775,FORESTGREEN:579543807,FUCHSIA:4278255615,GAINSBORO:3705462015,GHOSTWHITE:4177068031,GOLD:4292280575,GOLDENROD:3668254975,GRAY:2155905279,GREEN:8388863,GREENYELLOW:2919182335,GREY:2155905279,HONEYDEW:4043305215,HOTPINK:4285117695,INDIANRED:3445382399,INDIGO:1258324735,IVORY:4294963455,KHAKI:4041641215,LAVENDER:3873897215,LAVENDERBLUSH:4293981695,LAWNGREEN:2096890111,LEMONCHIFFON:4294626815,LIGHTBLUE:2916673279,LIGHTCORAL:4034953471,LIGHTCYAN:3774873599,LIGHTGOLDENRODYELLOW:4210742015,LIGHTGRAY:3553874943,LIGHTGREEN:2431553791,LIGHTGREY:3553874943,LIGHTPINK:4290167295,LIGHTSALMON:4288707327,LIGHTSEAGREEN:548580095,LIGHTSKYBLUE:2278488831,LIGHTSLATEGRAY:2005441023,LIGHTSLATEGREY:2005441023,LIGHTSTEELBLUE:2965692159,LIGHTYELLOW:4294959359,LIME:16711935,LIMEGREEN:852308735,LINEN:4210091775,MAGENTA:4278255615,MAROON:2147483903,MEDIUMAQUAMARINE:1724754687,MEDIUMBLUE:52735,MEDIUMORCHID:3126187007,MEDIUMPURPLE:2473647103,MEDIUMSEAGREEN:1018393087,MEDIUMSLATEBLUE:2070474495,MEDIUMSPRINGGREEN:16423679,MEDIUMTURQUOISE:1221709055,MEDIUMVIOLETRED:3340076543,MIDNIGHTBLUE:421097727,MINTCREAM:4127193855,MISTYROSE:4293190143,MOCCASIN:4293178879,NAVAJOWHITE:4292783615,NAVY:33023,OLDLACE:4260751103,OLIVE:2155872511,OLIVEDRAB:1804477439,ORANGE:4289003775,ORANGERED:4282712319,ORCHID:3664828159,PALEGOLDENROD:4008225535,PALEGREEN:2566625535,PALETURQUOISE:2951671551,PALEVIOLETRED:3681588223,PAPAYAWHIP:4293907967,PEACHPUFF:4292524543,PERU:3448061951,PINK:4290825215,PLUM:3718307327,POWDERBLUE:2967529215,PURPLE:2147516671,REBECCAPURPLE:1714657791,RED:4278190335,ROSYBROWN:3163525119,ROYALBLUE:1097458175,SADDLEBROWN:2336560127,SALMON:4202722047,SANDYBROWN:4104413439,SEAGREEN:780883967,SEASHELL:4294307583,SIENNA:2689740287,SILVER:3233857791,SKYBLUE:2278484991,SLATEBLUE:1784335871,SLATEGRAY:1887473919,SLATEGREY:1887473919,SNOW:4294638335,SPRINGGREEN:16744447,STEELBLUE:1182971135,TAN:3535047935,TEAL:8421631,THISTLE:3636451583,TOMATO:4284696575,TRANSPARENT:0,TURQUOISE:1088475391,VIOLET:4001558271,WHEAT:4125012991,WHITE:4294967295,WHITESMOKE:4126537215,YELLOW:4294902015,YELLOWGREEN:2597139199},tg={name:"background-clip",initialValue:"border-box",prefix:!1,type:1,parse:function(e,t){return t.map((function(e){if(Pv(e))switch(e.value){case"padding-box":return 1;case"content-box":return 2}return 0}))}},ig={name:"background-color",initialValue:"transparent",prefix:!1,type:3,format:"color"},rg=function(e,t){var i=Gv(e,t[0]),r=t[1];return r&&Sv(r)?{color:i,stop:r}:{color:i,stop:null}},sg=function(e,t){var i=e[0],r=e[e.length-1];null===i.stop&&(i.stop=Lv),null===r.stop&&(r.stop=Uv);for(var s=[],n=0,o=0;on?s.push(l):s.push(n),n=l}else s.push(null)}var u=null;for(o=0;oe.optimumDistance)?{optimumCorner:t,optimumDistance:a}:e}),{optimumDistance:s?1/0:-1/0,optimumCorner:null}).optimumCorner},lg=function(e,t){var i=jv(180),r=[];return kv(t).forEach((function(t,s){if(0===s){var n=t[0];if(20===n.type&&-1!==["top","left","right","bottom"].indexOf(n.value))return void(i=Hv(t));if(Vv(n))return void(i=(Qv(e,n)+jv(270))%jv(360))}var o=rg(e,t);r.push(o)})),{angle:i,stops:r,type:1}},ug=function(e,t){var i=0,r=3,s=[],n=[];return kv(t).forEach((function(t,o){var a=!0;if(0===o?a=t.reduce((function(e,t){if(Pv(t))switch(t.value){case"center":return n.push(Rv),!1;case"top":case"left":return n.push(Lv),!1;case"right":case"bottom":return n.push(Uv),!1}else if(Sv(t)||Dv(t))return n.push(t),!1;return e}),a):1===o&&(a=t.reduce((function(e,t){if(Pv(t))switch(t.value){case"circle":return i=0,!1;case"ellipse":return i=1,!1;case"contain":case"closest-side":return r=0,!1;case"farthest-side":return r=1,!1;case"closest-corner":return r=2,!1;case"cover":case"farthest-corner":return r=3,!1}else if(Dv(t)||Sv(t))return Array.isArray(r)||(r=[]),r.push(t),!1;return e}),a)),a){var l=rg(e,t);s.push(l)}})),{size:r,shape:i,stops:s,position:n,type:2}},cg=function(e,t){if(22===t.type){var i={url:t.value,type:0};return e.cache.addImage(t.value),i}if(18===t.type){var r=hg[t.name];if(void 0===r)throw new Error('Attempting to parse an unsupported image function "'+t.name+'"');return r(e,t.values)}throw new Error("Unsupported image type "+t.type)};var Ag,hg={"linear-gradient":function(e,t){var i=jv(180),r=[];return kv(t).forEach((function(t,s){if(0===s){var n=t[0];if(20===n.type&&"to"===n.value)return void(i=Hv(t));if(Vv(n))return void(i=Qv(e,n))}var o=rg(e,t);r.push(o)})),{angle:i,stops:r,type:1}},"-moz-linear-gradient":lg,"-ms-linear-gradient":lg,"-o-linear-gradient":lg,"-webkit-linear-gradient":lg,"radial-gradient":function(e,t){var i=0,r=3,s=[],n=[];return kv(t).forEach((function(t,o){var a=!0;if(0===o){var l=!1;a=t.reduce((function(e,t){if(l)if(Pv(t))switch(t.value){case"center":return n.push(Rv),e;case"top":case"left":return n.push(Lv),e;case"right":case"bottom":return n.push(Uv),e}else(Sv(t)||Dv(t))&&n.push(t);else if(Pv(t))switch(t.value){case"circle":return i=0,!1;case"ellipse":return i=1,!1;case"at":return l=!0,!1;case"closest-side":return r=0,!1;case"cover":case"farthest-side":return r=1,!1;case"contain":case"closest-corner":return r=2,!1;case"farthest-corner":return r=3,!1}else if(Dv(t)||Sv(t))return Array.isArray(r)||(r=[]),r.push(t),!1;return e}),a)}if(a){var u=rg(e,t);s.push(u)}})),{size:r,shape:i,stops:s,position:n,type:2}},"-moz-radial-gradient":ug,"-ms-radial-gradient":ug,"-o-radial-gradient":ug,"-webkit-radial-gradient":ug,"-webkit-gradient":function(e,t){var i=jv(180),r=[],s=1;return kv(t).forEach((function(t,i){var n=t[0];if(0===i){if(Pv(n)&&"linear"===n.value)return void(s=1);if(Pv(n)&&"radial"===n.value)return void(s=2)}if(18===n.type)if("from"===n.name){var o=Gv(e,n.values[0]);r.push({stop:Lv,color:o})}else if("to"===n.name){o=Gv(e,n.values[0]);r.push({stop:Uv,color:o})}else if("color-stop"===n.name){var a=n.values.filter(Fv);if(2===a.length){o=Gv(e,a[1]);var l=a[0];Bv(l)&&r.push({stop:{type:16,number:100*l.number,flags:l.flags},color:o})}}})),1===s?{angle:(i+jv(180))%jv(360),stops:r,type:s}:{size:3,shape:0,stops:r,position:[],type:s}}},dg={name:"background-image",initialValue:"none",type:1,prefix:!1,parse:function(e,t){if(0===t.length)return[];var i=t[0];return 20===i.type&&"none"===i.value?[]:t.filter((function(e){return Fv(e)&&function(e){return!(20===e.type&&"none"===e.value||18===e.type&&!hg[e.name])}(e)})).map((function(t){return cg(e,t)}))}},pg={name:"background-origin",initialValue:"border-box",prefix:!1,type:1,parse:function(e,t){return t.map((function(e){if(Pv(e))switch(e.value){case"padding-box":return 1;case"content-box":return 2}return 0}))}},fg={name:"background-position",initialValue:"0% 0%",type:1,prefix:!1,parse:function(e,t){return kv(t).map((function(e){return e.filter(Sv)})).map(Tv)}},vg={name:"background-repeat",initialValue:"repeat",prefix:!1,type:1,parse:function(e,t){return kv(t).map((function(e){return e.filter(Pv).map((function(e){return e.value})).join(" ")})).map(gg)}},gg=function(e){switch(e){case"no-repeat":return 1;case"repeat-x":case"repeat no-repeat":return 2;case"repeat-y":case"no-repeat repeat":return 3;default:return 0}};!function(e){e.AUTO="auto",e.CONTAIN="contain",e.COVER="cover"}(Ag||(Ag={}));var mg,_g={name:"background-size",initialValue:"0",prefix:!1,type:1,parse:function(e,t){return kv(t).map((function(e){return e.filter(yg)}))}},yg=function(e){return Pv(e)||Sv(e)},bg=function(e){return{name:"border-"+e+"-color",initialValue:"transparent",prefix:!1,type:3,format:"color"}},xg=bg("top"),wg=bg("right"),Bg=bg("bottom"),Pg=bg("left"),Cg=function(e){return{name:"border-radius-"+e,initialValue:"0 0",prefix:!1,type:1,parse:function(e,t){return Tv(t.filter(Sv))}}},Mg=Cg("top-left"),Eg=Cg("top-right"),Fg=Cg("bottom-right"),kg=Cg("bottom-left"),Ig=function(e){return{name:"border-"+e+"-style",initialValue:"solid",prefix:!1,type:2,parse:function(e,t){switch(t){case"none":return 0;case"dashed":return 2;case"dotted":return 3;case"double":return 4}return 1}}},Dg=Ig("top"),Sg=Ig("right"),Tg=Ig("bottom"),Lg=Ig("left"),Rg=function(e){return{name:"border-"+e+"-width",initialValue:"0",type:0,prefix:!1,parse:function(e,t){return wv(t)?t.number:0}}},Ug=Rg("top"),Og=Rg("right"),Ng=Rg("bottom"),Qg=Rg("left"),Vg={name:"color",initialValue:"transparent",prefix:!1,type:3,format:"color"},Hg={name:"direction",initialValue:"ltr",prefix:!1,type:2,parse:function(e,t){return"rtl"===t?1:0}},jg={name:"display",initialValue:"inline-block",prefix:!1,type:1,parse:function(e,t){return t.filter(Pv).reduce((function(e,t){return e|Gg(t.value)}),0)}},Gg=function(e){switch(e){case"block":case"-webkit-box":return 2;case"inline":return 4;case"run-in":return 8;case"flow":return 16;case"flow-root":return 32;case"table":return 64;case"flex":case"-webkit-flex":return 128;case"grid":case"-ms-grid":return 256;case"ruby":return 512;case"subgrid":return 1024;case"list-item":return 2048;case"table-row-group":return 4096;case"table-header-group":return 8192;case"table-footer-group":return 16384;case"table-row":return 32768;case"table-cell":return 65536;case"table-column-group":return 131072;case"table-column":return 262144;case"table-caption":return 524288;case"ruby-base":return 1048576;case"ruby-text":return 2097152;case"ruby-base-container":return 4194304;case"ruby-text-container":return 8388608;case"contents":return 16777216;case"inline-block":return 33554432;case"inline-list-item":return 67108864;case"inline-table":return 134217728;case"inline-flex":return 268435456;case"inline-grid":return 536870912}return 0},zg={name:"float",initialValue:"none",prefix:!1,type:2,parse:function(e,t){switch(t){case"left":return 1;case"right":return 2;case"inline-start":return 3;case"inline-end":return 4}return 0}},Wg={name:"letter-spacing",initialValue:"0",prefix:!1,type:0,parse:function(e,t){return 20===t.type&&"normal"===t.value?0:17===t.type||15===t.type?t.number:0}};!function(e){e.NORMAL="normal",e.STRICT="strict"}(mg||(mg={}));var Kg,Xg={name:"line-break",initialValue:"normal",prefix:!1,type:2,parse:function(e,t){return"strict"===t?mg.STRICT:mg.NORMAL}},Jg={name:"line-height",initialValue:"normal",prefix:!1,type:4},Yg=function(e,t){return Pv(e)&&"normal"===e.value?1.2*t:17===e.type?t*e.number:Sv(e)?Nv(e,t):t},Zg={name:"list-style-image",initialValue:"none",type:0,prefix:!1,parse:function(e,t){return 20===t.type&&"none"===t.value?null:cg(e,t)}},qg={name:"list-style-position",initialValue:"outside",prefix:!1,type:2,parse:function(e,t){return"inside"===t?0:1}},$g={name:"list-style-type",initialValue:"none",prefix:!1,type:2,parse:function(e,t){switch(t){case"disc":return 0;case"circle":return 1;case"square":return 2;case"decimal":return 3;case"cjk-decimal":return 4;case"decimal-leading-zero":return 5;case"lower-roman":return 6;case"upper-roman":return 7;case"lower-greek":return 8;case"lower-alpha":return 9;case"upper-alpha":return 10;case"arabic-indic":return 11;case"armenian":return 12;case"bengali":return 13;case"cambodian":return 14;case"cjk-earthly-branch":return 15;case"cjk-heavenly-stem":return 16;case"cjk-ideographic":return 17;case"devanagari":return 18;case"ethiopic-numeric":return 19;case"georgian":return 20;case"gujarati":return 21;case"gurmukhi":case"hebrew":return 22;case"hiragana":return 23;case"hiragana-iroha":return 24;case"japanese-formal":return 25;case"japanese-informal":return 26;case"kannada":return 27;case"katakana":return 28;case"katakana-iroha":return 29;case"khmer":return 30;case"korean-hangul-formal":return 31;case"korean-hanja-formal":return 32;case"korean-hanja-informal":return 33;case"lao":return 34;case"lower-armenian":return 35;case"malayalam":return 36;case"mongolian":return 37;case"myanmar":return 38;case"oriya":return 39;case"persian":return 40;case"simp-chinese-formal":return 41;case"simp-chinese-informal":return 42;case"tamil":return 43;case"telugu":return 44;case"thai":return 45;case"tibetan":return 46;case"trad-chinese-formal":return 47;case"trad-chinese-informal":return 48;case"upper-armenian":return 49;case"disclosure-open":return 50;case"disclosure-closed":return 51;default:return-1}}},em=function(e){return{name:"margin-"+e,initialValue:"0",prefix:!1,type:4}},tm=em("top"),im=em("right"),rm=em("bottom"),sm=em("left"),nm={name:"overflow",initialValue:"visible",prefix:!1,type:1,parse:function(e,t){return t.filter(Pv).map((function(e){switch(e.value){case"hidden":return 1;case"scroll":return 2;case"clip":return 3;case"auto":return 4;default:return 0}}))}},om={name:"overflow-wrap",initialValue:"normal",prefix:!1,type:2,parse:function(e,t){return"break-word"===t?"break-word":"normal"}},am=function(e){return{name:"padding-"+e,initialValue:"0",prefix:!1,type:3,format:"length-percentage"}},lm=am("top"),um=am("right"),cm=am("bottom"),Am=am("left"),hm={name:"text-align",initialValue:"left",prefix:!1,type:2,parse:function(e,t){switch(t){case"right":return 2;case"center":case"justify":return 1;default:return 0}}},dm={name:"position",initialValue:"static",prefix:!1,type:2,parse:function(e,t){switch(t){case"relative":return 1;case"absolute":return 2;case"fixed":return 3;case"sticky":return 4}return 0}},pm={name:"text-shadow",initialValue:"none",type:1,prefix:!1,parse:function(e,t){return 1===t.length&&Mv(t[0],"none")?[]:kv(t).map((function(t){for(var i={color:eg.TRANSPARENT,offsetX:Lv,offsetY:Lv,blur:Lv},r=0,s=0;s1?1:0],this.overflowWrap=Km(e,om,t.overflowWrap),this.paddingTop=Km(e,lm,t.paddingTop),this.paddingRight=Km(e,um,t.paddingRight),this.paddingBottom=Km(e,cm,t.paddingBottom),this.paddingLeft=Km(e,Am,t.paddingLeft),this.paintOrder=Km(e,Vm,t.paintOrder),this.position=Km(e,dm,t.position),this.textAlign=Km(e,hm,t.textAlign),this.textDecorationColor=Km(e,Cm,null!==(i=t.textDecorationColor)&&void 0!==i?i:t.color),this.textDecorationLine=Km(e,Mm,null!==(r=t.textDecorationLine)&&void 0!==r?r:t.textDecoration),this.textShadow=Km(e,pm,t.textShadow),this.textTransform=Km(e,fm,t.textTransform),this.transform=Km(e,vm,t.transform),this.transformOrigin=Km(e,ym,t.transformOrigin),this.visibility=Km(e,bm,t.visibility),this.webkitTextStrokeColor=Km(e,Hm,t.webkitTextStrokeColor),this.webkitTextStrokeWidth=Km(e,jm,t.webkitTextStrokeWidth),this.wordBreak=Km(e,xm,t.wordBreak),this.zIndex=Km(e,wm,t.zIndex)}return e.prototype.isVisible=function(){return this.display>0&&this.opacity>0&&0===this.visibility},e.prototype.isTransparent=function(){return zv(this.backgroundColor)},e.prototype.isTransformed=function(){return null!==this.transform},e.prototype.isPositioned=function(){return 0!==this.position},e.prototype.isPositionedWithZIndex=function(){return this.isPositioned()&&!this.zIndex.auto},e.prototype.isFloating=function(){return 0!==this.float},e.prototype.isInlineLevel=function(){return Sm(this.display,4)||Sm(this.display,33554432)||Sm(this.display,268435456)||Sm(this.display,536870912)||Sm(this.display,67108864)||Sm(this.display,134217728)},e}(),zm=function(e,t){this.content=Km(e,Tm,t.content),this.quotes=Km(e,Om,t.quotes)},Wm=function(e,t){this.counterIncrement=Km(e,Lm,t.counterIncrement),this.counterReset=Km(e,Rm,t.counterReset)},Km=function(e,t,i){var r=new bv,s=null!=i?i.toString():t.initialValue;r.write(s);var n=new xv(r.read());switch(t.type){case 2:var o=n.parseComponentValue();return t.parse(e,Pv(o)?o.value:t.initialValue);case 0:return t.parse(e,n.parseComponentValue());case 1:return t.parse(e,n.parseComponentValues());case 4:return n.parseComponentValue();case 3:switch(t.format){case"angle":return Qv(e,n.parseComponentValue());case"color":return Gv(e,n.parseComponentValue());case"image":return cg(e,n.parseComponentValue());case"length":var a=n.parseComponentValue();return Dv(a)?a:Lv;case"length-percentage":var l=n.parseComponentValue();return Sv(l)?l:Lv;case"time":return Bm(e,n.parseComponentValue())}}},Xm=function(e,t){var i=function(e){switch(e.getAttribute("data-html2canvas-debug")){case"all":return 1;case"clone":return 2;case"parse":return 3;case"render":return 4;default:return 0}}(e);return 1===i||t===i},Jm=function(e,t){this.context=e,this.textNodes=[],this.elements=[],this.flags=0,Xm(t,3),this.styles=new Gm(e,window.getComputedStyle(t,null)),J_(t)&&(this.styles.animationDuration.some((function(e){return e>0}))&&(t.style.animationDuration="0s"),null!==this.styles.transform&&(t.style.transform="none")),this.bounds=zp(this.context,t),Xm(t,4)&&(this.flags|=16)},Ym="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Zm="undefined"==typeof Uint8Array?[]:new Uint8Array(256),qm=0;qm=0){if(e<55296||e>56319&&e<=65535)return t=((t=this.index[e>>5])<<2)+(31&e),this.data[t];if(e<=65535)return t=((t=this.index[2048+(e-55296>>5)])<<2)+(31&e),this.data[t];if(e>11),t=this.index[t],t+=e>>5&63,t=((t=this.index[t])<<2)+(31&e),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},e}(),t_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i_="undefined"==typeof Uint8Array?[]:new Uint8Array(256),r_=0;r_>10),o%1024+56320)),(s+1===i||r.length>16384)&&(n+=String.fromCharCode.apply(String,r),r.length=0)}return n},c_=function(e,t){var i,r,s,n=function(e){var t,i,r,s,n,o=.75*e.length,a=e.length,l=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);var u="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&void 0!==Uint8Array.prototype.slice?new ArrayBuffer(o):new Array(o),c=Array.isArray(u)?u:new Uint8Array(u);for(t=0;t>4,c[l++]=(15&r)<<4|s>>2,c[l++]=(3&s)<<6|63&n;return u}(e),o=Array.isArray(n)?function(e){for(var t=e.length,i=[],r=0;r=55296&&s<=56319&&i=i)return{done:!0,value:null};for(var e="×";ro.x||s.y>o.y;return o=s,0===t||a}));return e.body.removeChild(t),a}(document);return Object.defineProperty(g_,"SUPPORT_WORD_BREAKING",{value:e}),e},get SUPPORT_SVG_DRAWING(){var e=function(e){var t=new Image,i=e.createElement("canvas"),r=i.getContext("2d");if(!r)return!1;t.src="data:image/svg+xml,";try{r.drawImage(t,0,0),i.toDataURL()}catch(e){return!1}return!0}(document);return Object.defineProperty(g_,"SUPPORT_SVG_DRAWING",{value:e}),e},get SUPPORT_FOREIGNOBJECT_DRAWING(){var e="function"==typeof Array.from&&"function"==typeof window.fetch?function(e){var t=e.createElement("canvas"),i=100;t.width=i,t.height=i;var r=t.getContext("2d");if(!r)return Promise.reject(!1);r.fillStyle="rgb(0, 255, 0)",r.fillRect(0,0,i,i);var s=new Image,n=t.toDataURL();s.src=n;var o=f_(i,i,0,0,s);return r.fillStyle="red",r.fillRect(0,0,i,i),v_(o).then((function(t){r.drawImage(t,0,0);var s=r.getImageData(0,0,i,i).data;r.fillStyle="red",r.fillRect(0,0,i,i);var o=e.createElement("div");return o.style.backgroundImage="url("+n+")",o.style.height="100px",p_(s)?v_(f_(i,i,0,0,o)):Promise.reject(!1)})).then((function(e){return r.drawImage(e,0,0),p_(r.getImageData(0,0,i,i).data)})).catch((function(){return!1}))}(document):Promise.resolve(!1);return Object.defineProperty(g_,"SUPPORT_FOREIGNOBJECT_DRAWING",{value:e}),e},get SUPPORT_CORS_IMAGES(){var e=void 0!==(new Image).crossOrigin;return Object.defineProperty(g_,"SUPPORT_CORS_IMAGES",{value:e}),e},get SUPPORT_RESPONSE_TYPE(){var e="string"==typeof(new XMLHttpRequest).responseType;return Object.defineProperty(g_,"SUPPORT_RESPONSE_TYPE",{value:e}),e},get SUPPORT_CORS_XHR(){var e="withCredentials"in new XMLHttpRequest;return Object.defineProperty(g_,"SUPPORT_CORS_XHR",{value:e}),e},get SUPPORT_NATIVE_TEXT_SEGMENTATION(){var e=!("undefined"==typeof Intl||!Intl.Segmenter);return Object.defineProperty(g_,"SUPPORT_NATIVE_TEXT_SEGMENTATION",{value:e}),e}},m_=function(e,t){this.text=e,this.bounds=t},__=function(e,t){var i=t.ownerDocument;if(i){var r=i.createElement("html2canvaswrapper");r.appendChild(t.cloneNode(!0));var s=t.parentNode;if(s){s.replaceChild(r,t);var n=zp(e,r);return r.firstChild&&s.replaceChild(r.firstChild,r),n}}return Gp.EMPTY},y_=function(e,t,i){var r=e.ownerDocument;if(!r)throw new Error("Node has no owner document");var s=r.createRange();return s.setStart(e,t),s.setEnd(e,t+i),s},b_=function(e){if(g_.SUPPORT_NATIVE_TEXT_SEGMENTATION){var t=new Intl.Segmenter(void 0,{granularity:"grapheme"});return Array.from(t.segment(e)).map((function(e){return e.segment}))}return function(e){for(var t,i=d_(e),r=[];!(t=i.next()).done;)t.value&&r.push(t.value.slice());return r}(e)},x_=function(e,t){return 0!==t.letterSpacing?b_(e):function(e,t){if(g_.SUPPORT_NATIVE_TEXT_SEGMENTATION){var i=new Intl.Segmenter(void 0,{granularity:"word"});return Array.from(i.segment(e)).map((function(e){return e.segment}))}return B_(e,t)}(e,t)},w_=[32,160,4961,65792,65793,4153,4241],B_=function(e,t){for(var i,r=function(e,t){var i=Wp(e),r=Hf(i,t),s=r[0],n=r[1],o=r[2],a=i.length,l=0,u=0;return{next:function(){if(u>=a)return{done:!0,value:null};for(var e="×";u0)if(g_.SUPPORT_RANGE_BOUNDS){var s=y_(r,o,t.length).getClientRects();if(s.length>1){var a=b_(t),l=0;a.forEach((function(t){n.push(new m_(t,Gp.fromDOMRectList(e,y_(r,l+o,t.length).getClientRects()))),l+=t.length}))}else n.push(new m_(t,Gp.fromDOMRectList(e,s)))}else{var u=r.splitText(t.length);n.push(new m_(t,__(e,r))),r=u}else g_.SUPPORT_RANGE_BOUNDS||(r=r.splitText(t.length));o+=t.length})),n}(e,this.text,i,t)},C_=function(e,t){switch(t){case 1:return e.toLowerCase();case 3:return e.replace(M_,E_);case 2:return e.toUpperCase();default:return e}},M_=/(^|\s|:|-|\(|\))([a-z])/g,E_=function(e,t,i){return e.length>0?t+i.toUpperCase():e},F_=function(e){function t(t,i){var r=e.call(this,t,i)||this;return r.src=i.currentSrc||i.src,r.intrinsicWidth=i.naturalWidth,r.intrinsicHeight=i.naturalHeight,r.context.cache.addImage(r.src),r}return Np(t,e),t}(Jm),k_=function(e){function t(t,i){var r=e.call(this,t,i)||this;return r.canvas=i,r.intrinsicWidth=i.width,r.intrinsicHeight=i.height,r}return Np(t,e),t}(Jm),I_=function(e){function t(t,i){var r=e.call(this,t,i)||this,s=new XMLSerializer,n=zp(t,i);return i.setAttribute("width",n.width+"px"),i.setAttribute("height",n.height+"px"),r.svg="data:image/svg+xml,"+encodeURIComponent(s.serializeToString(i)),r.intrinsicWidth=i.width.baseVal.value,r.intrinsicHeight=i.height.baseVal.value,r.context.cache.addImage(r.svg),r}return Np(t,e),t}(Jm),D_=function(e){function t(t,i){var r=e.call(this,t,i)||this;return r.value=i.value,r}return Np(t,e),t}(Jm),S_=function(e){function t(t,i){var r=e.call(this,t,i)||this;return r.start=i.start,r.reversed="boolean"==typeof i.reversed&&!0===i.reversed,r}return Np(t,e),t}(Jm),T_=[{type:15,flags:0,unit:"px",number:3}],L_=[{type:16,flags:0,number:50}],R_="password",U_=function(e){function t(t,i){var r,s=e.call(this,t,i)||this;switch(s.type=i.type.toLowerCase(),s.checked=i.checked,s.value=function(e){var t=e.type===R_?new Array(e.value.length+1).join("•"):e.value;return 0===t.length?e.placeholder||"":t}(i),"checkbox"!==s.type&&"radio"!==s.type||(s.styles.backgroundColor=3739148031,s.styles.borderTopColor=s.styles.borderRightColor=s.styles.borderBottomColor=s.styles.borderLeftColor=2779096575,s.styles.borderTopWidth=s.styles.borderRightWidth=s.styles.borderBottomWidth=s.styles.borderLeftWidth=1,s.styles.borderTopStyle=s.styles.borderRightStyle=s.styles.borderBottomStyle=s.styles.borderLeftStyle=1,s.styles.backgroundClip=[0],s.styles.backgroundOrigin=[0],s.bounds=(r=s.bounds).width>r.height?new Gp(r.left+(r.width-r.height)/2,r.top,r.height,r.height):r.width0)r.textNodes.push(new P_(t,n,r.styles));else if(X_(n))if(uy(n)&&n.assignedNodes)n.assignedNodes().forEach((function(i){return e(t,i,r,s)}));else{var a=j_(t,n);a.styles.isVisible()&&(z_(n,a,s)?a.flags|=4:W_(a.styles)&&(a.flags|=2),-1!==V_.indexOf(n.tagName)&&(a.flags|=8),r.elements.push(a),n.slot,n.shadowRoot?e(t,n.shadowRoot,a,s):ay(n)||ey(n)||ly(n)||e(t,n,a,s))}},j_=function(e,t){return sy(t)?new F_(e,t):iy(t)?new k_(e,t):ey(t)?new I_(e,t):Z_(t)?new D_(e,t):q_(t)?new S_(e,t):$_(t)?new U_(e,t):ly(t)?new O_(e,t):ay(t)?new N_(e,t):ny(t)?new Q_(e,t):new Jm(e,t)},G_=function(e,t){var i=j_(e,t);return i.flags|=4,H_(e,t,i,i),i},z_=function(e,t,i){return t.styles.isPositionedWithZIndex()||t.styles.opacity<1||t.styles.isTransformed()||ty(e)&&i.styles.isTransparent()},W_=function(e){return e.isPositioned()||e.isFloating()},K_=function(e){return e.nodeType===Node.TEXT_NODE},X_=function(e){return e.nodeType===Node.ELEMENT_NODE},J_=function(e){return X_(e)&&void 0!==e.style&&!Y_(e)},Y_=function(e){return"object"===w(e.className)},Z_=function(e){return"LI"===e.tagName},q_=function(e){return"OL"===e.tagName},$_=function(e){return"INPUT"===e.tagName},ey=function(e){return"svg"===e.tagName},ty=function(e){return"BODY"===e.tagName},iy=function(e){return"CANVAS"===e.tagName},ry=function(e){return"VIDEO"===e.tagName},sy=function(e){return"IMG"===e.tagName},ny=function(e){return"IFRAME"===e.tagName},oy=function(e){return"STYLE"===e.tagName},ay=function(e){return"TEXTAREA"===e.tagName},ly=function(e){return"SELECT"===e.tagName},uy=function(e){return"SLOT"===e.tagName},cy=function(e){return e.tagName.indexOf("-")>0},Ay=function(){function e(){this.counters={}}return e.prototype.getCounterValue=function(e){var t=this.counters[e];return t&&t.length?t[t.length-1]:1},e.prototype.getCounterValues=function(e){var t=this.counters[e];return t||[]},e.prototype.pop=function(e){var t=this;e.forEach((function(e){return t.counters[e].pop()}))},e.prototype.parse=function(e){var t=this,i=e.counterIncrement,r=e.counterReset,s=!0;null!==i&&i.forEach((function(e){var i=t.counters[e.counter];i&&0!==e.increment&&(s=!1,i.length||i.push(1),i[Math.max(0,i.length-1)]+=e.increment)}));var n=[];return s&&r.forEach((function(e){var i=t.counters[e.counter];n.push(e.counter),i||(i=t.counters[e.counter]=[]),i.push(e.reset)})),n},e}(),hy={integers:[1e3,900,500,400,100,90,50,40,10,9,5,4,1],values:["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]},dy={integers:[9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],values:["Ք","Փ","Ւ","Ց","Ր","Տ","Վ","Ս","Ռ","Ջ","Պ","Չ","Ո","Շ","Ն","Յ","Մ","Ճ","Ղ","Ձ","Հ","Կ","Ծ","Խ","Լ","Ի","Ժ","Թ","Ը","Է","Զ","Ե","Դ","Գ","Բ","Ա"]},py={integers:[1e4,9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,400,300,200,100,90,80,70,60,50,40,30,20,19,18,17,16,15,10,9,8,7,6,5,4,3,2,1],values:["י׳","ט׳","ח׳","ז׳","ו׳","ה׳","ד׳","ג׳","ב׳","א׳","ת","ש","ר","ק","צ","פ","ע","ס","נ","מ","ל","כ","יט","יח","יז","טז","טו","י","ט","ח","ז","ו","ה","ד","ג","ב","א"]},fy={integers:[1e4,9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],values:["ჵ","ჰ","ჯ","ჴ","ხ","ჭ","წ","ძ","ც","ჩ","შ","ყ","ღ","ქ","ფ","ჳ","ტ","ს","რ","ჟ","პ","ო","ჲ","ნ","მ","ლ","კ","ი","თ","ჱ","ზ","ვ","ე","დ","გ","ბ","ა"]},vy=function(e,t,i,r,s,n){return ei?by(e,s,n.length>0):r.integers.reduce((function(t,i,s){for(;e>=i;)e-=i,t+=r.values[s];return t}),"")+n},gy=function(e,t,i,r){var s="";do{i||e--,s=r(e)+s,e/=t}while(e*t>=t);return s},my=function(e,t,i,r,s){var n=i-t+1;return(e<0?"-":"")+(gy(Math.abs(e),n,r,(function(e){return Kp(Math.floor(e%n)+t)}))+s)},_y=function(e,t,i){void 0===i&&(i=". ");var r=t.length;return gy(Math.abs(e),r,!1,(function(e){return t[Math.floor(e%r)]}))+i},yy=function(e,t,i,r,s,n){if(e<-9999||e>9999)return by(e,4,s.length>0);var o=Math.abs(e),a=s;if(0===o)return t[0]+a;for(var l=0;o>0&&l<=4;l++){var u=o%10;0===u&&Sm(n,1)&&""!==a?a=t[u]+a:u>1||1===u&&0===l||1===u&&1===l&&Sm(n,2)||1===u&&1===l&&Sm(n,4)&&e>100||1===u&&l>1&&Sm(n,8)?a=t[u]+(l>0?i[l-1]:"")+a:1===u&&l>0&&(a=i[l-1]+a),o=Math.floor(o/10)}return(e<0?r:"")+a},by=function(e,t,i){var r=i?". ":"",s=i?"、":"",n=i?", ":"",o=i?" ":"";switch(t){case 0:return"•"+o;case 1:return"◦"+o;case 2:return"◾"+o;case 5:var a=my(e,48,57,!0,r);return a.length<4?"0"+a:a;case 4:return _y(e,"〇一二三四五六七八九",s);case 6:return vy(e,1,3999,hy,3,r).toLowerCase();case 7:return vy(e,1,3999,hy,3,r);case 8:return my(e,945,969,!1,r);case 9:return my(e,97,122,!1,r);case 10:return my(e,65,90,!1,r);case 11:return my(e,1632,1641,!0,r);case 12:case 49:return vy(e,1,9999,dy,3,r);case 35:return vy(e,1,9999,dy,3,r).toLowerCase();case 13:return my(e,2534,2543,!0,r);case 14:case 30:return my(e,6112,6121,!0,r);case 15:return _y(e,"子丑寅卯辰巳午未申酉戌亥",s);case 16:return _y(e,"甲乙丙丁戊己庚辛壬癸",s);case 17:case 48:return yy(e,"零一二三四五六七八九","十百千萬","負",s,14);case 47:return yy(e,"零壹貳參肆伍陸柒捌玖","拾佰仟萬","負",s,15);case 42:return yy(e,"零一二三四五六七八九","十百千萬","负",s,14);case 41:return yy(e,"零壹贰叁肆伍陆柒捌玖","拾佰仟萬","负",s,15);case 26:return yy(e,"〇一二三四五六七八九","十百千万","マイナス",s,0);case 25:return yy(e,"零壱弐参四伍六七八九","拾百千万","マイナス",s,7);case 31:return yy(e,"영일이삼사오육칠팔구","십백천만","마이너스",n,7);case 33:return yy(e,"零一二三四五六七八九","十百千萬","마이너스",n,0);case 32:return yy(e,"零壹貳參四五六七八九","拾百千","마이너스",n,7);case 18:return my(e,2406,2415,!0,r);case 20:return vy(e,1,19999,fy,3,r);case 21:return my(e,2790,2799,!0,r);case 22:return my(e,2662,2671,!0,r);case 22:return vy(e,1,10999,py,3,r);case 23:return _y(e,"あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわゐゑをん");case 24:return _y(e,"いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす");case 27:return my(e,3302,3311,!0,r);case 28:return _y(e,"アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヰヱヲン",s);case 29:return _y(e,"イロハニホヘトチリヌルヲワカヨタレソツネナラムウヰノオクヤマケフコエテアサキユメミシヱヒモセス",s);case 34:return my(e,3792,3801,!0,r);case 37:return my(e,6160,6169,!0,r);case 38:return my(e,4160,4169,!0,r);case 39:return my(e,2918,2927,!0,r);case 40:return my(e,1776,1785,!0,r);case 43:return my(e,3046,3055,!0,r);case 44:return my(e,3174,3183,!0,r);case 45:return my(e,3664,3673,!0,r);case 46:return my(e,3872,3881,!0,r);default:return my(e,48,57,!0,r)}},xy=function(){function e(e,t,i){if(this.context=e,this.options=i,this.scrolledElements=[],this.referenceElement=t,this.counters=new Ay,this.quoteDepth=0,!t.ownerDocument)throw new Error("Cloned element does not have an owner document");this.documentElement=this.cloneNode(t.ownerDocument.documentElement,!1)}return e.prototype.toIFrame=function(e,t){var i=this,r=By(e,t);if(!r.contentWindow)return Promise.reject("Unable to find iframe window");var s=e.defaultView.pageXOffset,n=e.defaultView.pageYOffset,o=r.contentWindow,a=o.document,l=My(r).then((function(){return Vp(i,void 0,void 0,(function(){var e,i;return Hp(this,(function(s){switch(s.label){case 0:return this.scrolledElements.forEach(Dy),o&&(o.scrollTo(t.left,t.top),!/(iPad|iPhone|iPod)/g.test(navigator.userAgent)||o.scrollY===t.top&&o.scrollX===t.left||(this.context.logger.warn("Unable to restore scroll position for cloned document"),this.context.windowBounds=this.context.windowBounds.add(o.scrollX-t.left,o.scrollY-t.top,0,0))),e=this.options.onclone,void 0===(i=this.clonedReferenceElement)?[2,Promise.reject("Error finding the "+this.referenceElement.nodeName+" in the cloned document")]:a.fonts&&a.fonts.ready?[4,a.fonts.ready]:[3,2];case 1:s.sent(),s.label=2;case 2:return/(AppleWebKit)/g.test(navigator.userAgent)?[4,Cy(a)]:[3,4];case 3:s.sent(),s.label=4;case 4:return"function"==typeof e?[2,Promise.resolve().then((function(){return e(a,i)})).then((function(){return r}))]:[2,r]}}))}))}));return a.open(),a.write(ky(document.doctype)+""),Iy(this.referenceElement.ownerDocument,s,n),a.replaceChild(a.adoptNode(this.documentElement),a.documentElement),a.close(),l},e.prototype.createElementClone=function(e){if(Xm(e,2),iy(e))return this.createCanvasClone(e);if(ry(e))return this.createVideoClone(e);if(oy(e))return this.createStyleClone(e);var t=e.cloneNode(!1);return sy(t)&&(sy(e)&&e.currentSrc&&e.currentSrc!==e.src&&(t.src=e.currentSrc,t.srcset=""),"lazy"===t.loading&&(t.loading="eager")),cy(t)?this.createCustomElementClone(t):t},e.prototype.createCustomElementClone=function(e){var t=document.createElement("html2canvascustomelement");return Fy(e.style,t),t},e.prototype.createStyleClone=function(e){try{var t=e.sheet;if(t&&t.cssRules){var i=[].slice.call(t.cssRules,0).reduce((function(e,t){return t&&"string"==typeof t.cssText?e+t.cssText:e}),""),r=e.cloneNode(!1);return r.textContent=i,r}}catch(e){if(this.context.logger.error("Unable to access cssRules property",e),"SecurityError"!==e.name)throw e}return e.cloneNode(!1)},e.prototype.createCanvasClone=function(e){var t;if(this.options.inlineImages&&e.ownerDocument){var i=e.ownerDocument.createElement("img");try{return i.src=e.toDataURL(),i}catch(t){this.context.logger.info("Unable to inline canvas contents, canvas is tainted",e)}}var r=e.cloneNode(!1);try{r.width=e.width,r.height=e.height;var s=e.getContext("2d"),n=r.getContext("2d");if(n)if(!this.options.allowTaint&&s)n.putImageData(s.getImageData(0,0,e.width,e.height),0,0);else{var o=null!==(t=e.getContext("webgl2"))&&void 0!==t?t:e.getContext("webgl");if(o){var a=o.getContextAttributes();!1===(null==a?void 0:a.preserveDrawingBuffer)&&this.context.logger.warn("Unable to clone WebGL context as it has preserveDrawingBuffer=false",e)}n.drawImage(e,0,0)}return r}catch(t){this.context.logger.info("Unable to clone canvas as it is tainted",e)}return r},e.prototype.createVideoClone=function(e){var t=e.ownerDocument.createElement("canvas");t.width=e.offsetWidth,t.height=e.offsetHeight;var i=t.getContext("2d");try{return i&&(i.drawImage(e,0,0,t.width,t.height),this.options.allowTaint||i.getImageData(0,0,t.width,t.height)),t}catch(t){this.context.logger.info("Unable to clone video as it is tainted",e)}var r=e.ownerDocument.createElement("canvas");return r.width=e.offsetWidth,r.height=e.offsetHeight,r},e.prototype.appendChildNode=function(e,t,i){X_(t)&&(function(e){return"SCRIPT"===e.tagName}(t)||t.hasAttribute("data-html2canvas-ignore")||"function"==typeof this.options.ignoreElements&&this.options.ignoreElements(t))||this.options.copyStyles&&X_(t)&&oy(t)||e.appendChild(this.cloneNode(t,i))},e.prototype.cloneChildNodes=function(e,t,i){for(var r=this,s=e.shadowRoot?e.shadowRoot.firstChild:e.firstChild;s;s=s.nextSibling)if(X_(s)&&uy(s)&&"function"==typeof s.assignedNodes){var n=s.assignedNodes();n.length&&n.forEach((function(e){return r.appendChildNode(t,e,i)}))}else this.appendChildNode(t,s,i)},e.prototype.cloneNode=function(e,t){if(K_(e))return document.createTextNode(e.data);if(!e.ownerDocument)return e.cloneNode(!1);var i=e.ownerDocument.defaultView;if(i&&X_(e)&&(J_(e)||Y_(e))){var r=this.createElementClone(e);r.style.transitionProperty="none";var s=i.getComputedStyle(e),n=i.getComputedStyle(e,":before"),o=i.getComputedStyle(e,":after");this.referenceElement===e&&J_(r)&&(this.clonedReferenceElement=r),ty(r)&&Ly(r);var a=this.counters.parse(new Wm(this.context,s)),l=this.resolvePseudoContent(e,r,n,s_.BEFORE);cy(e)&&(t=!0),ry(e)||this.cloneChildNodes(e,r,t),l&&r.insertBefore(l,r.firstChild);var u=this.resolvePseudoContent(e,r,o,s_.AFTER);return u&&r.appendChild(u),this.counters.pop(a),(s&&(this.options.copyStyles||Y_(e))&&!ny(e)||t)&&Fy(s,r),0===e.scrollTop&&0===e.scrollLeft||this.scrolledElements.push([r,e.scrollLeft,e.scrollTop]),(ay(e)||ly(e))&&(ay(r)||ly(r))&&(r.value=e.value),r}return e.cloneNode(!1)},e.prototype.resolvePseudoContent=function(e,t,i,r){var s=this;if(i){var n=i.content,o=t.ownerDocument;if(o&&n&&"none"!==n&&"-moz-alt-content"!==n&&"none"!==i.display){this.counters.parse(new Wm(this.context,i));var a=new zm(this.context,i),l=o.createElement("html2canvaspseudoelement");Fy(i,l),a.content.forEach((function(t){if(0===t.type)l.appendChild(o.createTextNode(t.value));else if(22===t.type){var i=o.createElement("img");i.src=t.value,i.style.opacity="1",l.appendChild(i)}else if(18===t.type){if("attr"===t.name){var r=t.values.filter(Pv);r.length&&l.appendChild(o.createTextNode(e.getAttribute(r[0].value)||""))}else if("counter"===t.name){var n=t.values.filter(Fv),u=n[0],c=n[1];if(u&&Pv(u)){var A=s.counters.getCounterValue(u.value),h=c&&Pv(c)?$g.parse(s.context,c.value):3;l.appendChild(o.createTextNode(by(A,h,!1)))}}else if("counters"===t.name){var d=t.values.filter(Fv),p=(u=d[0],d[1]);c=d[2];if(u&&Pv(u)){var f=s.counters.getCounterValues(u.value),v=c&&Pv(c)?$g.parse(s.context,c.value):3,g=p&&0===p.type?p.value:"",m=f.map((function(e){return by(e,v,!1)})).join(g);l.appendChild(o.createTextNode(m))}}}else if(20===t.type)switch(t.value){case"open-quote":l.appendChild(o.createTextNode(Nm(a.quotes,s.quoteDepth++,!0)));break;case"close-quote":l.appendChild(o.createTextNode(Nm(a.quotes,--s.quoteDepth,!1)));break;default:l.appendChild(o.createTextNode(t.value))}})),l.className=Sy+" "+Ty;var u=r===s_.BEFORE?" "+Sy:" "+Ty;return Y_(t)?t.className.baseValue+=u:t.className+=u,l}}},e.destroy=function(e){return!!e.parentNode&&(e.parentNode.removeChild(e),!0)},e}();!function(e){e[e.BEFORE=0]="BEFORE",e[e.AFTER=1]="AFTER"}(s_||(s_={}));var wy,By=function(e,t){var i=e.createElement("iframe");return i.className="html2canvas-container",i.style.visibility="hidden",i.style.position="fixed",i.style.left="-10000px",i.style.top="0px",i.style.border="0",i.width=t.width.toString(),i.height=t.height.toString(),i.scrolling="no",i.setAttribute("data-html2canvas-ignore","true"),e.body.appendChild(i),i},Py=function(e){return new Promise((function(t){e.complete?t():e.src?(e.onload=t,e.onerror=t):t()}))},Cy=function(e){return Promise.all([].slice.call(e.images,0).map(Py))},My=function(e){return new Promise((function(t,i){var r=e.contentWindow;if(!r)return i("No window assigned for iframe");var s=r.document;r.onload=e.onload=function(){r.onload=e.onload=null;var i=setInterval((function(){s.body.childNodes.length>0&&"complete"===s.readyState&&(clearInterval(i),t(e))}),50)}}))},Ey=["all","d","content"],Fy=function(e,t){for(var i=e.length-1;i>=0;i--){var r=e.item(i);-1===Ey.indexOf(r)&&t.style.setProperty(r,e.getPropertyValue(r))}return t},ky=function(e){var t="";return e&&(t+=""),t},Iy=function(e,t,i){e&&e.defaultView&&(t!==e.defaultView.pageXOffset||i!==e.defaultView.pageYOffset)&&e.defaultView.scrollTo(t,i)},Dy=function(e){var t=e[0],i=e[1],r=e[2];t.scrollLeft=i,t.scrollTop=r},Sy="___html2canvas___pseudoelement_before",Ty="___html2canvas___pseudoelement_after",Ly=function(e){Ry(e,"."+Sy+':before{\n content: "" !important;\n display: none !important;\n}\n .'+Ty+':after{\n content: "" !important;\n display: none !important;\n}')},Ry=function(e,t){var i=e.ownerDocument;if(i){var r=i.createElement("style");r.textContent=t,e.appendChild(r)}},Uy=function(){function e(){}return e.getOrigin=function(t){var i=e._link;return i?(i.href=t,i.href=i.href,i.protocol+i.hostname+i.port):"about:blank"},e.isSameOrigin=function(t){return e.getOrigin(t)===e._origin},e.setContext=function(t){e._link=t.document.createElement("a"),e._origin=e.getOrigin(t.location.href)},e._origin="about:blank",e}(),Oy=function(){function e(e,t){this.context=e,this._options=t,this._cache={}}return e.prototype.addImage=function(e){var t=Promise.resolve();return this.has(e)?t:zy(e)||Hy(e)?((this._cache[e]=this.loadImage(e)).catch((function(){})),t):t},e.prototype.match=function(e){return this._cache[e]},e.prototype.loadImage=function(e){return Vp(this,void 0,void 0,(function(){var t,i,r,s,n=this;return Hp(this,(function(o){switch(o.label){case 0:return t=Uy.isSameOrigin(e),i=!jy(e)&&!0===this._options.useCORS&&g_.SUPPORT_CORS_IMAGES&&!t,r=!jy(e)&&!t&&!zy(e)&&"string"==typeof this._options.proxy&&g_.SUPPORT_CORS_XHR&&!i,t||!1!==this._options.allowTaint||jy(e)||zy(e)||r||i?(s=e,r?[4,this.proxy(s)]:[3,2]):[2];case 1:s=o.sent(),o.label=2;case 2:return this.context.logger.debug("Added image "+e.substring(0,256)),[4,new Promise((function(e,t){var r=new Image;r.onload=function(){return e(r)},r.onerror=t,(Gy(s)||i)&&(r.crossOrigin="anonymous"),r.src=s,!0===r.complete&&setTimeout((function(){return e(r)}),500),n._options.imageTimeout>0&&setTimeout((function(){return t("Timed out ("+n._options.imageTimeout+"ms) loading image")}),n._options.imageTimeout)}))];case 3:return[2,o.sent()]}}))}))},e.prototype.has=function(e){return void 0!==this._cache[e]},e.prototype.keys=function(){return Promise.resolve(Object.keys(this._cache))},e.prototype.proxy=function(e){var t=this,i=this._options.proxy;if(!i)throw new Error("No proxy defined");var r=e.substring(0,256);return new Promise((function(s,n){var o=g_.SUPPORT_RESPONSE_TYPE?"blob":"text",a=new XMLHttpRequest;a.onload=function(){if(200===a.status)if("text"===o)s(a.response);else{var e=new FileReader;e.addEventListener("load",(function(){return s(e.result)}),!1),e.addEventListener("error",(function(e){return n(e)}),!1),e.readAsDataURL(a.response)}else n("Failed to proxy resource "+r+" with status code "+a.status)},a.onerror=n;var l=i.indexOf("?")>-1?"&":"?";if(a.open("GET",""+i+l+"url="+encodeURIComponent(e)+"&responseType="+o),"text"!==o&&a instanceof XMLHttpRequest&&(a.responseType=o),t._options.imageTimeout){var u=t._options.imageTimeout;a.timeout=u,a.ontimeout=function(){return n("Timed out ("+u+"ms) proxying "+r)}}a.send()}))},e}(),Ny=/^data:image\/svg\+xml/i,Qy=/^data:image\/.*;base64,/i,Vy=/^data:image\/.*/i,Hy=function(e){return g_.SUPPORT_SVG_DRAWING||!Wy(e)},jy=function(e){return Vy.test(e)},Gy=function(e){return Qy.test(e)},zy=function(e){return"blob"===e.substr(0,4)},Wy=function(e){return"svg"===e.substr(-3).toLowerCase()||Ny.test(e)},Ky=function(){function e(e,t){this.type=0,this.x=e,this.y=t}return e.prototype.add=function(t,i){return new e(this.x+t,this.y+i)},e}(),Xy=function(e,t,i){return new Ky(e.x+(t.x-e.x)*i,e.y+(t.y-e.y)*i)},Jy=function(){function e(e,t,i,r){this.type=1,this.start=e,this.startControl=t,this.endControl=i,this.end=r}return e.prototype.subdivide=function(t,i){var r=Xy(this.start,this.startControl,t),s=Xy(this.startControl,this.endControl,t),n=Xy(this.endControl,this.end,t),o=Xy(r,s,t),a=Xy(s,n,t),l=Xy(o,a,t);return i?new e(this.start,r,o,l):new e(l,a,n,this.end)},e.prototype.add=function(t,i){return new e(this.start.add(t,i),this.startControl.add(t,i),this.endControl.add(t,i),this.end.add(t,i))},e.prototype.reverse=function(){return new e(this.end,this.endControl,this.startControl,this.start)},e}(),Yy=function(e){return 1===e.type},Zy=function(e){var t=e.styles,i=e.bounds,r=Ov(t.borderTopLeftRadius,i.width,i.height),s=r[0],n=r[1],o=Ov(t.borderTopRightRadius,i.width,i.height),a=o[0],l=o[1],u=Ov(t.borderBottomRightRadius,i.width,i.height),c=u[0],A=u[1],h=Ov(t.borderBottomLeftRadius,i.width,i.height),d=h[0],p=h[1],f=[];f.push((s+a)/i.width),f.push((d+c)/i.width),f.push((n+p)/i.height),f.push((l+A)/i.height);var v=Math.max.apply(Math,f);v>1&&(s/=v,n/=v,a/=v,l/=v,c/=v,A/=v,d/=v,p/=v);var g=i.width-a,m=i.height-A,_=i.width-c,y=i.height-p,b=t.borderTopWidth,x=t.borderRightWidth,w=t.borderBottomWidth,B=t.borderLeftWidth,P=Nv(t.paddingTop,e.bounds.width),C=Nv(t.paddingRight,e.bounds.width),M=Nv(t.paddingBottom,e.bounds.width),E=Nv(t.paddingLeft,e.bounds.width);this.topLeftBorderDoubleOuterBox=s>0||n>0?qy(i.left+B/3,i.top+b/3,s-B/3,n-b/3,wy.TOP_LEFT):new Ky(i.left+B/3,i.top+b/3),this.topRightBorderDoubleOuterBox=s>0||n>0?qy(i.left+g,i.top+b/3,a-x/3,l-b/3,wy.TOP_RIGHT):new Ky(i.left+i.width-x/3,i.top+b/3),this.bottomRightBorderDoubleOuterBox=c>0||A>0?qy(i.left+_,i.top+m,c-x/3,A-w/3,wy.BOTTOM_RIGHT):new Ky(i.left+i.width-x/3,i.top+i.height-w/3),this.bottomLeftBorderDoubleOuterBox=d>0||p>0?qy(i.left+B/3,i.top+y,d-B/3,p-w/3,wy.BOTTOM_LEFT):new Ky(i.left+B/3,i.top+i.height-w/3),this.topLeftBorderDoubleInnerBox=s>0||n>0?qy(i.left+2*B/3,i.top+2*b/3,s-2*B/3,n-2*b/3,wy.TOP_LEFT):new Ky(i.left+2*B/3,i.top+2*b/3),this.topRightBorderDoubleInnerBox=s>0||n>0?qy(i.left+g,i.top+2*b/3,a-2*x/3,l-2*b/3,wy.TOP_RIGHT):new Ky(i.left+i.width-2*x/3,i.top+2*b/3),this.bottomRightBorderDoubleInnerBox=c>0||A>0?qy(i.left+_,i.top+m,c-2*x/3,A-2*w/3,wy.BOTTOM_RIGHT):new Ky(i.left+i.width-2*x/3,i.top+i.height-2*w/3),this.bottomLeftBorderDoubleInnerBox=d>0||p>0?qy(i.left+2*B/3,i.top+y,d-2*B/3,p-2*w/3,wy.BOTTOM_LEFT):new Ky(i.left+2*B/3,i.top+i.height-2*w/3),this.topLeftBorderStroke=s>0||n>0?qy(i.left+B/2,i.top+b/2,s-B/2,n-b/2,wy.TOP_LEFT):new Ky(i.left+B/2,i.top+b/2),this.topRightBorderStroke=s>0||n>0?qy(i.left+g,i.top+b/2,a-x/2,l-b/2,wy.TOP_RIGHT):new Ky(i.left+i.width-x/2,i.top+b/2),this.bottomRightBorderStroke=c>0||A>0?qy(i.left+_,i.top+m,c-x/2,A-w/2,wy.BOTTOM_RIGHT):new Ky(i.left+i.width-x/2,i.top+i.height-w/2),this.bottomLeftBorderStroke=d>0||p>0?qy(i.left+B/2,i.top+y,d-B/2,p-w/2,wy.BOTTOM_LEFT):new Ky(i.left+B/2,i.top+i.height-w/2),this.topLeftBorderBox=s>0||n>0?qy(i.left,i.top,s,n,wy.TOP_LEFT):new Ky(i.left,i.top),this.topRightBorderBox=a>0||l>0?qy(i.left+g,i.top,a,l,wy.TOP_RIGHT):new Ky(i.left+i.width,i.top),this.bottomRightBorderBox=c>0||A>0?qy(i.left+_,i.top+m,c,A,wy.BOTTOM_RIGHT):new Ky(i.left+i.width,i.top+i.height),this.bottomLeftBorderBox=d>0||p>0?qy(i.left,i.top+y,d,p,wy.BOTTOM_LEFT):new Ky(i.left,i.top+i.height),this.topLeftPaddingBox=s>0||n>0?qy(i.left+B,i.top+b,Math.max(0,s-B),Math.max(0,n-b),wy.TOP_LEFT):new Ky(i.left+B,i.top+b),this.topRightPaddingBox=a>0||l>0?qy(i.left+Math.min(g,i.width-x),i.top+b,g>i.width+x?0:Math.max(0,a-x),Math.max(0,l-b),wy.TOP_RIGHT):new Ky(i.left+i.width-x,i.top+b),this.bottomRightPaddingBox=c>0||A>0?qy(i.left+Math.min(_,i.width-B),i.top+Math.min(m,i.height-w),Math.max(0,c-x),Math.max(0,A-w),wy.BOTTOM_RIGHT):new Ky(i.left+i.width-x,i.top+i.height-w),this.bottomLeftPaddingBox=d>0||p>0?qy(i.left+B,i.top+Math.min(y,i.height-w),Math.max(0,d-B),Math.max(0,p-w),wy.BOTTOM_LEFT):new Ky(i.left+B,i.top+i.height-w),this.topLeftContentBox=s>0||n>0?qy(i.left+B+E,i.top+b+P,Math.max(0,s-(B+E)),Math.max(0,n-(b+P)),wy.TOP_LEFT):new Ky(i.left+B+E,i.top+b+P),this.topRightContentBox=a>0||l>0?qy(i.left+Math.min(g,i.width+B+E),i.top+b+P,g>i.width+B+E?0:a-B+E,l-(b+P),wy.TOP_RIGHT):new Ky(i.left+i.width-(x+C),i.top+b+P),this.bottomRightContentBox=c>0||A>0?qy(i.left+Math.min(_,i.width-(B+E)),i.top+Math.min(m,i.height+b+P),Math.max(0,c-(x+C)),A-(w+M),wy.BOTTOM_RIGHT):new Ky(i.left+i.width-(x+C),i.top+i.height-(w+M)),this.bottomLeftContentBox=d>0||p>0?qy(i.left+B+E,i.top+y,Math.max(0,d-(B+E)),p-(w+M),wy.BOTTOM_LEFT):new Ky(i.left+B+E,i.top+i.height-(w+M))};!function(e){e[e.TOP_LEFT=0]="TOP_LEFT",e[e.TOP_RIGHT=1]="TOP_RIGHT",e[e.BOTTOM_RIGHT=2]="BOTTOM_RIGHT",e[e.BOTTOM_LEFT=3]="BOTTOM_LEFT"}(wy||(wy={}));var qy=function(e,t,i,r,s){var n=(Math.sqrt(2)-1)/3*4,o=i*n,a=r*n,l=e+i,u=t+r;switch(s){case wy.TOP_LEFT:return new Jy(new Ky(e,u),new Ky(e,u-a),new Ky(l-o,t),new Ky(l,t));case wy.TOP_RIGHT:return new Jy(new Ky(e,t),new Ky(e+o,t),new Ky(l,u-a),new Ky(l,u));case wy.BOTTOM_RIGHT:return new Jy(new Ky(l,t),new Ky(l,t+a),new Ky(e+o,u),new Ky(e,u));case wy.BOTTOM_LEFT:default:return new Jy(new Ky(l,u),new Ky(l-o,u),new Ky(e,t+a),new Ky(e,t))}},$y=function(e){return[e.topLeftBorderBox,e.topRightBorderBox,e.bottomRightBorderBox,e.bottomLeftBorderBox]},eb=function(e){return[e.topLeftPaddingBox,e.topRightPaddingBox,e.bottomRightPaddingBox,e.bottomLeftPaddingBox]},tb=function(e,t,i){this.offsetX=e,this.offsetY=t,this.matrix=i,this.type=0,this.target=6},ib=function(e,t){this.path=e,this.target=t,this.type=1},rb=function(e){this.opacity=e,this.type=2,this.target=6},sb=function(e){return 1===e.type},nb=function(e,t){return e.length===t.length&&e.some((function(e,i){return e===t[i]}))},ob=function(e){this.element=e,this.inlineLevel=[],this.nonInlineLevel=[],this.negativeZIndex=[],this.zeroOrAutoZIndexOrTransformedOrOpacity=[],this.positiveZIndex=[],this.nonPositionedFloats=[],this.nonPositionedInlineLevel=[]},ab=function(){function e(e,t){if(this.container=e,this.parent=t,this.effects=[],this.curves=new Zy(this.container),this.container.styles.opacity<1&&this.effects.push(new rb(this.container.styles.opacity)),null!==this.container.styles.transform){var i=this.container.bounds.left+this.container.styles.transformOrigin[0].number,r=this.container.bounds.top+this.container.styles.transformOrigin[1].number,s=this.container.styles.transform;this.effects.push(new tb(i,r,s))}if(0!==this.container.styles.overflowX){var n=$y(this.curves),o=eb(this.curves);nb(n,o)?this.effects.push(new ib(n,6)):(this.effects.push(new ib(n,2)),this.effects.push(new ib(o,4)))}}return e.prototype.getEffects=function(e){for(var t=-1===[2,3].indexOf(this.container.styles.position),i=this.parent,r=this.effects.slice(0);i;){var s=i.effects.filter((function(e){return!sb(e)}));if(t||0!==i.container.styles.position||!i.parent){if(r.unshift.apply(r,s),t=-1===[2,3].indexOf(i.container.styles.position),0!==i.container.styles.overflowX){var n=$y(i.curves),o=eb(i.curves);nb(n,o)||r.unshift(new ib(o,6))}}else r.unshift.apply(r,s);i=i.parent}return r.filter((function(t){return Sm(t.target,e)}))},e}(),lb=function e(t,i,r,s){t.container.elements.forEach((function(n){var o=Sm(n.flags,4),a=Sm(n.flags,2),l=new ab(n,t);Sm(n.styles.display,2048)&&s.push(l);var u=Sm(n.flags,8)?[]:s;if(o||a){var c=o||n.styles.isPositioned()?r:i,A=new ob(l);if(n.styles.isPositioned()||n.styles.opacity<1||n.styles.isTransformed()){var h=n.styles.zIndex.order;if(h<0){var d=0;c.negativeZIndex.some((function(e,t){return h>e.element.container.styles.zIndex.order?(d=t,!1):d>0})),c.negativeZIndex.splice(d,0,A)}else if(h>0){var p=0;c.positiveZIndex.some((function(e,t){return h>=e.element.container.styles.zIndex.order?(p=t+1,!1):p>0})),c.positiveZIndex.splice(p,0,A)}else c.zeroOrAutoZIndexOrTransformedOrOpacity.push(A)}else n.styles.isFloating()?c.nonPositionedFloats.push(A):c.nonPositionedInlineLevel.push(A);e(l,A,o?A:r,u)}else n.styles.isInlineLevel()?i.inlineLevel.push(l):i.nonInlineLevel.push(l),e(l,i,r,u);Sm(n.flags,8)&&ub(n,u)}))},ub=function(e,t){for(var i=e instanceof S_?e.start:1,r=e instanceof S_&&e.reversed,s=0;s0&&e.intrinsicHeight>0){var r=fb(e),s=eb(t);this.path(s),this.ctx.save(),this.ctx.clip(),this.ctx.drawImage(i,0,0,e.intrinsicWidth,e.intrinsicHeight,r.left,r.top,r.width,r.height),this.ctx.restore()}},t.prototype.renderNodeContent=function(e){return Vp(this,void 0,void 0,(function(){var i,r,s,n,o,a,l,u,c,A,h,d,p,f,v,g,m,_;return Hp(this,(function(y){switch(y.label){case 0:this.applyEffects(e.getEffects(4)),i=e.container,r=e.curves,s=i.styles,n=0,o=i.textNodes,y.label=1;case 1:return n0&&w>0&&(g=r.ctx.createPattern(p,"repeat"),r.renderRepeat(_,g,P,C))):function(e){return 2===e.type}(i)&&(m=vb(e,t,[null,null,null]),_=m[0],y=m[1],b=m[2],x=m[3],w=m[4],B=0===i.position.length?[Rv]:i.position,P=Nv(B[0],x),C=Nv(B[B.length-1],w),M=function(e,t,i,r,s){var n=0,o=0;switch(e.size){case 0:0===e.shape?n=o=Math.min(Math.abs(t),Math.abs(t-r),Math.abs(i),Math.abs(i-s)):1===e.shape&&(n=Math.min(Math.abs(t),Math.abs(t-r)),o=Math.min(Math.abs(i),Math.abs(i-s)));break;case 2:if(0===e.shape)n=o=Math.min(og(t,i),og(t,i-s),og(t-r,i),og(t-r,i-s));else if(1===e.shape){var a=Math.min(Math.abs(i),Math.abs(i-s))/Math.min(Math.abs(t),Math.abs(t-r)),l=ag(r,s,t,i,!0),u=l[0],c=l[1];o=a*(n=og(u-t,(c-i)/a))}break;case 1:0===e.shape?n=o=Math.max(Math.abs(t),Math.abs(t-r),Math.abs(i),Math.abs(i-s)):1===e.shape&&(n=Math.max(Math.abs(t),Math.abs(t-r)),o=Math.max(Math.abs(i),Math.abs(i-s)));break;case 3:if(0===e.shape)n=o=Math.max(og(t,i),og(t,i-s),og(t-r,i),og(t-r,i-s));else if(1===e.shape){a=Math.max(Math.abs(i),Math.abs(i-s))/Math.max(Math.abs(t),Math.abs(t-r));var A=ag(r,s,t,i,!1);u=A[0],c=A[1],o=a*(n=og(u-t,(c-i)/a))}}return Array.isArray(e.size)&&(n=Nv(e.size[0],r),o=2===e.size.length?Nv(e.size[1],s):n),[n,o]}(i,P,C,x,w),E=M[0],F=M[1],E>0&&F>0&&(k=r.ctx.createRadialGradient(y+P,b+C,0,y+P,b+C,E),sg(i.stops,2*E).forEach((function(e){return k.addColorStop(e.stop,Wv(e.color))})),r.path(_),r.ctx.fillStyle=k,E!==F?(I=e.bounds.left+.5*e.bounds.width,D=e.bounds.top+.5*e.bounds.height,T=1/(S=F/E),r.ctx.save(),r.ctx.translate(I,D),r.ctx.transform(1,0,0,S,0,0),r.ctx.translate(-I,-D),r.ctx.fillRect(y,T*(b-D)+D,x,w*T),r.ctx.restore()):r.ctx.fill())),L.label=6;case 6:return t--,[2]}}))},r=this,s=0,n=e.styles.backgroundImage.slice(0).reverse(),a.label=1;case 1:return s0?2!==l.style?[3,5]:[4,this.renderDashedDottedBorder(l.color,l.width,n,e.curves,2)]:[3,11]:[3,13];case 4:return c.sent(),[3,11];case 5:return 3!==l.style?[3,7]:[4,this.renderDashedDottedBorder(l.color,l.width,n,e.curves,3)];case 6:return c.sent(),[3,11];case 7:return 4!==l.style?[3,9]:[4,this.renderDoubleBorder(l.color,l.width,n,e.curves)];case 8:return c.sent(),[3,11];case 9:return[4,this.renderSolidBorder(l.color,n,e.curves)];case 10:c.sent(),c.label=11;case 11:n++,c.label=12;case 12:return o++,[3,3];case 13:return[2]}}))}))},t.prototype.renderDashedDottedBorder=function(e,t,i,r,s){return Vp(this,void 0,void 0,(function(){var n,o,a,l,u,c,A,h,d,p,f,v,g,m,_,y;return Hp(this,(function(b){return this.ctx.save(),n=function(e,t){switch(t){case 0:return hb(e.topLeftBorderStroke,e.topRightBorderStroke);case 1:return hb(e.topRightBorderStroke,e.bottomRightBorderStroke);case 2:return hb(e.bottomRightBorderStroke,e.bottomLeftBorderStroke);default:return hb(e.bottomLeftBorderStroke,e.topLeftBorderStroke)}}(r,i),o=Ab(r,i),2===s&&(this.path(o),this.ctx.clip()),Yy(o[0])?(a=o[0].start.x,l=o[0].start.y):(a=o[0].x,l=o[0].y),Yy(o[1])?(u=o[1].end.x,c=o[1].end.y):(u=o[1].x,c=o[1].y),A=0===i||2===i?Math.abs(a-u):Math.abs(l-c),this.ctx.beginPath(),3===s?this.formatPath(n):this.formatPath(o.slice(0,2)),h=t<3?3*t:2*t,d=t<3?2*t:t,3===s&&(h=t,d=t),p=!0,A<=2*h?p=!1:A<=2*h+d?(h*=f=A/(2*h+d),d*=f):(v=Math.floor((A+d)/(h+d)),g=(A-v*h)/(v-1),d=(m=(A-(v+1)*h)/v)<=0||Math.abs(d-g)0&&void 0!==arguments[0]?arguments[0]:{},t=!this._snapshotBegun,i=void 0!==e.width&&void 0!==e.height,r=this.scene.canvas.canvas,s=r.clientWidth,n=r.clientHeight,o=e.width?Math.floor(e.width):r.width,a=e.height?Math.floor(e.height):r.height;i&&(r.width=o,r.height=a),this._snapshotBegun||this.beginSnapshot({width:o,height:a}),e.includeGizmos||this.sendToPlugins("snapshotStarting");for(var l={},u=0,c=this._plugins.length;u0&&void 0!==x[0]?x[0]:{},i=!this._snapshotBegun,r=void 0!==t.width&&void 0!==t.height,s=this.scene.canvas.canvas,n=s.clientWidth,o=s.clientHeight,l=t.width?Math.floor(t.width):s.width,u=t.height?Math.floor(t.height):s.height,r&&(s.width=l,s.height=u),this._snapshotBegun||this.beginSnapshot(),t.includeGizmos||this.sendToPlugins("snapshotStarting"),this.scene._renderer.renderSnapshot(),c=this.scene._renderer.readSnapshotAsCanvas(),r&&(s.width=n,s.height=o,this.scene.glRedraw()),A={},h=[],d=0,p=this._plugins.length;d1&&void 0!==arguments[1])||arguments[1],i=arguments.length>2?arguments[2]:void 0,r=i||new Set;if(e){if(tx(e))r.add(e);else if(tx(e.buffer))r.add(e.buffer);else if(ArrayBuffer.isView(e));else if(t&&"object"===w(e))for(var s in e)ex(e[s],t,r)}else;return void 0===i?Array.from(r):[]}function tx(e){return!!e&&(e instanceof ArrayBuffer||("undefined"!=typeof MessagePort&&e instanceof MessagePort||("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)))}var ix=function(){},rx=function(){function e(t){B(this,e),Xb(this,"name",void 0),Xb(this,"source",void 0),Xb(this,"url",void 0),Xb(this,"terminated",!1),Xb(this,"worker",void 0),Xb(this,"onMessage",void 0),Xb(this,"onError",void 0),Xb(this,"_loadableURL","");var i=t.name,r=t.source,s=t.url;Vb(r||s),this.name=i,this.source=r,this.url=s,this.onMessage=ix,this.onError=function(e){return console.log(e)},this.worker=Gb?this._createBrowserWorker():this._createNodeWorker()}return C(e,[{key:"destroy",value:function(){this.onMessage=ix,this.onError=ix,this.worker.terminate(),this.terminated=!0}},{key:"isRunning",get:function(){return Boolean(this.onMessage)}},{key:"postMessage",value:function(e,t){t=t||ex(e),this.worker.postMessage(e,t)}},{key:"_getErrorFromErrorEvent",value:function(e){var t="Failed to load ";return t+="worker ".concat(this.name," from ").concat(this.url,". "),e.message&&(t+="".concat(e.message," in ")),e.lineno&&(t+=":".concat(e.lineno,":").concat(e.colno)),new Error(t)}},{key:"_createBrowserWorker",value:function(){var e=this;this._loadableURL=qb({source:this.source,url:this.url});var t=new Worker(this._loadableURL,{name:this.name});return t.onmessage=function(t){t.data?e.onMessage(t.data):e.onError(new Error("No data received"))},t.onerror=function(t){e.onError(e._getErrorFromErrorEvent(t)),e.terminated=!0},t.onmessageerror=function(e){return console.error(e)},t}},{key:"_createNodeWorker",value:function(){var e,t=this;if(this.url){var i=this.url.includes(":/")||this.url.startsWith("/")?this.url:"./".concat(this.url);e=new Yb(i,{eval:!1})}else{if(!this.source)throw new Error("no worker");e=new Yb(this.source,{eval:!0})}return e.on("message",(function(e){t.onMessage(e)})),e.on("error",(function(e){t.onError(e)})),e.on("exit",(function(e){})),e}}],[{key:"isSupported",value:function(){return"undefined"!=typeof Worker&&Gb||void 0!==w(Yb)}}]),e}(),sx=function(){function e(t){B(this,e),Xb(this,"name","unnamed"),Xb(this,"source",void 0),Xb(this,"url",void 0),Xb(this,"maxConcurrency",1),Xb(this,"maxMobileConcurrency",1),Xb(this,"onDebug",(function(){})),Xb(this,"reuseWorkers",!0),Xb(this,"props",{}),Xb(this,"jobQueue",[]),Xb(this,"idleQueue",[]),Xb(this,"count",0),Xb(this,"isDestroyed",!1),this.source=t.source,this.url=t.url,this.setProps(t)}var t,i;return C(e,[{key:"destroy",value:function(){this.idleQueue.forEach((function(e){return e.destroy()})),this.isDestroyed=!0}},{key:"setProps",value:function(e){this.props=n(n({},this.props),e),void 0!==e.name&&(this.name=e.name),void 0!==e.maxConcurrency&&(this.maxConcurrency=e.maxConcurrency),void 0!==e.maxMobileConcurrency&&(this.maxMobileConcurrency=e.maxMobileConcurrency),void 0!==e.reuseWorkers&&(this.reuseWorkers=e.reuseWorkers),void 0!==e.onDebug&&(this.onDebug=e.onDebug)}},{key:"startJob",value:(i=u(a().mark((function e(t){var i,r,s,n=this,o=arguments;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=o.length>1&&void 0!==o[1]?o[1]:function(e,t,i){return e.done(i)},r=o.length>2&&void 0!==o[2]?o[2]:function(e,t){return e.error(t)},s=new Promise((function(e){return n.jobQueue.push({name:t,onMessage:i,onError:r,onStart:e}),n})),this._startQueuedJob(),e.next=6,s;case 6:return e.abrupt("return",e.sent);case 7:case"end":return e.stop()}}),e,this)}))),function(e){return i.apply(this,arguments)})},{key:"_startQueuedJob",value:(t=u(a().mark((function e(){var t,i,r;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.jobQueue.length){e.next=2;break}return e.abrupt("return");case 2:if(t=this._getAvailableWorker()){e.next=5;break}return e.abrupt("return");case 5:if(!(i=this.jobQueue.shift())){e.next=18;break}return this.onDebug({message:"Starting job",name:i.name,workerThread:t,backlog:this.jobQueue.length}),r=new Jb(i.name,t),t.onMessage=function(e){return i.onMessage(r,e.type,e.payload)},t.onError=function(e){return i.onError(r,e)},i.onStart(r),e.prev=12,e.next=15,r.result;case 15:return e.prev=15,this.returnWorkerToQueue(t),e.finish(15);case 18:case"end":return e.stop()}}),e,this,[[12,,15,18]])}))),function(){return t.apply(this,arguments)})},{key:"returnWorkerToQueue",value:function(e){this.isDestroyed||!this.reuseWorkers||this.count>this._getMaxConcurrency()?(e.destroy(),this.count--):this.idleQueue.push(e),this.isDestroyed||this._startQueuedJob()}},{key:"_getAvailableWorker",value:function(){if(this.idleQueue.length>0)return this.idleQueue.shift()||null;if(this.count0&&void 0!==arguments[0]?arguments[0]:{};return e._workerFarm=e._workerFarm||new e({}),e._workerFarm.setProps(t),e._workerFarm}}]),e}();Xb(ox,"_workerFarm",void 0);function ax(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t[e.id]||{},r="".concat(e.id,"-worker.js"),s=i.workerUrl;if(s||"compression"!==e.id||(s=t.workerUrl),"test"===t._workerType&&(s="modules/".concat(e.module,"/dist/").concat(r)),!s){var n=e.version;"latest"===n&&(n="latest");var o=n?"@".concat(n):"";s="https://unpkg.com/@loaders.gl/".concat(e.module).concat(o,"/dist/").concat(r)}return Vb(s),s}function lx(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"3.2.6";Vb(e,"no worker provided");var i=e.version;return!(!t||!i)}var ux=Object.freeze({__proto__:null,default:{}}),cx={};function Ax(e){return hx.apply(this,arguments)}function hx(){return hx=u(a().mark((function e(t){var i,r,s=arguments;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=s.length>1&&void 0!==s[1]?s[1]:null,r=s.length>2&&void 0!==s[2]?s[2]:{},i&&(t=dx(t,i,r)),cx[t]=cx[t]||px(t),e.next=6,cx[t];case 6:return e.abrupt("return",e.sent);case 7:case"end":return e.stop()}}),e)}))),hx.apply(this,arguments)}function dx(e,t,i){if(e.startsWith("http"))return e;var r=i.modules||{};return r[e]?r[e]:Gb?i.CDN?(Vb(i.CDN.startsWith("http")),"".concat(i.CDN,"/").concat(t,"@").concat("3.2.6","/dist/libs/").concat(e)):zb?"../src/libs/".concat(e):"modules/".concat(t,"/src/libs/").concat(e):"modules/".concat(t,"/dist/libs/").concat(e)}function px(e){return fx.apply(this,arguments)}function fx(){return(fx=u(a().mark((function e(t){var i,r,s;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.endsWith("wasm")){e.next=7;break}return e.next=3,fetch(t);case 3:return i=e.sent,e.next=6,i.arrayBuffer();case 6:return e.abrupt("return",e.sent);case 7:if(Gb){e.next=20;break}if(e.prev=8,e.t0=ux&&void 0,!e.t0){e.next=14;break}return e.next=13,(void 0)(t);case 13:e.t0=e.sent;case 14:return e.abrupt("return",e.t0);case 17:return e.prev=17,e.t1=e.catch(8),e.abrupt("return",null);case 20:if(!zb){e.next=22;break}return e.abrupt("return",importScripts(t));case 22:return e.next=24,fetch(t);case 24:return r=e.sent,e.next=27,r.text();case 27:return s=e.sent,e.abrupt("return",vx(s,t));case 29:case"end":return e.stop()}}),e,null,[[8,17]])})))).apply(this,arguments)}function vx(e,t){if(Gb){if(zb)return eval.call(jb,e),null;var i=document.createElement("script");i.id=t;try{i.appendChild(document.createTextNode(e))}catch(t){i.text=e}return document.body.appendChild(i),null}}function gx(e,t){return!!ox.isSupported()&&(!!(Gb||null!=t&&t._nodeWorkers)&&(e.worker&&(null==t?void 0:t.worker)))}function mx(e,t,i,r,s){return _x.apply(this,arguments)}function _x(){return _x=u(a().mark((function e(t,i,r,s,n){var o,l,u,c,A,h;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return o=t.id,l=ax(t,r),u=ox.getWorkerFarm(r),c=u.getWorkerPool({name:o,url:l}),r=JSON.parse(JSON.stringify(r)),s=JSON.parse(JSON.stringify(s||{})),e.next=8,c.startJob("process-on-worker",yx.bind(null,n));case 8:return(A=e.sent).postMessage("process",{input:i,options:r,context:s}),e.next=12,A.result;case 12:return h=e.sent,e.next=15,h.result;case 15:return e.abrupt("return",e.sent);case 16:case"end":return e.stop()}}),e)}))),_x.apply(this,arguments)}function yx(e,t,i,r){return bx.apply(this,arguments)}function bx(){return(bx=u(a().mark((function e(t,i,r,s){var n,o,l,u,c;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:e.t0=r,e.next="done"===e.t0?3:"error"===e.t0?5:"process"===e.t0?7:20;break;case 3:return i.done(s),e.abrupt("break",21);case 5:return i.error(new Error(s.error)),e.abrupt("break",21);case 7:return n=s.id,o=s.input,l=s.options,e.prev=8,e.next=11,t(o,l);case 11:u=e.sent,i.postMessage("done",{id:n,result:u}),e.next=19;break;case 15:e.prev=15,e.t1=e.catch(8),c=e.t1 instanceof Error?e.t1.message:"unknown error",i.postMessage("error",{id:n,error:c});case 19:return e.abrupt("break",21);case 20:console.warn("parse-with-worker unknown message ".concat(r));case 21:case"end":return e.stop()}}),e,null,[[8,15]])})))).apply(this,arguments)}function xx(e,t,i){if(e.byteLength<=t+i)return"";for(var r=new DataView(e),s="",n=0;n1&&void 0!==arguments[1]?arguments[1]:5;if("string"==typeof e)return e.slice(0,t);if(ArrayBuffer.isView(e))return xx(e.buffer,e.byteOffset,t);if(e instanceof ArrayBuffer){return xx(e,0,t)}return""}(e),'"'))}}function Bx(e){return e&&"object"===w(e)&&e.isBuffer}function Px(e){if(Bx(e))return Bx(t=e)?new Uint8Array(t.buffer,t.byteOffset,t.length).slice().buffer:t;var t;if(e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e))return 0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);if("string"==typeof e){var i=e;return(new TextEncoder).encode(i).buffer}if(e&&"object"===w(e)&&e._toArrayBuffer)return e._toArrayBuffer();throw new Error("toArrayBuffer")}function Cx(){for(var e=arguments.length,t=new Array(e),i=0;i=0),Ob(t>0),e+(t-1)&~(t-1)}function Fx(e,t,i){var r;if(e instanceof ArrayBuffer)r=new Uint8Array(e);else{var s=e.byteOffset,n=e.byteLength;r=new Uint8Array(e.buffer||e.arrayBuffer,s,n)}return t.set(r,i),i+Ex(r.byteLength,4)}function kx(e){return Ix.apply(this,arguments)}function Ix(){return(Ix=u(a().mark((function e(t){var i,r,s,n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=[],r=!1,s=!1,e.prev=3,o=I(t);case 5:return e.next=7,o.next();case 7:if(!(r=!(l=e.sent).done)){e.next=13;break}u=l.value,i.push(u);case 10:r=!1,e.next=5;break;case 13:e.next=19;break;case 15:e.prev=15,e.t0=e.catch(3),s=!0,n=e.t0;case 19:if(e.prev=19,e.prev=20,!r||null==o.return){e.next=24;break}return e.next=24,o.return();case 24:if(e.prev=24,!s){e.next=27;break}throw n;case 27:return e.finish(24);case 28:return e.finish(19);case 29:return e.abrupt("return",Cx.apply(void 0,i));case 30:case"end":return e.stop()}}),e,null,[[3,15,19,29],[20,,24,28]])})))).apply(this,arguments)}var Dx={};function Sx(e){for(var t in Dx)if(e.startsWith(t)){var i=Dx[t];e=e.replace(t,i)}return e.startsWith("http://")||e.startsWith("https://")||(e="".concat("").concat(e)),e}var Tx=function(e){return"function"==typeof e},Lx=function(e){return null!==e&&"object"===w(e)},Rx=function(e){return Lx(e)&&e.constructor==={}.constructor},Ux=function(e){return e&&"function"==typeof e[Symbol.iterator]},Ox=function(e){return e&&"function"==typeof e[Symbol.asyncIterator]},Nx=function(e){return"undefined"!=typeof Response&&e instanceof Response||e&&e.arrayBuffer&&e.text&&e.json},Qx=function(e){return"undefined"!=typeof Blob&&e instanceof Blob},Vx=function(e){return function(e){return"undefined"!=typeof ReadableStream&&e instanceof ReadableStream||Lx(e)&&Tx(e.tee)&&Tx(e.cancel)&&Tx(e.getReader)}(e)||function(e){return Lx(e)&&Tx(e.read)&&Tx(e.pipe)&&function(e){return"boolean"==typeof e}(e.readable)}(e)},Hx=/^data:([-\w.]+\/[-\w.+]+)(;|,)/,jx=/^([-\w.]+\/[-\w.+]+)/;function Gx(e){var t=jx.exec(e);return t?t[1]:e}function zx(e){var t=Hx.exec(e);return t?t[1]:""}var Wx=/\?.*/;function Kx(e){if(Nx(e)){var t=Jx(e.url||"");return{url:t,type:Gx(e.headers.get("content-type")||"")||zx(t)}}return Qx(e)?{url:Jx(e.name||""),type:e.type||""}:"string"==typeof e?{url:Jx(e),type:zx(e)}:{url:"",type:""}}function Xx(e){return Nx(e)?e.headers["content-length"]||-1:Qx(e)?e.size:"string"==typeof e?e.length:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:-1}function Jx(e){return e.replace(Wx,"")}function Yx(e){return Zx.apply(this,arguments)}function Zx(){return(Zx=u(a().mark((function e(t){var i,r,s,n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!Nx(t)){e.next=2;break}return e.abrupt("return",t);case 2:return i={},(r=Xx(t))>=0&&(i["content-length"]=String(r)),s=Kx(t),n=s.url,(o=s.type)&&(i["content-type"]=o),e.next=9,iw(t);case 9:return(l=e.sent)&&(i["x-first-bytes"]=l),"string"==typeof t&&(t=(new TextEncoder).encode(t)),u=new Response(t,{headers:i}),Object.defineProperty(u,"url",{value:n}),e.abrupt("return",u);case 15:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function qx(e){return $x.apply(this,arguments)}function $x(){return($x=u(a().mark((function e(t){var i;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.ok){e.next=5;break}return e.next=3,ew(t);case 3:throw i=e.sent,new Error(i);case 5:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ew(e){return tw.apply(this,arguments)}function tw(){return(tw=u(a().mark((function e(t){var i,r,s;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i="Failed to fetch resource ".concat(t.url," (").concat(t.status,"): "),e.prev=1,r=t.headers.get("Content-Type"),s=t.statusText,!r.includes("application/json")){e.next=11;break}return e.t0=s,e.t1=" ",e.next=9,t.text();case 9:e.t2=e.sent,s=e.t0+=e.t1.concat.call(e.t1,e.t2);case 11:i=(i+=s).length>60?"".concat(i.slice(0,60),"..."):i,e.next=17;break;case 15:e.prev=15,e.t3=e.catch(1);case 17:return e.abrupt("return",i);case 18:case"end":return e.stop()}}),e,null,[[1,15]])})))).apply(this,arguments)}function iw(e){return rw.apply(this,arguments)}function rw(){return(rw=u(a().mark((function e(t){var i,r,s,n;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=5,"string"!=typeof t){e.next=3;break}return e.abrupt("return","data:,".concat(t.slice(0,i)));case 3:if(!(t instanceof Blob)){e.next=8;break}return r=t.slice(0,5),e.next=7,new Promise((function(e){var t=new FileReader;t.onload=function(t){var i;return e(null==t||null===(i=t.target)||void 0===i?void 0:i.result)},t.readAsDataURL(r)}));case 7:return e.abrupt("return",e.sent);case 8:if(!(t instanceof ArrayBuffer)){e.next=12;break}return s=t.slice(0,i),n=sw(s),e.abrupt("return","data:base64,".concat(n));case 12:return e.abrupt("return",null);case 13:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function sw(e){for(var t="",i=new Uint8Array(e),r=0;r=0)}();function hw(e){try{var t=window[e],i="__storage_test__";return t.setItem(i,i),t.removeItem(i),t}catch(e){return null}}var dw=function(){function e(t,i){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"sessionStorage";B(this,e),this.storage=hw(r),this.id=t,this.config={},Object.assign(this.config,i),this._loadConfiguration()}return C(e,[{key:"getConfiguration",value:function(){return this.config}},{key:"setConfiguration",value:function(e){return this.config={},this.updateConfiguration(e)}},{key:"updateConfiguration",value:function(e){if(Object.assign(this.config,e),this.storage){var t=JSON.stringify(this.config);this.storage.setItem(this.id,t)}return this}},{key:"_loadConfiguration",value:function(){var e={};if(this.storage){var t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}}]),e}();function pw(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:600,s=e.src.replace(/\(/g,"%28").replace(/\)/g,"%29");e.width>r&&(i=Math.min(i,r/e.width));var n=e.width*i,o=e.height*i,a=["font-size:1px;","padding:".concat(Math.floor(o/2),"px ").concat(Math.floor(n/2),"px;"),"line-height:".concat(o,"px;"),"background:url(".concat(s,");"),"background-size:".concat(n,"px ").concat(o,"px;"),"color:transparent;"].join("");return["".concat(t," %c+"),a]}var fw={BLACK:30,RED:31,GREEN:32,YELLOW:33,BLUE:34,MAGENTA:35,CYAN:36,WHITE:37,BRIGHT_BLACK:90,BRIGHT_RED:91,BRIGHT_GREEN:92,BRIGHT_YELLOW:93,BRIGHT_BLUE:94,BRIGHT_MAGENTA:95,BRIGHT_CYAN:96,BRIGHT_WHITE:97};function vw(e){return"string"==typeof e?fw[e.toUpperCase()]||fw.WHITE:e}function gw(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:["constructor"],r=Object.getPrototypeOf(e),s=Object.getOwnPropertyNames(r),n=c(s);try{var o=function(){var r=t.value;"function"==typeof e[r]&&(i.find((function(e){return r===e}))||(e[r]=e[r].bind(e)))};for(n.s();!(t=n.n()).done;)o()}catch(e){n.e(e)}finally{n.f()}}function mw(e,t){if(!e)throw new Error(t||"Assertion failed")}function _w(){var e;if(Aw&&lw.performance)e=lw.performance.now();else if(uw.hrtime){var t=uw.hrtime();e=1e3*t[0]+t[1]/1e6}else e=Date.now();return e}var yw={debug:Aw&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},bw={enabled:!0,level:0};function xw(){}var ww={},Bw={once:!0};function Pw(e){for(var t in e)for(var i in e[t])return i||"untitled";return"empty"}var Cw=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{id:""},i=t.id;B(this,e),this.id=i,this.VERSION=cw,this._startTs=_w(),this._deltaTs=_w(),this.LOG_THROTTLE_TIMEOUT=0,this._storage=new dw("__probe-".concat(this.id,"__"),bw),this.userData={},this.timeStamp("".concat(this.id," started")),gw(this),Object.seal(this)}return C(e,[{key:"level",get:function(){return this.getLevel()},set:function(e){this.setLevel(e)}},{key:"isEnabled",value:function(){return this._storage.config.enabled}},{key:"getLevel",value:function(){return this._storage.config.level}},{key:"getTotal",value:function(){return Number((_w()-this._startTs).toPrecision(10))}},{key:"getDelta",value:function(){return Number((_w()-this._deltaTs).toPrecision(10))}},{key:"priority",get:function(){return this.level},set:function(e){this.level=e}},{key:"getPriority",value:function(){return this.level}},{key:"enable",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this._storage.updateConfiguration({enabled:e}),this}},{key:"setLevel",value:function(e){return this._storage.updateConfiguration({level:e}),this}},{key:"assert",value:function(e,t){mw(e,t)}},{key:"warn",value:function(e){return this._getLogFunction(0,e,yw.warn,arguments,Bw)}},{key:"error",value:function(e){return this._getLogFunction(0,e,yw.error,arguments)}},{key:"deprecated",value:function(e,t){return this.warn("`".concat(e,"` is deprecated and will be removed in a later version. Use `").concat(t,"` instead"))}},{key:"removed",value:function(e,t){return this.error("`".concat(e,"` has been removed. Use `").concat(t,"` instead"))}},{key:"probe",value:function(e,t){return this._getLogFunction(e,t,yw.log,arguments,{time:!0,once:!0})}},{key:"log",value:function(e,t){return this._getLogFunction(e,t,yw.debug,arguments)}},{key:"info",value:function(e,t){return this._getLogFunction(e,t,console.info,arguments)}},{key:"once",value:function(e,t){return this._getLogFunction(e,t,yw.debug||yw.info,arguments,Bw)}},{key:"table",value:function(e,t,i){return t?this._getLogFunction(e,t,console.table||xw,i&&[i],{tag:Pw(t)}):xw}},{key:"image",value:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){var t=e.logLevel,i=e.priority,r=e.image,s=e.message,n=void 0===s?"":s,o=e.scale,a=void 0===o?1:o;return this._shouldLog(t||i)?Aw?function(e){var t=e.image,i=e.message,r=void 0===i?"":i,s=e.scale,n=void 0===s?1:s;if("string"==typeof t){var o=new Image;return o.onload=function(){var e,t=pw(o,r,n);(e=console).log.apply(e,h(t))},o.src=t,xw}var a=t.nodeName||"";if("img"===a.toLowerCase()){var l;return(l=console).log.apply(l,h(pw(t,r,n))),xw}if("canvas"===a.toLowerCase()){var u=new Image;return u.onload=function(){var e;return(e=console).log.apply(e,h(pw(u,r,n)))},u.src=t.toDataURL(),xw}return xw}({image:r,message:n,scale:a}):function(e){var t=e.image,i=(e.message,e.scale),r=void 0===i?1:i,s=null;try{s=module.require("asciify-image")}catch(e){}if(s)return function(){return s(t,{fit:"box",width:"".concat(Math.round(80*r),"%")}).then((function(e){return console.log(e)}))};return xw}({image:r,message:n,scale:a}):xw}))},{key:"settings",value:function(){console.table?console.table(this._storage.config):console.log(this._storage.config)}},{key:"get",value:function(e){return this._storage.config[e]}},{key:"set",value:function(e,t){this._storage.updateConfiguration(o({},e,t))}},{key:"time",value:function(e,t){return this._getLogFunction(e,t,console.time?console.time:console.info)}},{key:"timeEnd",value:function(e,t){return this._getLogFunction(e,t,console.timeEnd?console.timeEnd:console.info)}},{key:"timeStamp",value:function(e,t){return this._getLogFunction(e,t,console.timeStamp||xw)}},{key:"group",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{collapsed:!1},r=i=Ew({logLevel:e,message:t,opts:i}),s=r.collapsed;return i.method=(s?console.groupCollapsed:console.group)||console.info,this._getLogFunction(i)}},{key:"groupCollapsed",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.group(e,t,Object.assign({},i,{collapsed:!0}))}},{key:"groupEnd",value:function(e){return this._getLogFunction(e,"",console.groupEnd||xw)}},{key:"withGroup",value:function(e,t,i){this.group(e,t)();try{i()}finally{this.groupEnd(e)()}}},{key:"trace",value:function(){console.trace&&console.trace()}},{key:"_shouldLog",value:function(e){return this.isEnabled()&&this.getLevel()>=Mw(e)}},{key:"_getLogFunction",value:function(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],s=arguments.length>4?arguments[4]:void 0;if(this._shouldLog(e)){var n;s=Ew({logLevel:e,message:t,args:r,opts:s}),mw(i=i||s.method),s.total=this.getTotal(),s.delta=this.getDelta(),this._deltaTs=_w();var o=s.tag||s.message;if(s.once){if(ww[o])return xw;ww[o]=_w()}return t=Fw(this.id,s.message,s),(n=i).bind.apply(n,[console,t].concat(h(s.args)))}return xw}}]),e}();function Mw(e){if(!e)return 0;var t;switch(w(e)){case"number":t=e;break;case"object":t=e.logLevel||e.priority||0;break;default:return 0}return mw(Number.isFinite(t)&&t>=0),t}function Ew(e){var t=e.logLevel,i=e.message;e.logLevel=Mw(t);for(var r=e.args?Array.from(e.args):[];r.length&&r.shift()!==i;);switch(e.args=r,w(t)){case"string":case"function":void 0!==i&&r.unshift(i),e.message=t;break;case"object":Object.assign(e,t)}"function"==typeof e.message&&(e.message=e.message());var s=w(e.message);return mw("string"===s||"object"===s),Object.assign(e,e.opts)}function Fw(e,t,i){if("string"==typeof t){var r=i.time?function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8,i=Math.max(t-e.length,0);return"".concat(" ".repeat(i)).concat(e)}((s=i.total)<10?"".concat(s.toFixed(2),"ms"):s<100?"".concat(s.toFixed(1),"ms"):s<1e3?"".concat(s.toFixed(0),"ms"):"".concat((s/1e3).toFixed(2),"s")):"";t=function(e,t,i){return Aw||"string"!=typeof e||(t&&(t=vw(t),e="[".concat(t,"m").concat(e,"")),i&&(t=vw(i),e="[".concat(i+10,"m").concat(e,""))),e}(t=i.time?"".concat(e,": ").concat(r," ").concat(t):"".concat(e,": ").concat(t),i.color,i.background)}var s;return t}Cw.VERSION=cw;var kw=new Cw({id:"loaders.gl"}),Iw=function(){function e(){B(this,e)}return C(e,[{key:"log",value:function(){return function(){}}},{key:"info",value:function(){return function(){}}},{key:"warn",value:function(){return function(){}}},{key:"error",value:function(){return function(){}}}]),e}(),Dw={fetch:null,mimeType:void 0,nothrow:!1,log:new(function(){function e(){B(this,e),Xb(this,"console",void 0),this.console=console}return C(e,[{key:"log",value:function(){for(var e,t=arguments.length,i=new Array(t),r=0;r=0)}()}var zw={self:"undefined"!=typeof self&&self,window:"undefined"!=typeof window&&window,global:"undefined"!=typeof global&&global,document:"undefined"!=typeof document&&document,process:"object"===("undefined"==typeof process?"undefined":w(process))&&process},Ww=zw.window||zw.self||zw.global,Kw=zw.process||{},Xw="undefined"!=typeof __VERSION__?__VERSION__:"untranspiled source";function Jw(e){try{var t=window[e],i="__storage_test__";return t.setItem(i,i),t.removeItem(i),t}catch(e){return null}}Gw();var Yw,Zw=function(){function e(t){B(this,e);var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"sessionStorage";Xb(this,"storage",void 0),Xb(this,"id",void 0),Xb(this,"config",{}),this.storage=Jw(r),this.id=t,this.config={},Object.assign(this.config,i),this._loadConfiguration()}return C(e,[{key:"getConfiguration",value:function(){return this.config}},{key:"setConfiguration",value:function(e){return this.config={},this.updateConfiguration(e)}},{key:"updateConfiguration",value:function(e){if(Object.assign(this.config,e),this.storage){var t=JSON.stringify(this.config);this.storage.setItem(this.id,t)}return this}},{key:"_loadConfiguration",value:function(){var e={};if(this.storage){var t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}}]),e}();function qw(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:600,s=e.src.replace(/\(/g,"%28").replace(/\)/g,"%29");e.width>r&&(i=Math.min(i,r/e.width));var n=e.width*i,o=e.height*i,a=["font-size:1px;","padding:".concat(Math.floor(o/2),"px ").concat(Math.floor(n/2),"px;"),"line-height:".concat(o,"px;"),"background:url(".concat(s,");"),"background-size:".concat(n,"px ").concat(o,"px;"),"color:transparent;"].join("");return["".concat(t," %c+"),a]}function $w(e){return"string"==typeof e?Yw[e.toUpperCase()]||Yw.WHITE:e}function eB(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:["constructor"],r=Object.getPrototypeOf(e),s=Object.getOwnPropertyNames(r),n=c(s);try{var o=function(){var r=t.value;"function"==typeof e[r]&&(i.find((function(e){return r===e}))||(e[r]=e[r].bind(e)))};for(n.s();!(t=n.n()).done;)o()}catch(e){n.e(e)}finally{n.f()}}function tB(e,t){if(!e)throw new Error(t||"Assertion failed")}function iB(){var e,t,i;if(Gw&&"performance"in Ww)e=null==Ww||null===(t=Ww.performance)||void 0===t||null===(i=t.now)||void 0===i?void 0:i.call(t);else if("hrtime"in Kw){var r,s=null==Kw||null===(r=Kw.hrtime)||void 0===r?void 0:r.call(Kw);e=1e3*s[0]+s[1]/1e6}else e=Date.now();return e}!function(e){e[e.BLACK=30]="BLACK",e[e.RED=31]="RED",e[e.GREEN=32]="GREEN",e[e.YELLOW=33]="YELLOW",e[e.BLUE=34]="BLUE",e[e.MAGENTA=35]="MAGENTA",e[e.CYAN=36]="CYAN",e[e.WHITE=37]="WHITE",e[e.BRIGHT_BLACK=90]="BRIGHT_BLACK",e[e.BRIGHT_RED=91]="BRIGHT_RED",e[e.BRIGHT_GREEN=92]="BRIGHT_GREEN",e[e.BRIGHT_YELLOW=93]="BRIGHT_YELLOW",e[e.BRIGHT_BLUE=94]="BRIGHT_BLUE",e[e.BRIGHT_MAGENTA=95]="BRIGHT_MAGENTA",e[e.BRIGHT_CYAN=96]="BRIGHT_CYAN",e[e.BRIGHT_WHITE=97]="BRIGHT_WHITE"}(Yw||(Yw={}));var rB={debug:Gw&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},sB={enabled:!0,level:0};function nB(){}var oB={},aB={once:!0},lB=function(){function e(){B(this,e);var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{id:""},i=t.id;Xb(this,"id",void 0),Xb(this,"VERSION",Xw),Xb(this,"_startTs",iB()),Xb(this,"_deltaTs",iB()),Xb(this,"_storage",void 0),Xb(this,"userData",{}),Xb(this,"LOG_THROTTLE_TIMEOUT",0),this.id=i,this._storage=new Zw("__probe-".concat(this.id,"__"),sB),this.userData={},this.timeStamp("".concat(this.id," started")),eB(this),Object.seal(this)}return C(e,[{key:"level",get:function(){return this.getLevel()},set:function(e){this.setLevel(e)}},{key:"isEnabled",value:function(){return this._storage.config.enabled}},{key:"getLevel",value:function(){return this._storage.config.level}},{key:"getTotal",value:function(){return Number((iB()-this._startTs).toPrecision(10))}},{key:"getDelta",value:function(){return Number((iB()-this._deltaTs).toPrecision(10))}},{key:"priority",get:function(){return this.level},set:function(e){this.level=e}},{key:"getPriority",value:function(){return this.level}},{key:"enable",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this._storage.updateConfiguration({enabled:e}),this}},{key:"setLevel",value:function(e){return this._storage.updateConfiguration({level:e}),this}},{key:"get",value:function(e){return this._storage.config[e]}},{key:"set",value:function(e,t){this._storage.updateConfiguration(o({},e,t))}},{key:"settings",value:function(){console.table?console.table(this._storage.config):console.log(this._storage.config)}},{key:"assert",value:function(e,t){tB(e,t)}},{key:"warn",value:function(e){return this._getLogFunction(0,e,rB.warn,arguments,aB)}},{key:"error",value:function(e){return this._getLogFunction(0,e,rB.error,arguments)}},{key:"deprecated",value:function(e,t){return this.warn("`".concat(e,"` is deprecated and will be removed in a later version. Use `").concat(t,"` instead"))}},{key:"removed",value:function(e,t){return this.error("`".concat(e,"` has been removed. Use `").concat(t,"` instead"))}},{key:"probe",value:function(e,t){return this._getLogFunction(e,t,rB.log,arguments,{time:!0,once:!0})}},{key:"log",value:function(e,t){return this._getLogFunction(e,t,rB.debug,arguments)}},{key:"info",value:function(e,t){return this._getLogFunction(e,t,console.info,arguments)}},{key:"once",value:function(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),s=2;s2&&void 0!==arguments[2]?arguments[2]:{collapsed:!1},r=cB({logLevel:e,message:t,opts:i}),s=i.collapsed;return r.method=(s?console.groupCollapsed:console.group)||console.info,this._getLogFunction(r)}},{key:"groupCollapsed",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.group(e,t,Object.assign({},i,{collapsed:!0}))}},{key:"groupEnd",value:function(e){return this._getLogFunction(e,"",console.groupEnd||nB)}},{key:"withGroup",value:function(e,t,i){this.group(e,t)();try{i()}finally{this.groupEnd(e)()}}},{key:"trace",value:function(){console.trace&&console.trace()}},{key:"_shouldLog",value:function(e){return this.isEnabled()&&this.getLevel()>=uB(e)}},{key:"_getLogFunction",value:function(e,t,i,r,s){if(this._shouldLog(e)){var n;s=cB({logLevel:e,message:t,args:r,opts:s}),tB(i=i||s.method),s.total=this.getTotal(),s.delta=this.getDelta(),this._deltaTs=iB();var o=s.tag||s.message;if(s.once){if(oB[o])return nB;oB[o]=iB()}return t=function(e,t,i){if("string"==typeof t){var r=i.time?function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8,i=Math.max(t-e.length,0);return"".concat(" ".repeat(i)).concat(e)}((s=i.total)<10?"".concat(s.toFixed(2),"ms"):s<100?"".concat(s.toFixed(1),"ms"):s<1e3?"".concat(s.toFixed(0),"ms"):"".concat((s/1e3).toFixed(2),"s")):"";t=function(e,t,i){return Gw||"string"!=typeof e||(t&&(t=$w(t),e="[".concat(t,"m").concat(e,"")),i&&(t=$w(i),e="[".concat(i+10,"m").concat(e,""))),e}(t=i.time?"".concat(e,": ").concat(r," ").concat(t):"".concat(e,": ").concat(t),i.color,i.background)}var s;return t}(this.id,s.message,s),(n=i).bind.apply(n,[console,t].concat(h(s.args)))}return nB}}]),e}();function uB(e){if(!e)return 0;var t;switch(w(e)){case"number":t=e;break;case"object":t=e.logLevel||e.priority||0;break;default:return 0}return tB(Number.isFinite(t)&&t>=0),t}function cB(e){var t=e.logLevel,i=e.message;e.logLevel=uB(t);for(var r=e.args?Array.from(e.args):[];r.length&&r.shift()!==i;);switch(w(t)){case"string":case"function":void 0!==i&&r.unshift(i),e.message=t;break;case"object":Object.assign(e,t)}"function"==typeof e.message&&(e.message=e.message());var s=w(e.message);return tB("string"===s||"object"===s),Object.assign(e,{args:r},e.opts)}function AB(e){for(var t in e)for(var i in e[t])return i||"untitled";return"empty"}Xb(lB,"VERSION",Xw);var hB=new lB({id:"loaders.gl"}),dB=/\.([^.]+)$/;function pB(e){return fB.apply(this,arguments)}function fB(){return fB=u(a().mark((function e(t){var i,r,s,o,l=arguments;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=l.length>1&&void 0!==l[1]?l[1]:[],r=l.length>2?l[2]:void 0,s=l.length>3?l[3]:void 0,mB(t)){e.next=5;break}return e.abrupt("return",null);case 5:if(!(o=vB(t,i,n(n({},r),{},{nothrow:!0}),s))){e.next=8;break}return e.abrupt("return",o);case 8:if(!Qx(t)){e.next=13;break}return e.next=11,t.slice(0,10).arrayBuffer();case 11:t=e.sent,o=vB(t,i,r,s);case 13:if(o||null!=r&&r.nothrow){e.next=15;break}throw new Error(_B(t));case 15:return e.abrupt("return",o);case 16:case"end":return e.stop()}}),e)}))),fB.apply(this,arguments)}function vB(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],i=arguments.length>2?arguments[2]:void 0,r=arguments.length>3?arguments[3]:void 0;if(!mB(e))return null;if(t&&!Array.isArray(t))return Hw(t);var s,n=[];(t&&(n=n.concat(t)),null!=i&&i.ignoreRegisteredLoaders)||(s=n).push.apply(s,h(jw()));yB(n);var o=gB(e,n,i,r);if(!(o||null!=i&&i.nothrow))throw new Error(_B(e));return o}function gB(e,t,i,r){var s,n=Kx(e),o=n.url,a=n.type,l=o||(null==r?void 0:r.url),u=null,A="";(null!=i&&i.mimeType&&(u=bB(t,null==i?void 0:i.mimeType),A="match forced by supplied MIME type ".concat(null==i?void 0:i.mimeType)),u=u||function(e,t){var i=t&&dB.exec(t),r=i&&i[1];return r?function(e,t){t=t.toLowerCase();var i,r=c(e);try{for(r.s();!(i=r.n()).done;){var s,n=i.value,o=c(n.extensions);try{for(o.s();!(s=o.n()).done;){if(s.value.toLowerCase()===t)return n}}catch(e){o.e(e)}finally{o.f()}}}catch(e){r.e(e)}finally{r.f()}return null}(e,r):null}(t,l),A=A||(u?"matched url ".concat(l):""),u=u||bB(t,a),A=A||(u?"matched MIME type ".concat(a):""),u=u||function(e,t){if(!t)return null;var i,r=c(e);try{for(r.s();!(i=r.n()).done;){var s=i.value;if("string"==typeof t){if(xB(t,s))return s}else if(ArrayBuffer.isView(t)){if(wB(t.buffer,t.byteOffset,s))return s}else if(t instanceof ArrayBuffer){if(wB(t,0,s))return s}}}catch(e){r.e(e)}finally{r.f()}return null}(t,e),A=A||(u?"matched initial data ".concat(BB(e)):""),u=u||bB(t,null==i?void 0:i.fallbackMimeType),A=A||(u?"matched fallback MIME type ".concat(a):""))&&hB.log(1,"selectLoader selected ".concat(null===(s=u)||void 0===s?void 0:s.name,": ").concat(A,"."));return u}function mB(e){return!(e instanceof Response&&204===e.status)}function _B(e){var t=Kx(e),i=t.url,r=t.type,s="No valid loader found (";s+=i?"".concat(function(e){var t=e&&e.lastIndexOf("/");return t>=0?e.substr(t+1):""}(i),", "):"no url provided, ",s+="MIME type: ".concat(r?'"'.concat(r,'"'):"not provided",", ");var n=e?BB(e):"";return s+=n?' first bytes: "'.concat(n,'"'):"first bytes: not available",s+=")"}function yB(e){var t,i=c(e);try{for(i.s();!(t=i.n()).done;){Hw(t.value)}}catch(e){i.e(e)}finally{i.f()}}function bB(e,t){var i,r=c(e);try{for(r.s();!(i=r.n()).done;){var s=i.value;if(s.mimeTypes&&s.mimeTypes.includes(t))return s;if(t==="application/x.".concat(s.id))return s}}catch(e){r.e(e)}finally{r.f()}return null}function xB(e,t){return t.testText?t.testText(e):(Array.isArray(t.tests)?t.tests:[t.tests]).some((function(t){return e.startsWith(t)}))}function wB(e,t,i){return(Array.isArray(i.tests)?i.tests:[i.tests]).some((function(r){return function(e,t,i,r){if(r instanceof ArrayBuffer)return function(e,t,i){if(i=i||e.byteLength,e.byteLength1&&void 0!==arguments[1]?arguments[1]:5;if("string"==typeof e)return e.slice(0,t);if(ArrayBuffer.isView(e))return PB(e.buffer,e.byteOffset,t);if(e instanceof ArrayBuffer){var i=0;return PB(e,i,t)}return""}function PB(e,t,i){if(e.byteLength1&&void 0!==c[1]?c[1]:{},r=t.chunkSize,s=void 0===r?262144:r,n=0;case 3:if(!(n2&&void 0!==arguments[2]?arguments[2]:null;if(i)return i;var r=n({fetch:Uw(t,e)},e);return Array.isArray(r.loaders)||(r.loaders=null),r}function OB(e,t){if(!t&&e&&!Array.isArray(e))return e;var i;if(e&&(i=Array.isArray(e)?e:[e]),t&&t.loaders){var r=Array.isArray(t.loaders)?t.loaders:[t.loaders];i=i?[].concat(h(i),h(r)):r}return i&&i.length?i:null}function NB(e,t,i,r){return QB.apply(this,arguments)}function QB(){return(QB=u(a().mark((function e(t,i,r,s){var n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return Vb(!s||"object"===w(s)),!i||Array.isArray(i)||Vw(i)||(s=void 0,r=i,i=void 0),e.next=4,t;case 4:return t=e.sent,r=r||{},n=Kx(t),o=n.url,l=OB(i,s),e.next=11,pB(t,l,r);case 11:if(u=e.sent){e.next=14;break}return e.abrupt("return",null);case 14:return r=Rw(r,u,l,o),s=UB({url:o,parse:NB,loaders:l},r,s),e.next=18,VB(u,t,r,s);case 18:return e.abrupt("return",e.sent);case 19:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function VB(e,t,i,r){return HB.apply(this,arguments)}function HB(){return(HB=u(a().mark((function e(t,i,r,s){var n,o,l,u,c,A,h,d;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return lx(t),Nx(i)&&(o=(n=i).ok,l=n.redirected,u=n.status,c=n.statusText,A=n.type,h=n.url,d=Object.fromEntries(n.headers.entries()),s.response={headers:d,ok:o,redirected:l,status:u,statusText:c,type:A,url:h}),e.next=4,LB(i,t,r);case 4:if(i=e.sent,!t.parseTextSync||"string"!=typeof i){e.next=8;break}return r.dataType="text",e.abrupt("return",t.parseTextSync(i,r,s,t));case 8:if(!gx(t,r)){e.next=12;break}return e.next=11,mx(t,i,r,s,NB);case 11:case 15:case 19:return e.abrupt("return",e.sent);case 12:if(!t.parseText||"string"!=typeof i){e.next=16;break}return e.next=15,t.parseText(i,r,s,t);case 16:if(!t.parse){e.next=20;break}return e.next=19,t.parse(i,r,s,t);case 20:throw Vb(!t.parseSync),new Error("".concat(t.id," loader - no parser found and worker is disabled"));case 22:case"end":return e.stop()}}),e)})))).apply(this,arguments)}var jB,GB,zB="https://unpkg.com/@loaders.gl/textures@".concat("3.2.6","/dist/libs/basis_encoder.wasm"),WB="https://unpkg.com/@loaders.gl/textures@".concat("3.2.6","/dist/libs/basis_encoder.js");function KB(e){return XB.apply(this,arguments)}function XB(){return(XB=u(a().mark((function e(t){var i;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(i=t.modules||{}).basis){e.next=3;break}return e.abrupt("return",i.basis);case 3:return jB=jB||JB(t),e.next=6,jB;case 6:return e.abrupt("return",e.sent);case 7:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function JB(e){return YB.apply(this,arguments)}function YB(){return(YB=u(a().mark((function e(t){var i,r,s,n;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=null,r=null,e.t0=Promise,e.next=5,Ax("basis_transcoder.js","textures",t);case 5:return e.t1=e.sent,e.next=8,Ax("basis_transcoder.wasm","textures",t);case 8:return e.t2=e.sent,e.t3=[e.t1,e.t2],e.next=12,e.t0.all.call(e.t0,e.t3);case 12:return s=e.sent,n=A(s,2),i=n[0],r=n[1],i=i||globalThis.BASIS,e.next=19,ZB(i,r);case 19:return e.abrupt("return",e.sent);case 20:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ZB(e,t){var i={};return t&&(i.wasmBinary=t),new Promise((function(t){e(i).then((function(e){var i=e.BasisFile;(0,e.initializeBasis)(),t({BasisFile:i})}))}))}function qB(e){return $B.apply(this,arguments)}function $B(){return($B=u(a().mark((function e(t){var i;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(i=t.modules||{}).basisEncoder){e.next=3;break}return e.abrupt("return",i.basisEncoder);case 3:return GB=GB||eP(t),e.next=6,GB;case 6:return e.abrupt("return",e.sent);case 7:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function eP(e){return tP.apply(this,arguments)}function tP(){return(tP=u(a().mark((function e(t){var i,r,s,n;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=null,r=null,e.t0=Promise,e.next=5,Ax(WB,"textures",t);case 5:return e.t1=e.sent,e.next=8,Ax(zB,"textures",t);case 8:return e.t2=e.sent,e.t3=[e.t1,e.t2],e.next=12,e.t0.all.call(e.t0,e.t3);case 12:return s=e.sent,n=A(s,2),i=n[0],r=n[1],i=i||globalThis.BASIS,e.next=19,iP(i,r);case 19:return e.abrupt("return",e.sent);case 20:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function iP(e,t){var i={};return t&&(i.wasmBinary=t),new Promise((function(t){e(i).then((function(e){var i=e.BasisFile,r=e.KTX2File,s=e.initializeBasis,n=e.BasisEncoder;s(),t({BasisFile:i,KTX2File:r,BasisEncoder:n})}))}))}var rP,sP,nP,oP,aP,lP,uP,cP,AP,hP=33776,dP=33779,pP=35840,fP=35842,vP=36196,gP=37808,mP=["","WEBKIT_","MOZ_"],_P={WEBGL_compressed_texture_s3tc:"dxt",WEBGL_compressed_texture_s3tc_srgb:"dxt-srgb",WEBGL_compressed_texture_etc1:"etc1",WEBGL_compressed_texture_etc:"etc2",WEBGL_compressed_texture_pvrtc:"pvrtc",WEBGL_compressed_texture_atc:"atc",WEBGL_compressed_texture_astc:"astc",EXT_texture_compression_rgtc:"rgtc"},yP=null;function bP(e){if(!yP){e=e||function(){try{return document.createElement("canvas").getContext("webgl")}catch(e){return null}}()||void 0,yP=new Set;var t,i=c(mP);try{for(i.s();!(t=i.n()).done;){var r=t.value;for(var s in _P)if(e&&e.getExtension("".concat(r).concat(s))){var n=_P[s];yP.add(n)}}}catch(e){i.e(e)}finally{i.f()}}return yP}(AP=rP||(rP={}))[AP.NONE=0]="NONE",AP[AP.BASISLZ=1]="BASISLZ",AP[AP.ZSTD=2]="ZSTD",AP[AP.ZLIB=3]="ZLIB",function(e){e[e.BASICFORMAT=0]="BASICFORMAT"}(sP||(sP={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.ETC1S=163]="ETC1S",e[e.UASTC=166]="UASTC"}(nP||(nP={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.SRGB=1]="SRGB"}(oP||(oP={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.LINEAR=1]="LINEAR",e[e.SRGB=2]="SRGB",e[e.ITU=3]="ITU",e[e.NTSC=4]="NTSC",e[e.SLOG=5]="SLOG",e[e.SLOG2=6]="SLOG2"}(aP||(aP={})),function(e){e[e.ALPHA_STRAIGHT=0]="ALPHA_STRAIGHT",e[e.ALPHA_PREMULTIPLIED=1]="ALPHA_PREMULTIPLIED"}(lP||(lP={})),function(e){e[e.RGB=0]="RGB",e[e.RRR=3]="RRR",e[e.GGG=4]="GGG",e[e.AAA=15]="AAA"}(uP||(uP={})),function(e){e[e.RGB=0]="RGB",e[e.RGBA=3]="RGBA",e[e.RRR=4]="RRR",e[e.RRRG=5]="RRRG"}(cP||(cP={}));var xP=[171,75,84,88,32,50,48,187,13,10,26,10];function wP(e){var t=new Uint8Array(e);return!(t.byteLength1&&void 0!==r[1]?r[1]:null)&&YP||(i=null),!i){e.next=13;break}return e.prev=3,e.next=6,createImageBitmap(t,i);case 6:return e.abrupt("return",e.sent);case 9:e.prev=9,e.t0=e.catch(3),console.warn(e.t0),YP=!1;case 13:return e.next=15,createImageBitmap(t);case 15:return e.abrupt("return",e.sent);case 16:case"end":return e.stop()}}),e,null,[[3,9]])}))),eC.apply(this,arguments)}function tC(e){for(var t in e||JP)return!1;return!0}function iC(e){var t=rC(e);return function(e){var t=rC(e);if(!(t.byteLength>=24&&2303741511===t.getUint32(0,false)))return null;return{mimeType:"image/png",width:t.getUint32(16,false),height:t.getUint32(20,false)}}(t)||function(e){var t=rC(e);if(!(t.byteLength>=3&&65496===t.getUint16(0,false)&&255===t.getUint8(2)))return null;var i=function(){for(var e=new Set([65499,65476,65484,65501,65534]),t=65504;t<65520;++t)e.add(t);var i=new Set([65472,65473,65474,65475,65477,65478,65479,65481,65482,65483,65485,65486,65487,65502]);return{tableMarkers:e,sofMarkers:i}}(),r=i.tableMarkers,s=i.sofMarkers,n=2;for(;n+9=10&&1195984440===t.getUint32(0,false)))return null;return{mimeType:"image/gif",width:t.getUint16(6,true),height:t.getUint16(8,true)}}(t)||function(e){var t=rC(e);if(!(t.byteLength>=14&&16973===t.getUint16(0,false)&&t.getUint32(2,true)===t.byteLength))return null;return{mimeType:"image/bmp",width:t.getUint32(18,true),height:t.getUint32(22,true)}}(t)}function rC(e){if(e instanceof DataView)return e;if(ArrayBuffer.isView(e))return new DataView(e.buffer);if(e instanceof ArrayBuffer)return new DataView(e);throw new Error("toDataView")}function sC(e,t){return nC.apply(this,arguments)}function nC(){return nC=u(a().mark((function e(t,i){var r,s,n;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=iC(t)||{},s=r.mimeType,Ob(n=globalThis._parseImageNode),e.next=5,n(t,s);case 5:return e.abrupt("return",e.sent);case 6:case"end":return e.stop()}}),e)}))),nC.apply(this,arguments)}function oC(){return(oC=u(a().mark((function e(t,i,r){var s,n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:s=(i=i||{}).image||{},n=s.type||"auto",o=(r||{}).url,l=aC(n),e.t0=l,e.next="imagebitmap"===e.t0?8:"image"===e.t0?12:"data"===e.t0?16:20;break;case 8:return e.next=10,ZP(t,i,o);case 10:return u=e.sent,e.abrupt("break",21);case 12:return e.next=14,zP(t,i,o);case 14:return u=e.sent,e.abrupt("break",21);case 16:return e.next=18,sC(t);case 18:return u=e.sent,e.abrupt("break",21);case 20:Ob(!1);case 21:return"data"===n&&(u=NP(u)),e.abrupt("return",u);case 23:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function aC(e){switch(e){case"auto":case"data":return function(){if(LP)return"imagebitmap";if(TP)return"image";if(UP)return"data";throw new Error("Install '@loaders.gl/polyfills' to parse images under Node.js")}();default:return function(e){switch(e){case"auto":return LP||TP||UP;case"imagebitmap":return LP;case"image":return TP;case"data":return UP;default:throw new Error("@loaders.gl/images: image ".concat(e," not supported in this environment"))}}(e),e}}var lC={id:"image",module:"images",name:"Images",version:"3.2.6",mimeTypes:["image/png","image/jpeg","image/gif","image/webp","image/bmp","image/vnd.microsoft.icon","image/svg+xml"],extensions:["png","jpg","jpeg","gif","webp","bmp","ico","svg"],parse:function(e,t,i){return oC.apply(this,arguments)},tests:[function(e){return Boolean(iC(new DataView(e)))}],options:{image:{type:"auto",decode:!0}}},uC=["image/png","image/jpeg","image/gif"],cC={};function AC(e){return void 0===cC[e]&&(cC[e]=function(e){switch(e){case"image/webp":return function(){if(!Nb)return!1;try{return 0===document.createElement("canvas").toDataURL("image/webp").indexOf("data:image/webp")}catch(e){return!1}}();case"image/svg":return Nb;default:if(!Nb){var t=globalThis._parseImageNode;return Boolean(t)&&uC.includes(e)}return!0}}(e)),cC[e]}function hC(e,t){if(!e)throw new Error(t||"assert failed: gltf")}function dC(e,t){if(e.startsWith("data:")||e.startsWith("http:")||e.startsWith("https:"))return e;var i=t.baseUri||t.uri;if(!i)throw new Error("'baseUri' must be provided to resolve relative url ".concat(e));return i.substr(0,i.lastIndexOf("/")+1)+e}function pC(e,t,i){var r=e.bufferViews[i];hC(r);var s=t[r.buffer];hC(s);var n=(r.byteOffset||0)+s.byteOffset;return new Uint8Array(s.arrayBuffer,n,r.byteLength)}var fC=["SCALAR","VEC2","VEC3","VEC4"],vC=[[Int8Array,5120],[Uint8Array,5121],[Int16Array,5122],[Uint16Array,5123],[Uint32Array,5125],[Float32Array,5126],[Float64Array,5130]],gC=new Map(vC),mC={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},_C={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},yC={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array};function bC(e){return fC[e-1]||fC[0]}function xC(e){var t=gC.get(e.constructor);if(!t)throw new Error("Illegal typed array");return t}function wC(e,t){var i=yC[e.componentType],r=mC[e.type],s=_C[e.componentType],n=e.count*r,o=e.count*r*s;return hC(o>=0&&o<=t.byteLength),{ArrayType:i,length:n,byteLength:o}}var BC,PC={asset:{version:"2.0",generator:"loaders.gl"},buffers:[]},CC=function(){function e(t){B(this,e),Xb(this,"gltf",void 0),Xb(this,"sourceBuffers",void 0),Xb(this,"byteLength",void 0),this.gltf=t||{json:n({},PC),buffers:[]},this.sourceBuffers=[],this.byteLength=0,this.gltf.buffers&&this.gltf.buffers[0]&&(this.byteLength=this.gltf.buffers[0].byteLength,this.sourceBuffers=[this.gltf.buffers[0]])}return C(e,[{key:"json",get:function(){return this.gltf.json}},{key:"getApplicationData",value:function(e){return this.json[e]}},{key:"getExtraData",value:function(e){return(this.json.extras||{})[e]}},{key:"getExtension",value:function(e){var t=this.getUsedExtensions().find((function(t){return t===e})),i=this.json.extensions||{};return t?i[e]||!0:null}},{key:"getRequiredExtension",value:function(e){var t=this.getRequiredExtensions().find((function(t){return t===e}));return t?this.getExtension(e):null}},{key:"getRequiredExtensions",value:function(){return this.json.extensionsRequired||[]}},{key:"getUsedExtensions",value:function(){return this.json.extensionsUsed||[]}},{key:"getObjectExtension",value:function(e,t){return(e.extensions||{})[t]}},{key:"getScene",value:function(e){return this.getObject("scenes",e)}},{key:"getNode",value:function(e){return this.getObject("nodes",e)}},{key:"getSkin",value:function(e){return this.getObject("skins",e)}},{key:"getMesh",value:function(e){return this.getObject("meshes",e)}},{key:"getMaterial",value:function(e){return this.getObject("materials",e)}},{key:"getAccessor",value:function(e){return this.getObject("accessors",e)}},{key:"getTexture",value:function(e){return this.getObject("textures",e)}},{key:"getSampler",value:function(e){return this.getObject("samplers",e)}},{key:"getImage",value:function(e){return this.getObject("images",e)}},{key:"getBufferView",value:function(e){return this.getObject("bufferViews",e)}},{key:"getBuffer",value:function(e){return this.getObject("buffers",e)}},{key:"getObject",value:function(e,t){if("object"===w(t))return t;var i=this.json[e]&&this.json[e][t];if(!i)throw new Error("glTF file error: Could not find ".concat(e,"[").concat(t,"]"));return i}},{key:"getTypedArrayForBufferView",value:function(e){var t=(e=this.getBufferView(e)).buffer,i=this.gltf.buffers[t];hC(i);var r=(e.byteOffset||0)+i.byteOffset;return new Uint8Array(i.arrayBuffer,r,e.byteLength)}},{key:"getTypedArrayForAccessor",value:function(e){e=this.getAccessor(e);var t=this.getBufferView(e.bufferView),i=this.getBuffer(t.buffer).data,r=wC(e,t),s=r.ArrayType,n=r.length;return new s(i,t.byteOffset+e.byteOffset,n)}},{key:"getTypedArrayForImageData",value:function(e){e=this.getAccessor(e);var t=this.getBufferView(e.bufferView),i=this.getBuffer(t.buffer).data,r=t.byteOffset||0;return new Uint8Array(i,r,t.byteLength)}},{key:"addApplicationData",value:function(e,t){return this.json[e]=t,this}},{key:"addExtraData",value:function(e,t){return this.json.extras=this.json.extras||{},this.json.extras[e]=t,this}},{key:"addObjectExtension",value:function(e,t,i){return e.extensions=e.extensions||{},e.extensions[t]=i,this.registerUsedExtension(t),this}},{key:"setObjectExtension",value:function(e,t,i){(e.extensions||{})[t]=i}},{key:"removeObjectExtension",value:function(e,t){var i=e.extensions||{},r=i[t];return delete i[t],r}},{key:"addExtension",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return hC(t),this.json.extensions=this.json.extensions||{},this.json.extensions[e]=t,this.registerUsedExtension(e),t}},{key:"addRequiredExtension",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return hC(t),this.addExtension(e,t),this.registerRequiredExtension(e),t}},{key:"registerUsedExtension",value:function(e){this.json.extensionsUsed=this.json.extensionsUsed||[],this.json.extensionsUsed.find((function(t){return t===e}))||this.json.extensionsUsed.push(e)}},{key:"registerRequiredExtension",value:function(e){this.registerUsedExtension(e),this.json.extensionsRequired=this.json.extensionsRequired||[],this.json.extensionsRequired.find((function(t){return t===e}))||this.json.extensionsRequired.push(e)}},{key:"removeExtension",value:function(e){this.json.extensionsRequired&&this._removeStringFromArray(this.json.extensionsRequired,e),this.json.extensionsUsed&&this._removeStringFromArray(this.json.extensionsUsed,e),this.json.extensions&&delete this.json.extensions[e]}},{key:"setDefaultScene",value:function(e){this.json.scene=e}},{key:"addScene",value:function(e){var t=e.nodeIndices;return this.json.scenes=this.json.scenes||[],this.json.scenes.push({nodes:t}),this.json.scenes.length-1}},{key:"addNode",value:function(e){var t=e.meshIndex,i=e.matrix;this.json.nodes=this.json.nodes||[];var r={mesh:t};return i&&(r.matrix=i),this.json.nodes.push(r),this.json.nodes.length-1}},{key:"addMesh",value:function(e){var t=e.attributes,i=e.indices,r=e.material,s=e.mode,n=void 0===s?4:s,o={primitives:[{attributes:this._addAttributes(t),mode:n}]};if(i){var a=this._addIndices(i);o.primitives[0].indices=a}return Number.isFinite(r)&&(o.primitives[0].material=r),this.json.meshes=this.json.meshes||[],this.json.meshes.push(o),this.json.meshes.length-1}},{key:"addPointCloud",value:function(e){var t={primitives:[{attributes:this._addAttributes(e),mode:0}]};return this.json.meshes=this.json.meshes||[],this.json.meshes.push(t),this.json.meshes.length-1}},{key:"addImage",value:function(e,t){var i=iC(e),r=t||(null==i?void 0:i.mimeType),s={bufferView:this.addBufferView(e),mimeType:r};return this.json.images=this.json.images||[],this.json.images.push(s),this.json.images.length-1}},{key:"addBufferView",value:function(e){var t=e.byteLength;hC(Number.isFinite(t)),this.sourceBuffers=this.sourceBuffers||[],this.sourceBuffers.push(e);var i={buffer:0,byteOffset:this.byteLength,byteLength:t};return this.byteLength+=Ex(t,4),this.json.bufferViews=this.json.bufferViews||[],this.json.bufferViews.push(i),this.json.bufferViews.length-1}},{key:"addAccessor",value:function(e,t){var i={bufferView:e,type:bC(t.size),componentType:t.componentType,count:t.count,max:t.max,min:t.min};return this.json.accessors=this.json.accessors||[],this.json.accessors.push(i),this.json.accessors.length-1}},{key:"addBinaryBuffer",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{size:3},i=this.addBufferView(e),r={min:t.min,max:t.max};r.min&&r.max||(r=this._getAccessorMinMax(e,t.size));var s={size:t.size,componentType:xC(e),count:Math.round(e.length/t.size),min:r.min,max:r.max};return this.addAccessor(i,Object.assign(s,t))}},{key:"addTexture",value:function(e){var t={source:e.imageIndex};return this.json.textures=this.json.textures||[],this.json.textures.push(t),this.json.textures.length-1}},{key:"addMaterial",value:function(e){return this.json.materials=this.json.materials||[],this.json.materials.push(e),this.json.materials.length-1}},{key:"createBinaryChunk",value:function(){var e,t;this.gltf.buffers=[];var i,r=this.byteLength,s=new ArrayBuffer(r),n=new Uint8Array(s),o=0,a=c(this.sourceBuffers||[]);try{for(a.s();!(i=a.n()).done;){o=Fx(i.value,n,o)}}catch(e){a.e(e)}finally{a.f()}null!==(e=this.json)&&void 0!==e&&null!==(t=e.buffers)&&void 0!==t&&t[0]?this.json.buffers[0].byteLength=r:this.json.buffers=[{byteLength:r}],this.gltf.binary=s,this.sourceBuffers=[s]}},{key:"_removeStringFromArray",value:function(e,t){for(var i=!0;i;){var r=e.indexOf(t);r>-1?e.splice(r,1):i=!1}}},{key:"_addAttributes",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};for(var i in e){var r=e[i],s=this._getGltfAttributeName(i),n=this.addBinaryBuffer(r.value,r);t[s]=n}return t}},{key:"_addIndices",value:function(e){return this.addBinaryBuffer(e,{size:1})}},{key:"_getGltfAttributeName",value:function(e){switch(e.toLowerCase()){case"position":case"positions":case"vertices":return"POSITION";case"normal":case"normals":return"NORMAL";case"color":case"colors":return"COLOR_0";case"texcoord":case"texcoords":return"TEXCOORD_0";default:return e}}},{key:"_getAccessorMinMax",value:function(e,t){var i={min:null,max:null};if(e.length5&&void 0!==u[5]?u[5]:"NONE",e.next=3,LC();case 3:QC(l=e.sent,l.exports[DC[n]],t,i,r,s,l.exports[IC[o||"NONE"]]);case 5:case"end":return e.stop()}}),e)}))),TC.apply(this,arguments)}function LC(){return RC.apply(this,arguments)}function RC(){return(RC=u(a().mark((function e(){return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return BC||(BC=UC()),e.abrupt("return",BC);case 2:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function UC(){return OC.apply(this,arguments)}function OC(){return(OC=u(a().mark((function e(){var t,i;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=MC,WebAssembly.validate(FC)&&(t=EC,console.log("Warning: meshopt_decoder is using experimental SIMD support")),e.next=4,WebAssembly.instantiate(NC(t),{});case 4:return i=e.sent,e.next=7,i.instance.exports.__wasm_call_ctors();case 7:return e.abrupt("return",i.instance);case 8:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function NC(e){for(var t=new Uint8Array(e.length),i=0;i96?r-71:r>64?r-65:r>47?r+4:r>46?63:62}for(var s=0,n=0;ns?c:s,n=A>n?A:n,o=h>o?h:o}return[[t,i,r],[s,n,o]]}var JC=function(){function e(t,i){B(this,e),Xb(this,"fields",void 0),Xb(this,"metadata",void 0),function(e,t){if(!e)throw new Error(t||"loader assertion failed.")}(Array.isArray(t)),function(e){var t,i={},r=c(e);try{for(r.s();!(t=r.n()).done;){var s=t.value;i[s.name]&&console.warn("Schema: duplicated field name",s.name,s),i[s.name]=!0}}catch(e){r.e(e)}finally{r.f()}}(t),this.fields=t,this.metadata=i||new Map}return C(e,[{key:"compareTo",value:function(e){if(this.metadata!==e.metadata)return!1;if(this.fields.length!==e.fields.length)return!1;for(var t=0;t2&&void 0!==arguments[2]&&arguments[2],s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:new Map;B(this,e),Xb(this,"name",void 0),Xb(this,"type",void 0),Xb(this,"nullable",void 0),Xb(this,"metadata",void 0),this.name=t,this.type=i,this.nullable=r,this.metadata=s}return C(e,[{key:"typeId",get:function(){return this.type&&this.type.typeId}},{key:"clone",value:function(){return new e(this.name,this.type,this.nullable,this.metadata)}},{key:"compareTo",value:function(e){return this.name===e.name&&this.type===e.type&&this.nullable===e.nullable&&this.metadata===e.metadata}},{key:"toString",value:function(){return"".concat(this.type).concat(this.nullable?", nullable":"").concat(this.metadata?", metadata: ".concat(this.metadata):"")}}]),e}();!function(e){e[e.NONE=0]="NONE",e[e.Null=1]="Null",e[e.Int=2]="Int",e[e.Float=3]="Float",e[e.Binary=4]="Binary",e[e.Utf8=5]="Utf8",e[e.Bool=6]="Bool",e[e.Decimal=7]="Decimal",e[e.Date=8]="Date",e[e.Time=9]="Time",e[e.Timestamp=10]="Timestamp",e[e.Interval=11]="Interval",e[e.List=12]="List",e[e.Struct=13]="Struct",e[e.Union=14]="Union",e[e.FixedSizeBinary=15]="FixedSizeBinary",e[e.FixedSizeList=16]="FixedSizeList",e[e.Map=17]="Map",e[e.Dictionary=-1]="Dictionary",e[e.Int8=-2]="Int8",e[e.Int16=-3]="Int16",e[e.Int32=-4]="Int32",e[e.Int64=-5]="Int64",e[e.Uint8=-6]="Uint8",e[e.Uint16=-7]="Uint16",e[e.Uint32=-8]="Uint32",e[e.Uint64=-9]="Uint64",e[e.Float16=-10]="Float16",e[e.Float32=-11]="Float32",e[e.Float64=-12]="Float64",e[e.DateDay=-13]="DateDay",e[e.DateMillisecond=-14]="DateMillisecond",e[e.TimestampSecond=-15]="TimestampSecond",e[e.TimestampMillisecond=-16]="TimestampMillisecond",e[e.TimestampMicrosecond=-17]="TimestampMicrosecond",e[e.TimestampNanosecond=-18]="TimestampNanosecond",e[e.TimeSecond=-19]="TimeSecond",e[e.TimeMillisecond=-20]="TimeMillisecond",e[e.TimeMicrosecond=-21]="TimeMicrosecond",e[e.TimeNanosecond=-22]="TimeNanosecond",e[e.DenseUnion=-23]="DenseUnion",e[e.SparseUnion=-24]="SparseUnion",e[e.IntervalDayTime=-25]="IntervalDayTime",e[e.IntervalYearMonth=-26]="IntervalYearMonth"}(ZC||(ZC={}));var $C=function(){function e(){B(this,e)}return C(e,[{key:"typeId",get:function(){return ZC.NONE}},{key:"compareTo",value:function(e){return this===e}}],[{key:"isNull",value:function(e){return e&&e.typeId===ZC.Null}},{key:"isInt",value:function(e){return e&&e.typeId===ZC.Int}},{key:"isFloat",value:function(e){return e&&e.typeId===ZC.Float}},{key:"isBinary",value:function(e){return e&&e.typeId===ZC.Binary}},{key:"isUtf8",value:function(e){return e&&e.typeId===ZC.Utf8}},{key:"isBool",value:function(e){return e&&e.typeId===ZC.Bool}},{key:"isDecimal",value:function(e){return e&&e.typeId===ZC.Decimal}},{key:"isDate",value:function(e){return e&&e.typeId===ZC.Date}},{key:"isTime",value:function(e){return e&&e.typeId===ZC.Time}},{key:"isTimestamp",value:function(e){return e&&e.typeId===ZC.Timestamp}},{key:"isInterval",value:function(e){return e&&e.typeId===ZC.Interval}},{key:"isList",value:function(e){return e&&e.typeId===ZC.List}},{key:"isStruct",value:function(e){return e&&e.typeId===ZC.Struct}},{key:"isUnion",value:function(e){return e&&e.typeId===ZC.Union}},{key:"isFixedSizeBinary",value:function(e){return e&&e.typeId===ZC.FixedSizeBinary}},{key:"isFixedSizeList",value:function(e){return e&&e.typeId===ZC.FixedSizeList}},{key:"isMap",value:function(e){return e&&e.typeId===ZC.Map}},{key:"isDictionary",value:function(e){return e&&e.typeId===ZC.Dictionary}}]),e}(),eM=function(e,t){g(r,$C);var i=_(r);function r(e,t){var s;return B(this,r),Xb(b(s=i.call(this)),"isSigned",void 0),Xb(b(s),"bitWidth",void 0),s.isSigned=e,s.bitWidth=t,s}return C(r,[{key:"typeId",get:function(){return ZC.Int}},{key:t,get:function(){return"Int"}},{key:"toString",value:function(){return"".concat(this.isSigned?"I":"Ui","nt").concat(this.bitWidth)}}]),r}(0,Symbol.toStringTag),tM=function(e){g(i,eM);var t=_(i);function i(){return B(this,i),t.call(this,!0,8)}return C(i)}(),iM=function(e){g(i,eM);var t=_(i);function i(){return B(this,i),t.call(this,!0,16)}return C(i)}(),rM=function(e){g(i,eM);var t=_(i);function i(){return B(this,i),t.call(this,!0,32)}return C(i)}(),sM=function(e){g(i,eM);var t=_(i);function i(){return B(this,i),t.call(this,!1,8)}return C(i)}(),nM=function(e){g(i,eM);var t=_(i);function i(){return B(this,i),t.call(this,!1,16)}return C(i)}(),oM=function(e){g(i,eM);var t=_(i);function i(){return B(this,i),t.call(this,!1,32)}return C(i)}(),aM=32,lM=64,uM=function(e,t){g(r,$C);var i=_(r);function r(e){var t;return B(this,r),Xb(b(t=i.call(this)),"precision",void 0),t.precision=e,t}return C(r,[{key:"typeId",get:function(){return ZC.Float}},{key:t,get:function(){return"Float"}},{key:"toString",value:function(){return"Float".concat(this.precision)}}]),r}(0,Symbol.toStringTag),cM=function(e){g(i,uM);var t=_(i);function i(){return B(this,i),t.call(this,aM)}return C(i)}(),AM=function(e){g(i,uM);var t=_(i);function i(){return B(this,i),t.call(this,lM)}return C(i)}(),hM=function(e,t){g(r,$C);var i=_(r);function r(e,t){var s;return B(this,r),Xb(b(s=i.call(this)),"listSize",void 0),Xb(b(s),"children",void 0),s.listSize=e,s.children=[t],s}return C(r,[{key:"typeId",get:function(){return ZC.FixedSizeList}},{key:"valueType",get:function(){return this.children[0].type}},{key:"valueField",get:function(){return this.children[0]}},{key:t,get:function(){return"FixedSizeList"}},{key:"toString",value:function(){return"FixedSizeList[".concat(this.listSize,"]<").concat(this.valueType,">")}}]),r}(0,Symbol.toStringTag);function dM(e,t,i){var r=function(e){switch(e.constructor){case Int8Array:return new tM;case Uint8Array:return new sM;case Int16Array:return new iM;case Uint16Array:return new nM;case Int32Array:return new rM;case Uint32Array:return new oM;case Float32Array:return new cM;case Float64Array:return new AM;default:throw new Error("array type not supported")}}(t.value),s=i||function(e){var t=new Map;"byteOffset"in e&&t.set("byteOffset",e.byteOffset.toString(10));"byteStride"in e&&t.set("byteStride",e.byteStride.toString(10));"normalized"in e&&t.set("normalized",e.normalized.toString());return t}(t);return new qC(e,new hM(t.size,new qC("value",r)),!1,s)}function pM(e,t,i){var r=vM(t.metadata),s=[],n=function(e){var t={};for(var i in e){var r=e[i];t[r.name||"undefined"]=r}return t}(t.attributes);for(var o in e){var a=fM(o,e[o],n[o]);s.push(a)}if(i){var l=fM("indices",i);s.push(l)}return new JC(s,r)}function fM(e,t,i){return dM(e,t,i?vM(i.metadata):void 0)}function vM(e){var t=new Map;for(var i in e)t.set("".concat(i,".string"),JSON.stringify(e[i]));return t}var gM={POSITION:"POSITION",NORMAL:"NORMAL",COLOR:"COLOR_0",TEX_COORD:"TEXCOORD_0"},mM={1:Int8Array,2:Uint8Array,3:Int16Array,4:Uint16Array,5:Int32Array,6:Uint32Array,9:Float32Array},_M=function(){function e(t){B(this,e),Xb(this,"draco",void 0),Xb(this,"decoder",void 0),Xb(this,"metadataQuerier",void 0),this.draco=t,this.decoder=new this.draco.Decoder,this.metadataQuerier=new this.draco.MetadataQuerier}return C(e,[{key:"destroy",value:function(){this.draco.destroy(this.decoder),this.draco.destroy(this.metadataQuerier)}},{key:"parseSync",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=new this.draco.DecoderBuffer;i.Init(new Int8Array(e),e.byteLength),this._disableAttributeTransforms(t);var r=this.decoder.GetEncodedGeometryType(i),s=r===this.draco.TRIANGULAR_MESH?new this.draco.Mesh:new this.draco.PointCloud;try{var o;switch(r){case this.draco.TRIANGULAR_MESH:o=this.decoder.DecodeBufferToMesh(i,s);break;case this.draco.POINT_CLOUD:o=this.decoder.DecodeBufferToPointCloud(i,s);break;default:throw new Error("DRACO: Unknown geometry type.")}if(!o.ok()||!s.ptr){var a="DRACO decompression failed: ".concat(o.error_msg());throw new Error(a)}var l=this._getDracoLoaderData(s,r,t),u=this._getMeshData(s,l,t),c=XC(u.attributes),A=pM(u.attributes,l,u.indices),h=n(n({loader:"draco",loaderData:l,header:{vertexCount:s.num_points(),boundingBox:c}},u),{},{schema:A});return h}finally{this.draco.destroy(i),s&&this.draco.destroy(s)}}},{key:"_getDracoLoaderData",value:function(e,t,i){var r=this._getTopLevelMetadata(e),s=this._getDracoAttributes(e,i);return{geometry_type:t,num_attributes:e.num_attributes(),num_points:e.num_points(),num_faces:e instanceof this.draco.Mesh?e.num_faces():0,metadata:r,attributes:s}}},{key:"_getDracoAttributes",value:function(e,t){for(var i={},r=0;r2&&void 0!==arguments[2]&&arguments[2];if(!e)return null;if(Array.isArray(e))return new t(e);if(i&&!(e instanceof t))return new t(e);return e}(t,Float32Array)),r=t.length/i);return{buffer:t,size:i,count:r}}(e),i=t.buffer,r=t.size;return{value:i,size:r,byteOffset:0,count:t.count,type:bC(r),componentType:xC(i)}}function SM(){return(SM=u(a().mark((function e(t,i,r){var s,n,o,l,u,A;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(null!=i&&null!==(s=i.gltf)&&void 0!==s&&s.decompressMeshes){e.next=2;break}return e.abrupt("return");case 2:n=new CC(t),o=[],l=c(OM(n));try{for(l.s();!(u=l.n()).done;)A=u.value,n.getObjectExtension(A,"KHR_draco_mesh_compression")&&o.push(TM(n,A,i,r))}catch(e){l.e(e)}finally{l.f()}return e.next=8,Promise.all(o);case 8:n.removeExtension("KHR_draco_mesh_compression");case 9:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function TM(e,t,i,r){return LM.apply(this,arguments)}function LM(){return LM=u(a().mark((function e(t,i,r,s){var o,l,u,c,h,d,p,f,v,g,m,_,y,b;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(o=t.getObjectExtension(i,"KHR_draco_mesh_compression")){e.next=3;break}return e.abrupt("return");case 3:return l=t.getTypedArrayForBufferView(o.bufferView),u=Mx(l.buffer,l.byteOffset),c=s.parse,delete(h=n({},r))["3d-tiles"],e.next=10,c(u,FM,h,s);case 10:for(d=e.sent,p=IM(d.attributes),f=0,v=Object.entries(p);f2&&void 0!==arguments[2]?arguments[2]:4,s=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0;if(!s.DracoWriter)throw new Error("options.gltf.DracoWriter not provided");var a=s.DracoWriter.encodeSync({attributes:e}),l=null==n||null===(i=n.parseSync)||void 0===i?void 0:i.call(n,{attributes:e}),u=s._addFauxAttributes(l.attributes),c=s.addBufferView(a),A={primitives:[{attributes:u,mode:r,extensions:o({},"KHR_draco_mesh_compression",{bufferView:c,attributes:u})}]};return A}function UM(e){if(!e.attributes&&Object.keys(e.attributes).length>0)throw new Error("glTF: Empty primitive detected: Draco decompression failure?")}function OM(e){var t,i,s,n,o,l;return a().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:t=c(e.json.meshes||[]),r.prev=1,t.s();case 3:if((i=t.n()).done){r.next=24;break}s=i.value,n=c(s.primitives),r.prev=6,n.s();case 8:if((o=n.n()).done){r.next=14;break}return l=o.value,r.next=12,l;case 12:r.next=8;break;case 14:r.next=19;break;case 16:r.prev=16,r.t0=r.catch(6),n.e(r.t0);case 19:return r.prev=19,n.f(),r.finish(19);case 22:r.next=3;break;case 24:r.next=29;break;case 26:r.prev=26,r.t1=r.catch(1),t.e(r.t1);case 29:return r.prev=29,t.f(),r.finish(29);case 32:case"end":return r.stop()}}),r,null,[[1,26,29,32],[6,16,19,22]])}function NM(){return(NM=u(a().mark((function e(t){var i,r,s,n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=new CC(t),r=i.json,(s=i.getExtension("KHR_lights_punctual"))&&(i.json.lights=s.lights,i.removeExtension("KHR_lights_punctual")),n=c(r.nodes||[]);try{for(n.s();!(o=n.n()).done;)l=o.value,(u=i.getObjectExtension(l,"KHR_lights_punctual"))&&(l.light=u.light),i.removeObjectExtension(l,"KHR_lights_punctual")}catch(e){n.e(e)}finally{n.f()}case 6:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function QM(){return(QM=u(a().mark((function e(t){var i,r,s,n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=new CC(t),(r=i.json).lights&&(hC(!(s=i.addExtension("KHR_lights_punctual")).lights),s.lights=r.lights,delete r.lights),i.json.lights){n=c(i.json.lights);try{for(n.s();!(o=n.n()).done;)l=o.value,u=l.node,i.addObjectExtension(u,"KHR_lights_punctual",l)}catch(e){n.e(e)}finally{n.f()}delete i.json.lights}case 4:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function VM(){return(VM=u(a().mark((function e(t){var i,r,s,n,o;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=new CC(t),r=i.json,i.removeExtension("KHR_materials_unlit"),s=c(r.materials||[]);try{for(s.s();!(n=s.n()).done;)o=n.value,o.extensions&&o.extensions.KHR_materials_unlit&&(o.unlit=!0),i.removeObjectExtension(o,"KHR_materials_unlit")}catch(e){s.e(e)}finally{s.f()}case 5:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function HM(){return(HM=u(a().mark((function e(t){var i,r,s,n,o,l,u,A;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=new CC(t),r=i.json,s=i.getExtension("KHR_techniques_webgl")){n=GM(s,i),o=c(r.materials||[]);try{for(o.s();!(l=o.n()).done;)u=l.value,(A=i.getObjectExtension(u,"KHR_techniques_webgl"))&&(u.technique=Object.assign({},A,n[A.technique]),u.technique.values=zM(u.technique,i)),i.removeObjectExtension(u,"KHR_techniques_webgl")}catch(e){o.e(e)}finally{o.f()}i.removeExtension("KHR_techniques_webgl")}case 4:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function jM(){return(jM=u(a().mark((function e(t,i){return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function GM(e,t){var i=e.programs,r=void 0===i?[]:i,s=e.shaders,n=void 0===s?[]:s,o=e.techniques,a=void 0===o?[]:o,l=new TextDecoder;return n.forEach((function(e){if(!Number.isFinite(e.bufferView))throw new Error("KHR_techniques_webgl: no shader code");e.code=l.decode(t.getTypedArrayForBufferView(e.bufferView))})),r.forEach((function(e){e.fragmentShader=n[e.fragmentShader],e.vertexShader=n[e.vertexShader]})),a.forEach((function(e){e.program=r[e.program]})),a}function zM(e,t){var i=Object.assign({},e.values);return Object.keys(e.uniforms||{}).forEach((function(t){e.uniforms[t].value&&!(t in i)&&(i[t]=e.uniforms[t].value)})),Object.keys(i).forEach((function(e){"object"===w(i[e])&&void 0!==i[e].index&&(i[e].texture=t.getTexture(i[e].index))})),i}var WM=[GC,zC,WC,Object.freeze({__proto__:null,name:"KHR_draco_mesh_compression",preprocess:function(e,t,i){var r,s=new CC(e),n=c(OM(s));try{for(n.s();!(r=n.n()).done;){var o=r.value;s.getObjectExtension(o,"KHR_draco_mesh_compression")}}catch(e){n.e(e)}finally{n.f()}},decode:function(e,t,i){return SM.apply(this,arguments)},encode:function(e){var t,i=new CC(e),r=c(i.json.meshes||[]);try{for(r.s();!(t=r.n()).done;){var s=t.value;RM(s),i.addRequiredExtension("KHR_draco_mesh_compression")}}catch(e){r.e(e)}finally{r.f()}}}),Object.freeze({__proto__:null,name:"KHR_lights_punctual",decode:function(e){return NM.apply(this,arguments)},encode:function(e){return QM.apply(this,arguments)}}),Object.freeze({__proto__:null,name:"KHR_materials_unlit",decode:function(e){return VM.apply(this,arguments)},encode:function(e){var t=new CC(e),i=t.json;if(t.materials){var r,s=c(i.materials||[]);try{for(s.s();!(r=s.n()).done;){var n=r.value;n.unlit&&(delete n.unlit,t.addObjectExtension(n,"KHR_materials_unlit",{}),t.addExtension("KHR_materials_unlit"))}}catch(e){s.e(e)}finally{s.f()}}}}),Object.freeze({__proto__:null,name:"KHR_techniques_webgl",decode:function(e){return HM.apply(this,arguments)},encode:function(e,t){return jM.apply(this,arguments)}})];function KM(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0,s=WM.filter((function(e){return YM(e.name,i)})),n=c(s);try{for(n.s();!(t=n.n()).done;){var o,a=t.value;null===(o=a.preprocess)||void 0===o||o.call(a,e,i,r)}}catch(e){n.e(e)}finally{n.f()}}function XM(e){return JM.apply(this,arguments)}function JM(){return JM=u(a().mark((function e(t){var i,r,s,n,o,l,u,A=arguments;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=A.length>1&&void 0!==A[1]?A[1]:{},r=A.length>2?A[2]:void 0,s=WM.filter((function(e){return YM(e.name,i)})),n=c(s),e.prev=4,n.s();case 6:if((o=n.n()).done){e.next=12;break}return l=o.value,e.next=10,null===(u=l.decode)||void 0===u?void 0:u.call(l,t,i,r);case 10:e.next=6;break;case 12:e.next=17;break;case 14:e.prev=14,e.t0=e.catch(4),n.e(e.t0);case 17:return e.prev=17,n.f(),e.finish(17);case 20:case"end":return e.stop()}}),e,null,[[4,14,17,20]])}))),JM.apply(this,arguments)}function YM(e,t){var i,r=(null==t||null===(i=t.gltf)||void 0===i?void 0:i.excludeExtensions)||{};return!(e in r&&!r[e])}var ZM={accessors:"accessor",animations:"animation",buffers:"buffer",bufferViews:"bufferView",images:"image",materials:"material",meshes:"mesh",nodes:"node",samplers:"sampler",scenes:"scene",skins:"skin",textures:"texture"},qM={accessor:"accessors",animations:"animation",buffer:"buffers",bufferView:"bufferViews",image:"images",material:"materials",mesh:"meshes",node:"nodes",sampler:"samplers",scene:"scenes",skin:"skins",texture:"textures"},$M=function(){function e(){B(this,e),Xb(this,"idToIndexMap",{animations:{},accessors:{},buffers:{},bufferViews:{},images:{},materials:{},meshes:{},nodes:{},samplers:{},scenes:{},skins:{},textures:{}}),Xb(this,"json",void 0)}return C(e,[{key:"normalize",value:function(e,t){this.json=e.json;var i=e.json;switch(i.asset&&i.asset.version){case"2.0":return;case void 0:case"1.0":break;default:return void console.warn("glTF: Unknown version ".concat(i.asset.version))}if(!t.normalize)throw new Error("glTF v1 is not supported.");console.warn("Converting glTF v1 to glTF v2 format. This is experimental and may fail."),this._addAsset(i),this._convertTopLevelObjectsToArrays(i),function(e){var t,i=new CC(e),r=i.json,s=c(r.images||[]);try{for(s.s();!(t=s.n()).done;){var n=t.value,o=i.getObjectExtension(n,"KHR_binary_glTF");o&&Object.assign(n,o),i.removeObjectExtension(n,"KHR_binary_glTF")}}catch(e){s.e(e)}finally{s.f()}r.buffers&&r.buffers[0]&&delete r.buffers[0].uri,i.removeExtension("KHR_binary_glTF")}(e),this._convertObjectIdsToArrayIndices(i),this._updateObjects(i),this._updateMaterial(i)}},{key:"_addAsset",value:function(e){e.asset=e.asset||{},e.asset.version="2.0",e.asset.generator=e.asset.generator||"Normalized to glTF 2.0 by loaders.gl"}},{key:"_convertTopLevelObjectsToArrays",value:function(e){for(var t in ZM)this._convertTopLevelObjectToArray(e,t)}},{key:"_convertTopLevelObjectToArray",value:function(e,t){var i=e[t];if(i&&!Array.isArray(i))for(var r in e[t]=[],i){var s=i[r];s.id=s.id||r;var n=e[t].length;e[t].push(s),this.idToIndexMap[t][r]=n}}},{key:"_convertObjectIdsToArrayIndices",value:function(e){for(var t in ZM)this._convertIdsToIndices(e,t);"scene"in e&&(e.scene=this._convertIdToIndex(e.scene,"scene"));var i,r=c(e.textures);try{for(r.s();!(i=r.n()).done;){var s=i.value;this._convertTextureIds(s)}}catch(e){r.e(e)}finally{r.f()}var n,o=c(e.meshes);try{for(o.s();!(n=o.n()).done;){var a=n.value;this._convertMeshIds(a)}}catch(e){o.e(e)}finally{o.f()}var l,u=c(e.nodes);try{for(u.s();!(l=u.n()).done;){var A=l.value;this._convertNodeIds(A)}}catch(e){u.e(e)}finally{u.f()}var h,d=c(e.scenes);try{for(d.s();!(h=d.n()).done;){var p=h.value;this._convertSceneIds(p)}}catch(e){d.e(e)}finally{d.f()}}},{key:"_convertTextureIds",value:function(e){e.source&&(e.source=this._convertIdToIndex(e.source,"image"))}},{key:"_convertMeshIds",value:function(e){var t,i=c(e.primitives);try{for(i.s();!(t=i.n()).done;){var r=t.value,s=r.attributes,n=r.indices,o=r.material;for(var a in s)s[a]=this._convertIdToIndex(s[a],"accessor");n&&(r.indices=this._convertIdToIndex(n,"accessor")),o&&(r.material=this._convertIdToIndex(o,"material"))}}catch(e){i.e(e)}finally{i.f()}}},{key:"_convertNodeIds",value:function(e){var t=this;e.children&&(e.children=e.children.map((function(e){return t._convertIdToIndex(e,"node")}))),e.meshes&&(e.meshes=e.meshes.map((function(e){return t._convertIdToIndex(e,"mesh")})))}},{key:"_convertSceneIds",value:function(e){var t=this;e.nodes&&(e.nodes=e.nodes.map((function(e){return t._convertIdToIndex(e,"node")})))}},{key:"_convertIdsToIndices",value:function(e,t){e[t]||(console.warn("gltf v1: json doesn't contain attribute ".concat(t)),e[t]=[]);var i,r=c(e[t]);try{for(r.s();!(i=r.n()).done;){var s=i.value;for(var n in s){var o=s[n],a=this._convertIdToIndex(o,n);s[n]=a}}}catch(e){r.e(e)}finally{r.f()}}},{key:"_convertIdToIndex",value:function(e,t){var i=qM[t];if(i in this.idToIndexMap){var r=this.idToIndexMap[i][e];if(!Number.isFinite(r))throw new Error("gltf v1: failed to resolve ".concat(t," with id ").concat(e));return r}return e}},{key:"_updateObjects",value:function(e){var t,i=c(this.json.buffers);try{for(i.s();!(t=i.n()).done;){delete t.value.type}}catch(e){i.e(e)}finally{i.f()}}},{key:"_updateMaterial",value:function(e){var t,i=c(e.materials);try{var r=function(){var i=t.value;i.pbrMetallicRoughness={baseColorFactor:[1,1,1,1],metallicFactor:1,roughnessFactor:1};var r=(null===(s=i.values)||void 0===s?void 0:s.tex)||(null===(n=i.values)||void 0===n?void 0:n.texture2d_0),o=e.textures.findIndex((function(e){return e.id===r}));-1!==o&&(i.pbrMetallicRoughness.baseColorTexture={index:o})};for(i.s();!(t=i.n()).done;){var s,n;r()}}catch(e){i.e(e)}finally{i.f()}}}]),e}();function eE(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return(new $M).normalize(e,t)}var tE={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},iE={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},rE=10240,sE=10241,nE=10242,oE=10243,aE=10497,lE=9986,uE={magFilter:rE,minFilter:sE,wrapS:nE,wrapT:oE},cE=(o(e={},rE,9729),o(e,sE,lE),o(e,nE,aE),o(e,oE,aE),e);var AE=function(){function e(){B(this,e),Xb(this,"baseUri",""),Xb(this,"json",{}),Xb(this,"buffers",[]),Xb(this,"images",[])}return C(e,[{key:"postProcess",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=e.json,r=e.buffers,s=void 0===r?[]:r,n=e.images,o=void 0===n?[]:n,a=e.baseUri,l=void 0===a?"":a;return hC(i),this.baseUri=l,this.json=i,this.buffers=s,this.images=o,this._resolveTree(this.json,t),this.json}},{key:"_resolveTree",value:function(e){var t=this;e.bufferViews&&(e.bufferViews=e.bufferViews.map((function(e,i){return t._resolveBufferView(e,i)}))),e.images&&(e.images=e.images.map((function(e,i){return t._resolveImage(e,i)}))),e.samplers&&(e.samplers=e.samplers.map((function(e,i){return t._resolveSampler(e,i)}))),e.textures&&(e.textures=e.textures.map((function(e,i){return t._resolveTexture(e,i)}))),e.accessors&&(e.accessors=e.accessors.map((function(e,i){return t._resolveAccessor(e,i)}))),e.materials&&(e.materials=e.materials.map((function(e,i){return t._resolveMaterial(e,i)}))),e.meshes&&(e.meshes=e.meshes.map((function(e,i){return t._resolveMesh(e,i)}))),e.nodes&&(e.nodes=e.nodes.map((function(e,i){return t._resolveNode(e,i)}))),e.skins&&(e.skins=e.skins.map((function(e,i){return t._resolveSkin(e,i)}))),e.scenes&&(e.scenes=e.scenes.map((function(e,i){return t._resolveScene(e,i)}))),void 0!==e.scene&&(e.scene=e.scenes[this.json.scene])}},{key:"getScene",value:function(e){return this._get("scenes",e)}},{key:"getNode",value:function(e){return this._get("nodes",e)}},{key:"getSkin",value:function(e){return this._get("skins",e)}},{key:"getMesh",value:function(e){return this._get("meshes",e)}},{key:"getMaterial",value:function(e){return this._get("materials",e)}},{key:"getAccessor",value:function(e){return this._get("accessors",e)}},{key:"getCamera",value:function(e){return null}},{key:"getTexture",value:function(e){return this._get("textures",e)}},{key:"getSampler",value:function(e){return this._get("samplers",e)}},{key:"getImage",value:function(e){return this._get("images",e)}},{key:"getBufferView",value:function(e){return this._get("bufferViews",e)}},{key:"getBuffer",value:function(e){return this._get("buffers",e)}},{key:"_get",value:function(e,t){if("object"===w(t))return t;var i=this.json[e]&&this.json[e][t];return i||console.warn("glTF file error: Could not find ".concat(e,"[").concat(t,"]")),i}},{key:"_resolveScene",value:function(e,t){var i=this;return e.id=e.id||"scene-".concat(t),e.nodes=(e.nodes||[]).map((function(e){return i.getNode(e)})),e}},{key:"_resolveNode",value:function(e,t){var i=this;return e.id=e.id||"node-".concat(t),e.children&&(e.children=e.children.map((function(e){return i.getNode(e)}))),void 0!==e.mesh?e.mesh=this.getMesh(e.mesh):void 0!==e.meshes&&e.meshes.length&&(e.mesh=e.meshes.reduce((function(e,t){var r=i.getMesh(t);return e.id=r.id,e.primitives=e.primitives.concat(r.primitives),e}),{primitives:[]})),void 0!==e.camera&&(e.camera=this.getCamera(e.camera)),void 0!==e.skin&&(e.skin=this.getSkin(e.skin)),e}},{key:"_resolveSkin",value:function(e,t){return e.id=e.id||"skin-".concat(t),e.inverseBindMatrices=this.getAccessor(e.inverseBindMatrices),e}},{key:"_resolveMesh",value:function(e,t){var i=this;return e.id=e.id||"mesh-".concat(t),e.primitives&&(e.primitives=e.primitives.map((function(e){var t=(e=n({},e)).attributes;for(var r in e.attributes={},t)e.attributes[r]=i.getAccessor(t[r]);return void 0!==e.indices&&(e.indices=i.getAccessor(e.indices)),void 0!==e.material&&(e.material=i.getMaterial(e.material)),e}))),e}},{key:"_resolveMaterial",value:function(e,t){if(e.id=e.id||"material-".concat(t),e.normalTexture&&(e.normalTexture=n({},e.normalTexture),e.normalTexture.texture=this.getTexture(e.normalTexture.index)),e.occlusionTexture&&(e.occlustionTexture=n({},e.occlustionTexture),e.occlusionTexture.texture=this.getTexture(e.occlusionTexture.index)),e.emissiveTexture&&(e.emmisiveTexture=n({},e.emmisiveTexture),e.emissiveTexture.texture=this.getTexture(e.emissiveTexture.index)),e.emissiveFactor||(e.emissiveFactor=e.emmisiveTexture?[1,1,1]:[0,0,0]),e.pbrMetallicRoughness){e.pbrMetallicRoughness=n({},e.pbrMetallicRoughness);var i=e.pbrMetallicRoughness;i.baseColorTexture&&(i.baseColorTexture=n({},i.baseColorTexture),i.baseColorTexture.texture=this.getTexture(i.baseColorTexture.index)),i.metallicRoughnessTexture&&(i.metallicRoughnessTexture=n({},i.metallicRoughnessTexture),i.metallicRoughnessTexture.texture=this.getTexture(i.metallicRoughnessTexture.index))}return e}},{key:"_resolveAccessor",value:function(e,t){var i,r;if(e.id=e.id||"accessor-".concat(t),void 0!==e.bufferView&&(e.bufferView=this.getBufferView(e.bufferView)),e.bytesPerComponent=(i=e.componentType,iE[i]),e.components=(r=e.type,tE[r]),e.bytesPerElement=e.bytesPerComponent*e.components,e.bufferView){var s=e.bufferView.buffer,n=wC(e,e.bufferView),o=n.ArrayType,a=n.byteLength,l=(e.bufferView.byteOffset||0)+(e.byteOffset||0)+s.byteOffset,u=s.arrayBuffer.slice(l,l+a);e.bufferView.byteStride&&(u=this._getValueFromInterleavedBuffer(s,l,e.bufferView.byteStride,e.bytesPerElement,e.count)),e.value=new o(u)}return e}},{key:"_getValueFromInterleavedBuffer",value:function(e,t,i,r,s){for(var n=new Uint8Array(s*r),o=0;o1&&void 0!==arguments[1]?arguments[1]:0;return"".concat(String.fromCharCode(e.getUint8(t+0))).concat(String.fromCharCode(e.getUint8(t+1))).concat(String.fromCharCode(e.getUint8(t+2))).concat(String.fromCharCode(e.getUint8(t+3)))}function fE(e,t,i){Ob(e.header.byteLength>20);var r=t.getUint32(i+0,dE),s=t.getUint32(i+4,dE);return i+=8,Ob(0===s),gE(e,t,i,r),i+=r,i+=mE(e,t,i,e.header.byteLength)}function vE(e,t,i,r){return Ob(e.header.byteLength>20),function(e,t,i,r){for(;i+8<=e.header.byteLength;){var s=t.getUint32(i+0,dE),n=t.getUint32(i+4,dE);switch(i+=8,n){case 1313821514:gE(e,t,i,s);break;case 5130562:mE(e,t,i,s);break;case 0:r.strict||gE(e,t,i,s);break;case 1:r.strict||mE(e,t,i,s)}i+=Ex(s,4)}}(e,t,i,r),i+e.header.byteLength}function gE(e,t,i,r){var s=new Uint8Array(t.buffer,i,r),n=new TextDecoder("utf8").decode(s);return e.json=JSON.parse(n),Ex(r,4)}function mE(e,t,i,r){return e.header.hasBinChunk=!0,e.binChunks.push({byteOffset:i,byteLength:r,arrayBuffer:t.buffer}),Ex(r,4)}function _E(e,t){return yE.apply(this,arguments)}function yE(){return yE=u(a().mark((function e(t,i){var r,s,n,o,l,u,c,A,h,d,p=arguments;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=p.length>2&&void 0!==p[2]?p[2]:0,s=p.length>3?p[3]:void 0,n=p.length>4?p[4]:void 0,bE(t,i,r,s),eE(t,{normalize:null==s||null===(o=s.gltf)||void 0===o?void 0:o.normalize}),KM(t,s,n),A=[],null==s||null===(l=s.gltf)||void 0===l||!l.loadBuffers||!t.json.buffers){e.next=10;break}return e.next=10,xE(t,s,n);case 10:return null!=s&&null!==(u=s.gltf)&&void 0!==u&&u.loadImages&&(h=BE(t,s,n),A.push(h)),d=XM(t,s,n),A.push(d),e.next=15,Promise.all(A);case 15:return e.abrupt("return",null!=s&&null!==(c=s.gltf)&&void 0!==c&&c.postProcess?hE(t,s):t);case 16:case"end":return e.stop()}}),e)}))),yE.apply(this,arguments)}function bE(e,t,i,r){(r.uri&&(e.baseUri=r.uri),t instanceof ArrayBuffer&&!function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=new DataView(e),s=i.magic,n=void 0===s?1735152710:s,o=r.getUint32(t,!1);return o===n||1735152710===o}(t,i,r))&&(t=(new TextDecoder).decode(t));if("string"==typeof t)e.json=wx(t);else if(t instanceof ArrayBuffer){var s={};i=function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,r=new DataView(t),s=pE(r,i+0),n=r.getUint32(i+4,dE),o=r.getUint32(i+8,dE);switch(Object.assign(e,{header:{byteOffset:i,byteLength:o,hasBinChunk:!1},type:s,version:n,json:{},binChunks:[]}),i+=12,e.version){case 1:return fE(e,r,i);case 2:return vE(e,r,i,{});default:throw new Error("Invalid GLB version ".concat(e.version,". Only supports v1 and v2."))}}(s,t,i,r.glb),hC("glTF"===s.type,"Invalid GLB magic string ".concat(s.type)),e._glb=s,e.json=s.json}else hC(!1,"GLTF: must be ArrayBuffer or string");var n=e.json.buffers||[];if(e.buffers=new Array(n.length).fill(null),e._glb&&e._glb.header.hasBinChunk){var o=e._glb.binChunks;e.buffers[0]={arrayBuffer:o[0].arrayBuffer,byteOffset:o[0].byteOffset,byteLength:o[0].byteLength}}var a=e.json.images||[];e.images=new Array(a.length).fill({})}function xE(e,t,i){return wE.apply(this,arguments)}function wE(){return(wE=u(a().mark((function e(t,i,r){var s,n,o,l,u,c,A,h;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:s=t.json.buffers||[],n=0;case 2:if(!(n1&&void 0!==u[1]?u[1]:{},r=u.length>2?u[2]:void 0,(i=n(n({},FE.options),i)).gltf=n(n({},FE.options.gltf),i.gltf),s=i.byteOffset,o=void 0===s?0:s,l={},e.next=8,_E(l,t,o,i,r);case 8:return e.abrupt("return",e.sent);case 9:case"end":return e.stop()}}),e)}))),kE.apply(this,arguments)}var IE=function(){function e(t){B(this,e)}return C(e,[{key:"load",value:function(e,t,i,r,s,n,o){!function(e,t,i,r,s,n,o){var a=e.viewer.scene.canvas.spinner;a.processes++,"glb"===t.split(".").pop()?e.dataSource.getGLB(t,(function(o){r.basePath=DE(t),SE(e,t,o,i,r,s,n),a.processes--}),(function(e){a.processes--,o(e)})):e.dataSource.getGLTF(t,(function(o){r.basePath=DE(t),SE(e,t,o,i,r,s,n),a.processes--}),(function(e){a.processes--,o(e)}))}(e,t,i,r=r||{},s,(function(){we.scheduleTask((function(){s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1)})),n&&n()}),(function(t){e.error(t),o&&o(t),s.fire("error",t)}))}},{key:"parse",value:function(e,t,i,r,s,n,o){SE(e,"",t,i,r=r||{},s,(function(){s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1),n&&n()}))}}]),e}();function DE(e){var t=e.lastIndexOf("/");return 0!==t?e.substring(0,t+1):""}function SE(e,t,i,r,s,n,o){var a=e.viewer.scene.canvas.spinner;a.processes++,NB(i,FE,{baseUri:s.basePath}).then((function(i){var l={src:t,entityId:s.entityId,metaModelJSON:r,autoMetaModel:s.autoMetaModel,globalizeObjectIds:s.globalizeObjectIds,metaObjects:[],loadBuffer:s.loadBuffer,basePath:s.basePath,handlenode:s.handlenode,backfaces:!!s.backfaces,gltfData:i,scene:n.scene,plugin:e,sceneModel:n,numObjects:0,nodes:[],nextId:0,log:function(t){e.log(t)}};!function(e){var t=e.gltfData.textures;if(t)for(var i=0,r=t.length;i0)for(var o=0;o0){var c=e.globalizeObjectIds?re.globalizeObjectId(e.sceneModel.id,l):l;e.sceneModel.createEntity({id:c,meshIds:n,isObject:!0}),e.autoMetaModel&&e.metaObjects.push({id:c,type:"Default",name:c,parent:e.sceneModel.id})}n=s.pop()}}))}(r,0,null)}(l),n.finalize(),s.autoMetaModel&&e.viewer.metaScene.createMetaModel(n.id,{metaObjects:l.metaObjects}),a.processes--,o()}))}function TE(e,t){if(t.source&&t.source.image){var i="texture-".concat(e.nextId++),r=1005;switch(t.sampler.minFilter){case 9728:r=1003;break;case 9729:r=1006;break;case 9984:r=1004;break;case 9985:r=1007;break;case 9986:r=1005;break;case 9987:r=1008}var s=1006;switch(t.sampler.magFilter){case 9728:s=1003;break;case 9729:s=1006}var n=1e3;switch(t.sampler.wrapS){case 33071:n=1001;break;case 33648:n=1002;break;case 10497:n=1e3}var o=1e3;switch(t.sampler.wrapT){case 33071:o=1001;break;case 33648:o=1002;break;case 10497:o=1e3}var a=1e3;switch(t.sampler.wrapR){case 33071:a=1001;break;case 33648:a=1002;break;case 10497:a=1e3}e.sceneModel.createTexture({id:i,image:t.source.image,flipY:!!t.flipY,minFilter:r,magFilter:s,wrapS:n,wrapT:o,wrapR:a,encoding:3001}),t._textureId=i}}function LE(e,t){var i={};switch(t.normalTexture&&(i.normalTextureId=t.normalTexture.texture._textureId),t.occlusionTexture&&(i.occlusionTextureId=t.occlusionTexture.texture._textureId),t.emissiveTexture&&(i.emissiveTextureId=t.emissiveTexture.texture._textureId),t.alphaMode){case"OPAQUE":break;case"MASK":var r=t.alphaCutoff;i.alphaCutoff=void 0!==r?r:.5}var s=t.pbrMetallicRoughness;if(t.pbrMetallicRoughness){var n=t.pbrMetallicRoughness,o=n.baseColorTexture||n.colorTexture;o&&(o.texture?i.colorTextureId=o.texture._textureId:i.colorTextureId=e.gltfData.textures[o.index]._textureId),s.metallicRoughnessTexture&&(i.metallicRoughnessTextureId=s.metallicRoughnessTexture.texture._textureId)}var a=t.extensions;if(a){var l=a.KHR_materials_pbrSpecularGlossiness;if(l){l.specularTexture;var u=l.specularColorTexture;null!=u&&(i.colorTextureId=e.gltfData.textures[u.index]._textureId)}}return void 0!==i.normalTextureId||void 0!==i.occlusionTextureId||void 0!==i.emissiveTextureId||void 0!==i.colorTextureId||void 0!==i.metallicRoughnessTextureId?(i.id="textureSet-".concat(e.nextId++,";"),e.sceneModel.createTextureSet(i),i.id):null}function RE(e,t){var i=t.extensions,r={color:new Float32Array([1,1,1,1]),opacity:1,metallic:0,roughness:1,doubleSided:!0};if(i){var s=i.KHR_materials_pbrSpecularGlossiness;if(s){var n=s.diffuseFactor;null!=n&&r.color.set(n)}var o=i.KHR_materials_common;if(o){var a=o.technique,l=o.values||{},u="BLINN"===a,c="PHONG"===a,A="LAMBERT"===a,h=l.diffuse;h&&(u||c||A)&&(he.isString(h)||r.color.set(h));var d=l.transparency;null!=d&&(r.opacity=d);var p=l.transparent;null!=p&&(r.opacity=p)}}var f=t.pbrMetallicRoughness;if(f){var v=f.baseColorFactor;v&&(r.color[0]=v[0],r.color[1]=v[1],r.color[2]=v[2],r.opacity=v[3]);var g=f.metallicFactor;null!=g&&(r.metallic=g);var m=f.roughnessFactor;null!=m&&(r.roughness=m)}return r.doubleSided=!1!==t.doubleSided,r}var UE={DEFAULT:{}},OE=function(e){g(i,Ue);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),(r=t.call(this,"GLTFLoader",e,s))._sceneModelLoader=new IE(b(r),s),r.dataSource=s.dataSource,r.objectDefaults=s.objectDefaults,r}return C(i,[{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new Ad}},{key:"objectDefaults",get:function(){return this._objectDefaults},set:function(e){this._objectDefaults=e||UE}},{key:"load",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.id&&this.viewer.scene.components[t.id]&&(this.error("Component with this ID already exists in viewer: "+t.id+" - will autogenerate this ID"),delete t.id);var i=new Qh(this.viewer.scene,he.apply(t,{isModel:!0,dtxEnabled:t.dtxEnabled})),r=i.id;if(!t.src&&!t.gltf)return this.error("load() param expected: src or gltf"),i;if(t.metaModelSrc||t.metaModelJSON){var s=function(s){e.viewer.metaScene.createMetaModel(r,s,{}),e.viewer.scene.canvas.spinner.processes--,t.src?e._sceneModelLoader.load(e,t.src,s,t,i):e._sceneModelLoader.parse(e,t.gltf,s,t,i)};if(t.metaModelSrc){var n=t.metaModelSrc;this.viewer.scene.canvas.spinner.processes++,this._dataSource.getMetaModel(n,(function(t){e.viewer.scene.canvas.spinner.processes--,s(t)}),(function(t){e.error("load(): Failed to load model metadata for model '".concat(r," from '").concat(n,"' - ").concat(t)),e.viewer.scene.canvas.spinner.processes--}))}else t.metaModelJSON&&s(t.metaModelJSON)}else t.src?this._sceneModelLoader.load(this,t.src,null,t,i):this._sceneModelLoader.parse(this,t.gltf,null,t,i);return i.once("destroyed",(function(){e.viewer.metaScene.destroyMetaModel(r)})),i}},{key:"destroy",value:function(){f(x(i.prototype),"destroy",this).call(this)}}]),i}();function NE(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r="lightgrey",s=i.hoverColor||"rgba(0,0,0,0.4)",n=i.textColor||"black",o=500,a=o+o/3,l=a/24,u=[{boundary:[6,6,6,6],color:i.frontColor||i.color||"#55FF55"},{boundary:[18,6,6,6],color:i.backColor||i.color||"#55FF55"},{boundary:[12,6,6,6],color:i.rightColor||i.color||"#FF5555"},{boundary:[0,6,6,6],color:i.leftColor||i.color||"#FF5555"},{boundary:[6,0,6,6],color:i.topColor||i.color||"#7777FF"},{boundary:[6,12,6,6],color:i.bottomColor||i.color||"#7777FF"}],c=[{label:"NavCube.front",boundaries:[[7,7,4,4]],dir:[0,1,0],up:[0,0,1]},{label:"NavCube.back",boundaries:[[19,7,4,4]],dir:[0,-1,0],up:[0,0,1]},{label:"NavCube.right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,0,1]},{label:"NavCube.left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,0,1]},{label:"NavCube.top",boundaries:[[7,1,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"NavCube.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]}];i.frontColor||i.color,i.backColor||i.color,i.rightColor||i.color,i.leftColor||i.color,i.topColor||i.color,i.bottomColor||i.color;for(var A=[{yUp:"",label:"NavCube.front",boundaries:[[7,7,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"NavCube.back",boundaries:[[19,7,4,4]],dir:[0,0,1],up:[0,1,0]},{label:"NavCube.right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,1,0]},{label:"NavCube.left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,1,0]},{label:"NavCube.top",boundaries:[[7,1,4,4]],dir:[0,-1,0],up:[0,0,-1]},{label:"NavCube.bottom",boundaries:[[7,13,4,4]],dir:[0,1,0],up:[0,0,1]},{boundaries:[[7,5,4,2]],dir:[0,-.7071,-.7071],up:[0,.7071,-.7071]},{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,-.7071,.7071],up:[0,.7071,.7071]},{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:[.5,.7071,-.5],up:[-.5,.7071,.5]},{boundaries:[[23,11,1,1],[6,17,1,1],[0,11,1,1]],dir:[.5,.7071,.5],up:[-.5,.7071,-.5]},{boundaries:[[5,5,2,2]],dir:[.5,-.7071,-.5],up:[.5,.7071,-.5]},{boundaries:[[11,17,1,1],[17,11,2,1]],dir:[-.5,.7071,.5],up:[.5,.7071,-.5]},{boundaries:[[17,6,2,1],[11,0,1,1]],dir:[-.5,-.7071,.5],up:[-.5,.7071,.5]},{boundaries:[[11,11,2,2]],dir:[-.5,.7071,-.5],up:[.5,.7071,.5]},{boundaries:[[0,6,1,1],[6,0,1,1],[23,6,1,1]],dir:[.5,-.7071,.5],up:[.5,.7071,.5]},{boundaries:[[11,5,2,2]],dir:[-.5,-.7071,-.5],up:[-.5,.7071,-.5]}],h=0,d=c.length;h=A[0]*l&&t<=(A[0]+A[2])*l&&i>=A[1]*l&&i<=(A[1]+A[3])*l)return r}return-1},this.setAreaHighlighted=function(e,t){var i=v[e];if(!i)throw"Area not found: "+e;i.highlighted=!!t,y()},this.getAreaDir=function(e){var t=v[e];if(!t)throw"Unknown area: "+e;return t.dir},this.getAreaUp=function(e){var t=v[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)}}var QE=re.vec3(),VE=re.vec3();re.mat4();var HE=function(e){g(i,Ue);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};B(this,i),r=t.call(this,"NavCube",e,s),e.navCube=b(r);var n=!0;try{r._navCubeScene=new hr(e,{canvasId:s.canvasId,canvasElement:s.canvasElement,transparent:!0}),r._navCubeCanvas=r._navCubeScene.canvas.canvas,r._navCubeScene.input.keyboardEnabled=!1}catch(e){return r.error(e),y(r)}var o=r._navCubeScene;o.clearLights(),new Ti(o,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new Ti(o,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new Ti(o,{dir:[.8,-.6,-.8],color:[1,1,1],intensity:1,space:"view"}),r._navCubeCamera=o.camera,r._navCubeCamera.ortho.scale=7,r._navCubeCamera.ortho.near=.1,r._navCubeCamera.ortho.far=2e3,o.edgeMaterial.edgeColor=[.2,.2,.2],o.edgeMaterial.edgeAlpha=.6,r._zUp=Boolean(e.camera.zUp);var a=b(r);r.setIsProjectNorth(s.isProjectNorth),r.setProjectNorthOffsetAngle(s.projectNorthOffsetAngle);var l,u=(l=re.mat4(),function(e,t,i){return re.identityMat4(l),re.rotationMat4v(e*a._projectNorthOffsetAngle*re.DEGTORAD,[0,1,0],l),re.transformVec3(l,t,i)});r._synchCamera=function(){var t=re.rotationMat4c(-90*re.DEGTORAD,1,0,0),i=re.vec3(),r=re.vec3(),s=re.vec3();return function(){var n=e.camera.eye,o=e.camera.look,l=e.camera.up;i=re.mulVec3Scalar(re.normalizeVec3(re.subVec3(n,o,i)),5),a._isProjectNorth&&a._projectNorthOffsetAngle&&(i=u(-1,i,QE),l=u(-1,l,VE)),a._zUp?(re.transformVec3(t,i,r),re.transformVec3(t,l,s),a._navCubeCamera.look=[0,0,0],a._navCubeCamera.eye=re.transformVec3(t,i,r),a._navCubeCamera.up=re.transformPoint3(t,l,s)):(a._navCubeCamera.look=[0,0,0],a._navCubeCamera.eye=i,a._navCubeCamera.up=l)}}(),r._cubeTextureCanvas=new NE(e,o,s),r._cubeSampler=new Zn(o,{image:r._cubeTextureCanvas.getImage(),flipY:!0,wrapS:1001,wrapT:1001}),r._cubeMesh=new mn(o,{geometry:new Ki(o,{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 qi(o,{diffuse:[.4,.4,.4],specular:[.4,.4,.4],emissive:[.6,.6,.6],diffuseMap:r._cubeSampler,emissiveMap:r._cubeSampler}),visible:!!n,edges:!0}),r._shadow=!1===s.shadowVisible?null:new mn(o,{geometry:new Ki(o,yn({center:[0,0,0],radiusTop:.001,radiusBottom:1.4,height:.01,radialSegments:20,heightSegments:1,openEnded:!0})),material:new qi(o,{diffuse:[0,0,0],specular:[0,0,0],emissive:[0,0,0],alpha:.5}),position:[0,-1.5,0],visible:!!n,pickable:!1,backfaces:!1}),r._onCameraMatrix=e.camera.on("matrix",r._synchCamera),r._onCameraWorldAxis=e.camera.on("worldAxis",(function(){e.camera.zUp?(r._zUp=!0,r._cubeTextureCanvas.setZUp(),r._repaint(),r._synchCamera()):e.camera.yUp&&(r._zUp=!1,r._cubeTextureCanvas.setYUp(),r._repaint(),r._synchCamera())})),r._onCameraFOV=e.camera.perspective.on("fov",(function(e){r._synchProjection&&(r._navCubeCamera.perspective.fov=e)})),r._onCameraProjection=e.camera.on("projection",(function(e){r._synchProjection&&(r._navCubeCamera.projection="ortho"===e||"perspective"===e?e:"perspective")}));var c=-1;function A(t,i){var r=(t-d)*-_,s=(i-p)*-_;e.camera.orbitYaw(r),e.camera.orbitPitch(-s),d=t,p=i}function h(e){var t=[0,0];if(e){for(var i=e.target,r=0,s=0;i.offsetParent;)r+=i.offsetLeft,s+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-r,t[1]=e.pageY-s}else e=window.event,t[0]=e.x,t[1]=e.y;return t}var d,p,f=null,v=null,g=!1,m=!1,_=.5;a._navCubeCanvas.addEventListener("mouseenter",a._onMouseEnter=function(e){m=!0}),a._navCubeCanvas.addEventListener("mouseleave",a._onMouseLeave=function(e){m=!1}),a._navCubeCanvas.addEventListener("mousedown",a._onMouseDown=function(e){if(1===e.which){f=e.x,v=e.y,d=e.clientX,p=e.clientY;var t=h(e),i=o.pick({canvasPos:t});g=!!i}}),document.addEventListener("mouseup",a._onMouseUp=function(e){if(1===e.which&&(g=!1,null!==f)){var t=h(e),i=o.pick({canvasPos:t,pickSurface:!0});if(i&&i.uv){var r=a._cubeTextureCanvas.getArea(i.uv);if(r>=0&&(document.body.style.cursor="pointer",c>=0&&(a._cubeTextureCanvas.setAreaHighlighted(c,!1),a._repaint(),c=-1),r>=0)){if(a._cubeTextureCanvas.setAreaHighlighted(r,!0),c=r,a._repaint(),e.xf+3||e.yv+3)return;var s=a._cubeTextureCanvas.getAreaDir(r);if(s){var n=a._cubeTextureCanvas.getAreaUp(r);a._isProjectNorth&&a._projectNorthOffsetAngle&&(s=u(1,s,QE),n=u(1,n,VE)),x(s,n,(function(){c>=0&&(a._cubeTextureCanvas.setAreaHighlighted(c,!1),a._repaint(),c=-1),document.body.style.cursor="pointer",c>=0&&(a._cubeTextureCanvas.setAreaHighlighted(c,!1),a._repaint(),c=-1),r>=0&&(a._cubeTextureCanvas.setAreaHighlighted(r,!1),c=-1,a._repaint())}))}}}}}),document.addEventListener("mousemove",a._onMouseMove=function(e){if(c>=0&&(a._cubeTextureCanvas.setAreaHighlighted(c,!1),a._repaint(),c=-1),1!==e.buttons||g){if(g){var t=e.clientX,i=e.clientY;return document.body.style.cursor="move",void A(t,i)}if(m){var r=h(e),s=o.pick({canvasPos:r,pickSurface:!0});if(s){if(s.uv){document.body.style.cursor="pointer";var n=a._cubeTextureCanvas.getArea(s.uv);if(n===c)return;c>=0&&a._cubeTextureCanvas.setAreaHighlighted(c,!1),n>=0&&(a._cubeTextureCanvas.setAreaHighlighted(n,!0),a._repaint(),c=n)}}else document.body.style.cursor="default",c>=0&&(a._cubeTextureCanvas.setAreaHighlighted(c,!1),a._repaint(),c=-1)}}});var x=function(){var t=re.vec3();return function(i,r,s){var n=a._fitVisible?e.scene.getAABB(e.scene.visibleObjectIds):e.scene.aabb,o=re.getAABB3Diag(n);re.getAABB3Center(n,t);var l=Math.abs(o/Math.tan(a._cameraFitFOV*re.DEGTORAD));e.cameraControl.pivotPos=t,a._cameraFly?e.cameraFlight.flyTo({look:t,eye:[t[0]-l*i[0],t[1]-l*i[1],t[2]-l*i[2]],up:r||[0,1,0],orthoScale:1.1*o,fitFOV:a._cameraFitFOV,duration:a._cameraFlyDuration},s):e.cameraFlight.jumpTo({look:t,eye:[t[0]-l*i[0],t[1]-l*i[1],t[2]-l*i[2]],up:r||[0,1,0],orthoScale:1.1*o,fitFOV:a._cameraFitFOV},s)}}();return r._onUpdated=e.localeService.on("updated",(function(){r._cubeTextureCanvas.clear(),r._repaint()})),r.setVisible(s.visible),r.setCameraFitFOV(s.cameraFitFOV),r.setCameraFly(s.cameraFly),r.setCameraFlyDuration(s.cameraFlyDuration),r.setFitVisible(s.fitVisible),r.setSynchProjection(s.synchProjection),r}return C(i,[{key:"send",value:function(e,t){if("language"===e)this._cubeTextureCanvas.clear(),this._repaint()}},{key:"_repaint",value:function(){var e=this._cubeTextureCanvas.getImage();this._cubeMesh.material.diffuseMap.image=e,this._cubeMesh.material.emissiveMap.image=e}},{key:"setVisible",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this._navCubeCanvas&&(this._cubeMesh.visible=e,this._shadow&&(this._shadow.visible=e),this._navCubeCanvas.style.visibility=e?"visible":"hidden")}},{key:"getVisible",value:function(){return!!this._navCubeCanvas&&this._cubeMesh.visible}},{key:"setFitVisible",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._fitVisible=e}},{key:"getFitVisible",value:function(){return this._fitVisible}},{key:"setCameraFly",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this._cameraFly=e}},{key:"getCameraFly",value:function(){return this._cameraFly}},{key:"setCameraFitFOV",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:45;this._cameraFitFOV=e}},{key:"getCameraFitFOV",value:function(){return this._cameraFitFOV}},{key:"setCameraFlyDuration",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:.5;this._cameraFlyDuration=e}},{key:"getCameraFlyDuration",value:function(){return this._cameraFlyDuration}},{key:"setSynchProjection",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._synchProjection=e}},{key:"getSynchProjection",value:function(){return this._synchProjection}},{key:"setIsProjectNorth",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._isProjectNorth=e}},{key:"getIsProjectNorth",value:function(){return this._isProjectNorth}},{key:"setProjectNorthOffsetAngle",value:function(e){this._projectNorthOffsetAngle=e}},{key:"getProjectNorthOffsetAngle",value:function(){return this._projectNorthOffsetAngle}},{key:"destroy",value:function(){this._navCubeCanvas&&(this.viewer.localeService.off(this._onUpdated),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,f(x(i.prototype),"destroy",this).call(this)}}]),i}(),jE=re.vec3(),GE=function(){function e(){B(this,e)}return C(e,[{key:"load",value:function(e,t){var i=e.scene.canvas.spinner;i.processes++,zE(e,t,(function(t){KE(e,t,(function(){YE(e,t),i.processes--,we.scheduleTask((function(){e.fire("loaded",!0,!1)}))}))}))}},{key:"parse",value:function(e,t,i,r){if(t){var s=WE(e,t,null);i&&JE(e,i,r),YE(e,s),e.src=null,e.fire("loaded",!0,!1)}else this.warn("load() param expected: objText")}}]),e}(),zE=function(e,t,i){ZE(t,(function(r){var s=WE(e,r,t);i(s)}),(function(t){e.error(t)}))},WE=function(){var e={vertex_pattern:/^v\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,normal_pattern:/^vn\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,uv_pattern:/^vt\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,face_vertex:/^f\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)(?:\s+(-?\d+))?/,face_vertex_uv:/^f\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+))?/,face_vertex_uv_normal:/^f\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+)\/(-?\d+))?/,face_vertex_normal:/^f\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)(?:\s+(-?\d+)\/\/(-?\d+))?/,object_pattern:/^[og]\s*(.+)?/,smoothing_pattern:/^s\s+(\d+|on|off)/,material_library_pattern:/^mtllib /,material_use_pattern:/^usemtl /};return function(r,s,n){var o={src:n=n||"",basePath:t(n),objects:[],object:{},positions:[],normals:[],uv:[],materialLibraries:{}};i(o,"",!1),-1!==s.indexOf("\r\n")&&(s=s.replace("\r\n","\n"));for(var a=s.split("\n"),l="",u="",c="",d=[],p="function"==typeof"".trimLeft,f=0,v=a.length;f=0?i-1:i+t/3)}function s(e,t){var i=parseInt(e,10);return 3*(i>=0?i-1:i+t/3)}function n(e,t){var i=parseInt(e,10);return 2*(i>=0?i-1:i+t/2)}function o(e,t,i,r){var s=e.positions,n=e.object.geometry.positions;n.push(s[t+0]),n.push(s[t+1]),n.push(s[t+2]),n.push(s[i+0]),n.push(s[i+1]),n.push(s[i+2]),n.push(s[r+0]),n.push(s[r+1]),n.push(s[r+2])}function a(e,t){var i=e.positions,r=e.object.geometry.positions;r.push(i[t+0]),r.push(i[t+1]),r.push(i[t+2])}function l(e,t,i,r){var s=e.normals,n=e.object.geometry.normals;n.push(s[t+0]),n.push(s[t+1]),n.push(s[t+2]),n.push(s[i+0]),n.push(s[i+1]),n.push(s[i+2]),n.push(s[r+0]),n.push(s[r+1]),n.push(s[r+2])}function u(e,t,i,r){var s=e.uv,n=e.object.geometry.uv;n.push(s[t+0]),n.push(s[t+1]),n.push(s[i+0]),n.push(s[i+1]),n.push(s[r+0]),n.push(s[r+1])}function c(e,t){var i=e.uv,r=e.object.geometry.uv;r.push(i[t+0]),r.push(i[t+1])}function A(e,t,i,a,c,A,h,d,p,f,v,g,m){var _,y=e.positions.length,b=r(t,y),x=r(i,y),w=r(a,y);if(void 0===c?o(e,b,x,w):(o(e,b,x,_=r(c,y)),o(e,x,w,_)),void 0!==A){var B=e.uv.length;b=n(A,B),x=n(h,B),w=n(d,B),void 0===c?u(e,b,x,w):(u(e,b,x,_=n(p,B)),u(e,x,w,_))}if(void 0!==f){var P=e.normals.length;b=s(f,P),x=f===v?b:s(v,P),w=f===g?b:s(g,P),void 0===c?l(e,b,x,w):(l(e,b,x,_=s(m,P)),l(e,x,w,_))}}function h(e,t,i){e.object.geometry.type="Line";for(var s=e.positions.length,o=e.uv.length,l=0,u=t.length;l=0?o.substring(0,a):o).toLowerCase(),u=(u=a>=0?o.substring(a+1):"").trim(),l.toLowerCase()){case"newmtl":i(e,h),h={id:u},d=!0;break;case"ka":h.ambient=r(u);break;case"kd":h.diffuse=r(u);break;case"ks":h.specular=r(u);break;case"map_kd":h.diffuseMap||(h.diffuseMap=t(e,n,u,"sRGB"));break;case"map_ks":h.specularMap||(h.specularMap=t(e,n,u,"linear"));break;case"map_bump":case"bump":h.normalMap||(h.normalMap=t(e,n,u));break;case"ns":h.shininess=parseFloat(u);break;case"d":(c=parseFloat(u))<1&&(h.alpha=c,h.alphaMode="blend");break;case"tr":(c=parseFloat(u))>0&&(h.alpha=1-c,h.alphaMode="blend")}d&&i(e,h)};function t(e,t,i,r){var s={},n=i.split(/\s+/),o=n.indexOf("-bm");return o>=0&&n.splice(o,2),(o=n.indexOf("-s"))>=0&&(s.scale=[parseFloat(n[o+1]),parseFloat(n[o+2])],n.splice(o,4)),(o=n.indexOf("-o"))>=0&&(s.translate=[parseFloat(n[o+1]),parseFloat(n[o+2])],n.splice(o,4)),s.src=t+n.join(" ").trim(),s.flipY=!0,s.encoding=r||"linear",new Zn(e,s).id}function i(e,t){new qi(e,t)}function r(t){var i=t.split(e,3);return[parseFloat(i[0]),parseFloat(i[1]),parseFloat(i[2])]}}();function YE(e,t){for(var i=0,r=t.objects.length;i0&&(o.normals=n.normals),n.uv.length>0&&(o.uv=n.uv);for(var a=new Array(o.positions.length/3),l=0;l0&&void 0!==arguments[0]?arguments[0]:{};t.id&&this.viewer.scene.components[t.id]&&(this.error("Component with this ID already exists in viewer: "+t.id+" - will autogenerate this ID"),delete t.id);var i=new Ln(this.viewer.scene,he.apply(t,{isModel:!0})),r=i.id,s=t.src;if(!s)return this.error("load() param expected: src"),i;if(t.metaModelSrc){var n=t.metaModelSrc;he.loadJSON(n,(function(n){e.viewer.metaScene.createMetaModel(r,n),e._sceneGraphLoader.load(i,s,t)}),(function(t){e.error("load(): Failed to load model modelMetadata for model '".concat(r," from '").concat(n,"' - ").concat(t))}))}else this._sceneGraphLoader.load(i,s,t);return i.once("destroyed",(function(){e.viewer.metaScene.destroyMetaModel(r)})),i}},{key:"destroy",value:function(){f(x(i.prototype),"destroy",this).call(this)}}]),i}(),$E=new Float64Array([0,0,1]),eF=new Float64Array(4),tF=function(){function e(t){B(this,e),this.id=null,this._viewer=t.viewer,this._visible=!1,this._pos=re.vec3(),this._origin=re.vec3(),this._rtcPos=re.vec3(),this._baseDir=re.vec3(),this._rootNode=null,this._displayMeshes=null,this._affordanceMeshes=null,this._ignoreNextSectionPlaneDirUpdate=!1,this._createNodes(),this._bindEvents()}return C(e,[{key:"_setSectionPlane",value:function(e){var t=this;this._sectionPlane&&(this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._onSectionPlanePos=null,this._onSectionPlaneDir=null,this._sectionPlane=null),e&&(this.id=e.id,this._setPos(e.pos),this._setDir(e.dir),this._sectionPlane=e,this._onSectionPlanePos=e.on("pos",(function(){t._setPos(t._sectionPlane.pos)})),this._onSectionPlaneDir=e.on("dir",(function(){t._ignoreNextSectionPlaneDirUpdate?t._ignoreNextSectionPlaneDirUpdate=!1:t._setDir(t._sectionPlane.dir)})))}},{key:"sectionPlane",get:function(){return this._sectionPlane}},{key:"_setPos",value:function(e){this._pos.set(e),He(this._pos,this._origin,this._rtcPos),this._rootNode.origin=this._origin,this._rootNode.position=this._rtcPos}},{key:"_setDir",value:function(e){this._baseDir.set(e),this._rootNode.quaternion=re.vec3PairToQuaternion($E,e,eF)}},{key:"_setSectionPlaneDir",value:function(e){this._sectionPlane&&(this._ignoreNextSectionPlaneDirUpdate=!0,this._sectionPlane.dir=e)}},{key:"setVisible",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[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)}}},{key:"getVisible",value:function(){return this._visible}},{key:"setCulled",value:function(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)}},{key:"_createNodes",value:function(){var e=!1,t=this._viewer.scene,i=.01;this._rootNode=new Ln(t,{position:[0,0,0],scale:[5,5,5],isObject:!1});var r,s,n=this._rootNode,o={arrowHead:new Ki(n,yn({radiusTop:.001,radiusBottom:.07,radialSegments:32,heightSegments:1,height:.2,openEnded:!1})),arrowHeadBig:new Ki(n,yn({radiusTop:.001,radiusBottom:.09,radialSegments:32,heightSegments:1,height:.25,openEnded:!1})),arrowHeadHandle:new Ki(n,yn({radiusTop:.09,radiusBottom:.09,radialSegments:8,heightSegments:1,height:.37,openEnded:!1})),curve:new Ki(n,uo({radius:.8,tube:i,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),curveHandle:new Ki(n,uo({radius:.8,tube:.06,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),hoop:new Ki(n,uo({radius:.8,tube:i,radialSegments:64,tubeSegments:8,arc:2*Math.PI})),axis:new Ki(n,yn({radiusTop:i,radiusBottom:i,radialSegments:20,heightSegments:1,height:1,openEnded:!1})),axisHandle:new Ki(n,yn({radiusTop:.08,radiusBottom:.08,radialSegments:20,heightSegments:1,height:1,openEnded:!1}))},a={pickable:new qi(n,{diffuse:[1,1,0],alpha:0,alphaMode:"blend"}),red:new qi(n,{diffuse:[1,0,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightRed:new er(n,{edges:!1,fill:!0,fillColor:[1,0,0],fillAlpha:.6}),green:new qi(n,{diffuse:[0,1,0],emissive:[0,1,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightGreen:new er(n,{edges:!1,fill:!0,fillColor:[0,1,0],fillAlpha:.6}),blue:new qi(n,{diffuse:[0,0,1],emissive:[0,0,1],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightBlue:new er(n,{edges:!1,fill:!0,fillColor:[0,0,1],fillAlpha:.2}),center:new qi(n,{diffuse:[0,0,0],emissive:[0,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80}),highlightBall:new er(n,{edges:!1,fill:!0,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1}),highlightPlane:new er(n,{edges:!0,edgeWidth:3,fill:!1,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1})};this._displayMeshes={plane:n.addChild(new mn(n,{geometry:new Ki(n,{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 qi(n,{emissive:[0,0,0],diffuse:[0,0,0],backfaces:!0}),opacity:.6,ghosted:!0,ghostMaterial:new er(n,{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],isObject:!1}),e),planeFrame:n.addChild(new mn(n,{geometry:new Ki(n,uo({center:[0,0,0],radius:1.7,tube:.02,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new qi(n,{emissive:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],shininess:0}),highlightMaterial:new er(n,{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],isObject:!1}),e),xCurve:n.addChild(new mn(n,{geometry:o.curve,material:a.red,matrix:(r=re.rotationMat4v(90*re.DEGTORAD,[0,1,0],re.identityMat4()),s=re.rotationMat4v(270*re.DEGTORAD,[1,0,0],re.identityMat4()),re.mulMat4(s,r,re.identityMat4())),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xCurveHandle:n.addChild(new mn(n,{geometry:o.curveHandle,material:a.pickable,matrix:function(){var e=re.rotationMat4v(90*re.DEGTORAD,[0,1,0],re.identityMat4()),t=re.rotationMat4v(270*re.DEGTORAD,[1,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xCurveArrow1:n.addChild(new mn(n,{geometry:o.arrowHead,material:a.red,matrix:function(){var e=re.translateMat4c(0,-.07,-.8,re.identityMat4()),t=re.scaleMat4v([.6,.6,.6],re.identityMat4()),i=re.rotationMat4v(0*re.DEGTORAD,[0,0,1],re.identityMat4());return re.mulMat4(re.mulMat4(e,t,re.identityMat4()),i,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xCurveArrow2:n.addChild(new mn(n,{geometry:o.arrowHead,material:a.red,matrix:function(){var e=re.translateMat4c(0,-.8,-.07,re.identityMat4()),t=re.scaleMat4v([.6,.6,.6],re.identityMat4()),i=re.rotationMat4v(90*re.DEGTORAD,[1,0,0],re.identityMat4());return re.mulMat4(re.mulMat4(e,t,re.identityMat4()),i,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yCurve:n.addChild(new mn(n,{geometry:o.curve,material:a.green,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),yCurveHandle:n.addChild(new mn(n,{geometry:o.curveHandle,material:a.pickable,rotation:[-90,0,0],pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),yCurveArrow1:n.addChild(new mn(n,{geometry:o.arrowHead,material:a.green,matrix:function(){var e=re.translateMat4c(.07,0,-.8,re.identityMat4()),t=re.scaleMat4v([.6,.6,.6],re.identityMat4()),i=re.rotationMat4v(90*re.DEGTORAD,[0,0,1],re.identityMat4());return re.mulMat4(re.mulMat4(e,t,re.identityMat4()),i,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yCurveArrow2:n.addChild(new mn(n,{geometry:o.arrowHead,material:a.green,matrix:function(){var e=re.translateMat4c(.8,0,-.07,re.identityMat4()),t=re.scaleMat4v([.6,.6,.6],re.identityMat4()),i=re.rotationMat4v(90*re.DEGTORAD,[1,0,0],re.identityMat4());return re.mulMat4(re.mulMat4(e,t,re.identityMat4()),i,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurve:n.addChild(new mn(n,{geometry:o.curve,material:a.blue,matrix:re.rotationMat4v(180*re.DEGTORAD,[1,0,0],re.identityMat4()),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveHandle:n.addChild(new mn(n,{geometry:o.curveHandle,material:a.pickable,matrix:re.rotationMat4v(180*re.DEGTORAD,[1,0,0],re.identityMat4()),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveCurveArrow1:n.addChild(new mn(n,{geometry:o.arrowHead,material:a.blue,matrix:function(){var e=re.translateMat4c(.8,-.07,0,re.identityMat4()),t=re.scaleMat4v([.6,.6,.6],re.identityMat4());return re.mulMat4(e,t,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveArrow2:n.addChild(new mn(n,{geometry:o.arrowHead,material:a.blue,matrix:function(){var e=re.translateMat4c(.05,-.8,0,re.identityMat4()),t=re.scaleMat4v([.6,.6,.6],re.identityMat4()),i=re.rotationMat4v(90*re.DEGTORAD,[0,0,1],re.identityMat4());return re.mulMat4(re.mulMat4(e,t,re.identityMat4()),i,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),center:n.addChild(new mn(n,{geometry:new Ki(n,bn({radius:.05})),material:a.center,pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisArrow:n.addChild(new mn(n,{geometry:o.arrowHead,material:a.red,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[0,0,1],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisArrowHandle:n.addChild(new mn(n,{geometry:o.arrowHeadHandle,material:a.pickable,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[0,0,1],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxis:n.addChild(new mn(n,{geometry:o.axis,material:a.red,matrix:function(){var e=re.translateMat4c(0,.5,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[0,0,1],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisHandle:n.addChild(new mn(n,{geometry:o.axisHandle,material:a.pickable,matrix:function(){var e=re.translateMat4c(0,.5,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[0,0,1],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrow:n.addChild(new mn(n,{geometry:o.arrowHead,material:a.green,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(180*re.DEGTORAD,[1,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrowHandle:n.addChild(new mn(n,{geometry:o.arrowHeadHandle,material:a.pickable,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(180*re.DEGTORAD,[1,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,opacity:.2,isObject:!1}),e),yShaft:n.addChild(new mn(n,{geometry:o.axis,material:a.green,position:[0,-.5,0],pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yShaftHandle:n.addChild(new mn(n,{geometry:o.axisHandle,material:a.pickable,position:[0,-.5,0],pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrow:n.addChild(new mn(n,{geometry:o.arrowHead,material:a.blue,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[.8,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrowHandle:n.addChild(new mn(n,{geometry:o.arrowHeadHandle,material:a.pickable,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[.8,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zShaft:n.addChild(new mn(n,{geometry:o.axis,material:a.blue,matrix:function(){var e=re.translateMat4c(0,.5,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[1,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),clippable:!1,pickable:!1,collidable:!0,visible:!1,isObject:!1}),e),zAxisHandle:n.addChild(new mn(n,{geometry:o.axisHandle,material:a.pickable,matrix:function(){var e=re.translateMat4c(0,.5,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[1,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),clippable:!1,pickable:!0,collidable:!0,visible:!1,isObject:!1}),e)},this._affordanceMeshes={planeFrame:n.addChild(new mn(n,{geometry:new Ki(n,uo({center:[0,0,0],radius:2,tube:i,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new qi(n,{ambient:[1,1,1],diffuse:[0,0,0],emissive:[1,1,0]}),highlighted:!0,highlightMaterial:new er(n,{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],isObject:!1}),e),xHoop:n.addChild(new mn(n,{geometry:o.hoop,material:a.red,highlighted:!0,highlightMaterial:a.highlightRed,matrix:function(){var e=re.rotationMat4v(90*re.DEGTORAD,[0,1,0],re.identityMat4()),t=re.rotationMat4v(270*re.DEGTORAD,[1,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yHoop:n.addChild(new mn(n,{geometry:o.hoop,material:a.green,highlighted:!0,highlightMaterial:a.highlightGreen,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zHoop:n.addChild(new mn(n,{geometry:o.hoop,material:a.blue,highlighted:!0,highlightMaterial:a.highlightBlue,matrix:re.rotationMat4v(180*re.DEGTORAD,[1,0,0],re.identityMat4()),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xAxisArrow:n.addChild(new mn(n,{geometry:o.arrowHeadBig,material:a.red,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[0,0,1],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrow:n.addChild(new mn(n,{geometry:o.arrowHeadBig,material:a.green,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(180*re.DEGTORAD,[1,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrow:n.addChild(new mn(n,{geometry:o.arrowHeadBig,material:a.blue,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[.8,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e)}}},{key:"_bindEvents",value:function(){var e=this,t=this,i=!1,r=-1,s=0,n=1,o=2,a=3,l=4,u=5,c=this._rootNode,A=null,h=null,d=re.vec2(),p=re.vec3([1,0,0]),f=re.vec3([0,1,0]),v=re.vec3([0,0,1]),g=this._viewer.scene.canvas.canvas,m=this._viewer.camera,_=this._viewer.scene,y=re.vec3([0,0,0]),b=-1;this._onCameraViewMatrix=_.camera.on("viewMatrix",(function(){})),this._onCameraProjMatrix=_.camera.on("projMatrix",(function(){})),this._onSceneTick=_.on("tick",(function(){var t=Math.abs(re.lenVec3(re.subVec3(_.camera.eye,e._pos,y)));if(t!==b&&"perspective"===m.projection){var i=.07*(Math.tan(m.perspective.fov*re.DEGTORAD)*t);c.scale=[i,i,i],b=t}if("ortho"===m.projection){var r=m.ortho.scale/10;c.scale=[r,r,r],b=t}}));var x,w,B,P,C,M=function(){var e=new Float64Array(2);return function(t){if(t){for(var i=t.target,r=0,s=0;i.offsetParent;)r+=i.offsetLeft,s+=i.offsetTop,i=i.offsetParent;e[0]=t.pageX-r,e[1]=t.pageY-s}else t=window.event,e[0]=t.x,e[1]=t.y;return e}}(),E=function(){var e=re.mat4();return function(i,r){return re.quaternionToMat4(t._rootNode.quaternion,e),re.transformVec3(e,i,r),re.normalizeVec3(r),r}}(),F=(x=re.vec3(),function(e){var t=Math.abs(e[0]);return t>Math.abs(e[1])&&t>Math.abs(e[2])?re.cross3Vec3(e,[0,1,0],x):re.cross3Vec3(e,[1,0,0],x),re.cross3Vec3(x,e,x),re.normalizeVec3(x),x}),k=(w=re.vec3(),B=re.vec3(),P=re.vec4(),function(e,i,r){E(e,P);var s=F(P,i,r);D(i,s,w),D(r,s,B),re.subVec3(B,w);var n=re.dotVec3(B,P);t._pos[0]+=P[0]*n,t._pos[1]+=P[1]*n,t._pos[2]+=P[2]*n,t._rootNode.position=t._pos,t._sectionPlane&&(t._sectionPlane.pos=t._pos)}),I=function(){var e=re.vec4(),i=re.vec4(),r=re.vec4(),s=re.vec4();return function(n,o,a){if(E(n,s),!(D(o,s,e)&&D(a,s,i))){var l=F(s,o,a);D(o,l,e,1),D(a,l,i,1);var u=re.dotVec3(e,s);e[0]-=u*s[0],e[1]-=u*s[1],e[2]-=u*s[2],u=re.dotVec3(i,s),i[0]-=u*s[0],i[1]-=u*s[1],i[2]-=u*s[2]}re.normalizeVec3(e),re.normalizeVec3(i),u=re.dotVec3(e,i),u=re.clamp(u,-1,1);var c=Math.acos(u)*re.RADTODEG;re.cross3Vec3(e,i,r),re.dotVec3(r,s)<0&&(c=-c),t._rootNode.rotate(n,c),S()}}(),D=function(){var e=re.vec4([0,0,0,1]),i=re.mat4();return function(r,s,n,o){o=o||0,e[0]=r[0]/g.width*2-1,e[1]=-(r[1]/g.height*2-1),e[2]=0,e[3]=1,re.mulMat4(m.projMatrix,m.viewMatrix,i),re.inverseMat4(i),re.transformVec4(i,e,e),re.mulVec4Scalar(e,1/e[3]);var a=m.eye;re.subVec4(e,a,e);var l=t._sectionPlane.pos,u=-re.dotVec3(l,s)-o,c=re.dotVec3(s,e);if(Math.abs(c)>.005){var A=-(re.dotVec3(s,a)+u)/c;return re.mulVec3Scalar(e,A,n),re.addVec3(n,a),re.subVec3(n,l,n),!0}return!1}}(),S=function(){var e=re.vec3(),i=re.mat4();return function(){t.sectionPlane&&(re.quaternionToMat4(c.quaternion,i),re.transformVec3(i,[0,0,1],e),t._setSectionPlaneDir(e))}}(),T=!1;this._onCameraControlHover=this._viewer.cameraControl.on("hoverEnter",(function(t){if(e._visible&&!T){var c;switch(i=!1,C&&(C.visible=!1),t.entity.id){case e._displayMeshes.xAxisArrowHandle.id:case e._displayMeshes.xAxisHandle.id:c=e._affordanceMeshes.xAxisArrow,A=s;break;case e._displayMeshes.yAxisArrowHandle.id:case e._displayMeshes.yShaftHandle.id:c=e._affordanceMeshes.yAxisArrow,A=n;break;case e._displayMeshes.zAxisArrowHandle.id:case e._displayMeshes.zAxisHandle.id:c=e._affordanceMeshes.zAxisArrow,A=o;break;case e._displayMeshes.xCurveHandle.id:c=e._affordanceMeshes.xHoop,A=a;break;case e._displayMeshes.yCurveHandle.id:c=e._affordanceMeshes.yHoop,A=l;break;case e._displayMeshes.zCurveHandle.id:c=e._affordanceMeshes.zHoop,A=u;break;default:return void(A=r)}c&&(c.visible=!0),C=c,i=!0}})),this._onCameraControlHoverLeave=this._viewer.cameraControl.on("hoverOutEntity",(function(t){e._visible&&(C&&(C.visible=!1),C=null,A=r)})),g.addEventListener("mousedown",this._canvasMouseDownListener=function(t){if(t.preventDefault(),e._visible&&i&&(e._viewer.cameraControl.pointerEnabled=!1,1===t.which)){T=!0;var r=M(t);h=A,d[0]=r[0],d[1]=r[1]}}),g.addEventListener("mousemove",this._canvasMouseMoveListener=function(t){if(e._visible&&T){var i=M(t),r=i[0],c=i[1];switch(h){case s:k(p,d,i);break;case n:k(f,d,i);break;case o:k(v,d,i);break;case a:I(p,d,i);break;case l:I(f,d,i);break;case u:I(v,d,i)}d[0]=r,d[1]=c}}),g.addEventListener("mouseup",this._canvasMouseUpListener=function(t){e._visible&&(e._viewer.cameraControl.pointerEnabled=!0,T&&(t.which,T=!1,i=!1))}),g.addEventListener("wheel",this._canvasWheelListener=function(t){if(e._visible)Math.max(-1,Math.min(1,40*-t.deltaY))})}},{key:"_destroy",value:function(){this._unbindEvents(),this._destroyNodes()}},{key:"_unbindEvents",value:function(){var e=this._viewer,t=e.scene,i=t.canvas.canvas,r=e.camera,s=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),r.off(this._onCameraViewMatrix),r.off(this._onCameraProjMatrix),s.off(this._onCameraControlHover),s.off(this._onCameraControlHoverLeave)}},{key:"_destroyNodes",value:function(){this._setSectionPlane(null),this._rootNode.destroy(),this._displayMeshes={},this._affordanceMeshes={}}}]),e}(),iF=function(){function e(t,i,r){var s=this;B(this,e),this.id=r.id,this._sectionPlane=r,this._mesh=new mn(i,{id:r.id,geometry:new Ki(i,Xi({xSize:.5,ySize:.5,zSize:.001})),material:new qi(i,{emissive:[1,1,1],diffuse:[0,0,0],backfaces:!1}),edgeMaterial:new ir(i,{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),highlightMaterial:new er(i,{fill:!0,fillColor:[.5,1,.5],fillAlpha:.7,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),selectedMaterial:new er(i,{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});var n=re.vec3([0,0,0]),o=re.vec3(),a=re.vec3([0,0,1]),l=re.vec4(4),u=re.vec3(),c=function(){var e=s._sectionPlane.scene.center,t=[-s._sectionPlane.dir[0],-s._sectionPlane.dir[1],-s._sectionPlane.dir[2]];re.subVec3(e,s._sectionPlane.pos,n);var i=-re.dotVec3(t,n);re.normalizeVec3(t),re.mulVec3Scalar(t,i,o);var r=re.vec3PairToQuaternion(a,s._sectionPlane.dir,l);u[0]=.1*o[0],u[1]=.1*o[1],u[2]=.1*o[2],s._mesh.quaternion=r,s._mesh.position=u};this._onSectionPlanePos=this._sectionPlane.on("pos",c),this._onSectionPlaneDir=this._sectionPlane.on("dir",c),this._highlighted=!1,this._selected=!1}return C(e,[{key:"setHighlighted",value:function(e){this._highlighted=!!e,this._mesh.highlighted=this._highlighted,this._mesh.highlightMaterial.fillColor=e?[0,.7,0]:[0,0,0]}},{key:"getHighlighted",value:function(){return this._highlighted}},{key:"setSelected",value:function(e){this._selected=!!e,this._mesh.edgeMaterial.edgeWidth=e?3:1,this._mesh.highlightMaterial.edgeWidth=e?3:1}},{key:"getSelected",value:function(){return this._selected}},{key:"destroy",value:function(){this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._mesh.destroy()}}]),e}(),rF=function(){function e(t,i){var r=this;if(B(this,e),!(i.onHoverEnterPlane&&i.onHoverLeavePlane&&i.onClickedNothing&&i.onClickedPlane))throw"Missing config(s): onHoverEnterPlane, onHoverLeavePlane, onClickedNothing || onClickedPlane";this.plugin=t,this._viewer=t.viewer,this._onHoverEnterPlane=i.onHoverEnterPlane,this._onHoverLeavePlane=i.onHoverLeavePlane,this._onClickedNothing=i.onClickedNothing,this._onClickedPlane=i.onClickedPlane,this._visible=!0,this._planes={},this._canvas=i.overviewCanvas,this._scene=new hr(this._viewer,{canvasId:this._canvas.id,transparent:!0}),this._scene.clearLights(),new Ti(this._scene,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new Ti(this._scene,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new Ti(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;var s=this._scene.camera,n=re.rotationMat4c(-90*re.DEGTORAD,1,0,0),o=re.vec3(),a=re.vec3(),l=re.vec3();this._synchCamera=function(){var e=r._viewer.camera.eye,t=r._viewer.camera.look,i=r._viewer.camera.up;re.mulVec3Scalar(re.normalizeVec3(re.subVec3(e,t,o)),7),r._zUp?(re.transformVec3(n,o,a),re.transformVec3(n,i,l),s.look=[0,0,0],s.eye=re.transformVec3(n,o,a),s.up=re.transformPoint3(n,i,l)):(s.look=[0,0,0],s.eye=o,s.up=i)},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",(function(e){r._scene.camera.perspective.fov=e}));var u=null;this._onInputMouseMove=this._scene.input.on("mousemove",(function(e){var t=r._scene.pick({canvasPos:e});if(t){if(!u||t.entity.id!==u.id){if(u)r._planes[u.id]&&r._onHoverLeavePlane(u.id);u=t.entity,r._planes[u.id]&&r._onHoverEnterPlane(u.id)}}else u&&(r._onHoverLeavePlane(u.id),u=null)})),this._scene.canvas.canvas.addEventListener("mouseup",this._onCanvasMouseUp=function(){u?r._planes[u.id]&&r._onClickedPlane(u.id):r._onClickedNothing()}),this._scene.canvas.canvas.addEventListener("mouseout",this._onCanvasMouseOut=function(){u&&(r._onHoverLeavePlane(u.id),u=null)}),this.setVisible(i.overviewVisible)}return C(e,[{key:"addSectionPlane",value:function(e){this._planes[e.id]=new iF(this,this._scene,e)}},{key:"setPlaneHighlighted",value:function(e,t){var i=this._planes[e];i&&i.setHighlighted(t)}},{key:"setPlaneSelected",value:function(e,t){var i=this._planes[e];i&&i.setSelected(t)}},{key:"removeSectionPlane",value:function(e){var t=this._planes[e.id];t&&(t.destroy(),delete this._planes[e.id])}},{key:"setVisible",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this._visible=e,this._canvas.style.visibility=e?"visible":"hidden"}},{key:"getVisible",value:function(){return this._visible}},{key:"destroy",value:function(){this._viewer.camera.off(this._onViewerCameraMatrix),this._viewer.camera.off(this._onViewerCameraWorldAxis),this._viewer.camera.perspective.off(this._onViewerCameraFOV),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()}}]),e}(),sF=re.AABB3(),nF=re.vec3(),oF=function(e){g(i,Ue);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(B(this,i),(r=t.call(this,"SectionPlanes",e))._freeControls=[],r._sectionPlanes=e.scene.sectionPlanes,r._controls={},r._shownControlId=null,null!==s.overviewCanvasId&&void 0!==s.overviewCanvasId){var n=document.getElementById(s.overviewCanvasId);n?r._overview=new rF(b(r),{overviewCanvas:n,visible:s.overviewVisible,onHoverEnterPlane:function(e){r._overview.setPlaneHighlighted(e,!0)},onHoverLeavePlane:function(e){r._overview.setPlaneHighlighted(e,!1)},onClickedPlane:function(e){if(r.getShownControl()!==e){r.showControl(e);var t=r.sectionPlanes[e].pos;sF.set(r.viewer.scene.aabb),re.getAABB3Center(sF,nF),sF[0]+=t[0]-nF[0],sF[1]+=t[1]-nF[1],sF[2]+=t[2]-nF[2],sF[3]+=t[0]-nF[0],sF[4]+=t[1]-nF[1],sF[5]+=t[2]-nF[2],r.viewer.cameraFlight.flyTo({aabb:sF,fitFOV:65})}else r.hideControl()},onClickedNothing:function(){r.hideControl()}}):r.warn("Can't find overview canvas: '"+s.overviewCanvasId+"' - will create plugin without overview")}return r._onSceneSectionPlaneCreated=e.scene.on("sectionPlaneCreated",(function(e){r._sectionPlaneCreated(e)})),r}return C(i,[{key:"setOverviewVisible",value:function(e){this._overview&&this._overview.setVisible(e)}},{key:"getOverviewVisible",value:function(){if(this._overview)return this._overview.getVisible()}},{key:"sectionPlanes",get:function(){return this._sectionPlanes}},{key:"createSectionPlane",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};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);var t=new Pn(this.viewer.scene,{id:e.id,pos:e.pos,dir:e.dir,active:!0});return t}},{key:"_sectionPlaneCreated",value:function(e){var t=this,i=this._freeControls.length>0?this._freeControls.pop():new tF(this);i._setSectionPlane(e),i.setVisible(!1),this._controls[e.id]=i,this._overview&&this._overview.addSectionPlane(e),e.once("destroyed",(function(){t._sectionPlaneDestroyed(e)}))}},{key:"flipSectionPlanes",value:function(){var e=this.viewer.scene.sectionPlanes;for(var t in e){e[t].flipDir()}}},{key:"showControl",value:function(e){var 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)}},{key:"getShownControl",value:function(){return this._shownControlId}},{key:"hideControl",value:function(){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}},{key:"destroySectionPlane",value:function(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)}},{key:"_sectionPlaneDestroyed",value:function(e){this._overview&&this._overview.removeSectionPlane(e);var t=this._controls[e.id];t&&(t.setVisible(!1),t._setSectionPlane(null),delete this._controls[e.id],this._freeControls.push(t))}},{key:"clear",value:function(){for(var e=Object.keys(this._sectionPlanes),t=0,i=e.length;t1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),(r=t.call(this,"StoreyViews",e))._objectsMemento=new Hd,r._cameraMemento=new Od,r.storeys={},r.modelStoreys={},r._fitStoreyMaps=!!s.fitStoreyMaps,r._onModelLoaded=r.viewer.scene.on("modelLoaded",(function(e){r._registerModelStoreys(e),r.fire("storeys",r.storeys)})),r}return C(i,[{key:"_registerModelStoreys",value:function(e){var t=this,i=this.viewer,r=i.scene,s=i.metaScene,n=s.metaModels[e],o=r.models[e];if(n&&n.rootMetaObjects)for(var a=n.rootMetaObjects,l=0,u=a.length;l.5?p.length:0,g=new aF(this,o.aabb,f,e,d,v);g._onModelDestroyed=o.once("destroyed",(function(){t._deregisterModelStoreys(e),t.fire("storeys",t.storeys)})),this.storeys[d]=g,this.modelStoreys[e]||(this.modelStoreys[e]={}),this.modelStoreys[e][d]=g}}},{key:"_deregisterModelStoreys",value:function(e){var t=this.modelStoreys[e];if(t){var i=this.viewer.scene;for(var r in t)if(t.hasOwnProperty(r)){var s=t[r],n=i.models[s.modelId];n&&n.off(s._onModelDestroyed),delete this.storeys[r]}delete this.modelStoreys[e]}}},{key:"fitStoreyMaps",get:function(){return this._fitStoreyMaps}},{key:"gotoStoreyCamera",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=this.storeys[e];if(!i)return this.error("IfcBuildingStorey not found with this ID: "+e),void(t.done&&t.done());var r=this.viewer,s=r.scene,n=s.camera,o=i.storeyAABB;if(o[3]1&&void 0!==arguments[1]?arguments[1]:{},i=this.storeys[e];if(i){var r=this.viewer,s=r.scene,n=r.metaScene,o=n.metaObjects[e];o&&(t.hideOthers&&s.setObjectsVisible(r.scene.visibleObjectIds,!1),this.withStoreyObjects(e,(function(e,t){e&&(e.visible=!0)})))}else this.error("IfcBuildingStorey not found with this ID: "+e)}},{key:"withStoreyObjects",value:function(e,t){var i=this.viewer,r=i.scene,s=i.metaScene,n=s.metaObjects[e];if(n)for(var o=n.getObjectIDsInSubtree(),a=0,l=o.length;a1&&void 0!==arguments[1]?arguments[1]:{},i=this.storeys[e];if(!i)return this.error("IfcBuildingStorey not found with this ID: "+e),AF;var r,s,n=this.viewer,o=n.scene,a=t.format||"png",l=this._fitStoreyMaps?i.storeyAABB:i.modelAABB,u=Math.abs((l[5]-l[2])/(l[3]-l[0])),c=t.padding||0;t.width&&t.height?(r=t.width,s=t.height):t.height?(s=t.height,r=Math.round(s/u)):t.width?(r=t.width,s=Math.round(r*u)):(r=300,s=Math.round(r*u)),this._objectsMemento.saveObjects(o),this._cameraMemento.saveCamera(o),this.showStoreyObjects(e,he.apply(t,{hideOthers:!0})),this._arrangeStoreyMapCamera(i);var A=n.getSnapshot({width:r,height:s,format:a});return this._objectsMemento.restoreObjects(o),this._cameraMemento.restoreCamera(o),new lF(e,A,a,r,s,c)}},{key:"_arrangeStoreyMapCamera",value:function(e){var t=this.viewer,i=t.scene.camera,r=this._fitStoreyMaps?e.storeyAABB:e.modelAABB,s=re.getAABB3Center(r),n=uF;n[0]=s[0]+.5*i.worldUp[0],n[1]=s[1]+.5*i.worldUp[1],n[2]=s[2]+.5*i.worldUp[2];var o=i.worldForward;t.cameraFlight.jumpTo({eye:n,look:s,up:o});var a=(r[3]-r[0])/2,l=(r[4]-r[1])/2,u=(r[5]-r[2])/2,c=-a,A=+a,h=-l,d=+l,p=-u,f=+u;t.camera.customProjection.matrix=re.orthoMat4c(c,A,p,f,h,d,cF),t.camera.projection="customProjection"}},{key:"pickStoreyMap",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=e.storeyId,s=this.storeys[r];if(!s)return this.error("IfcBuildingStorey not found with this ID: "+r),null;var n=1-t[0]/e.width,o=1-t[1]/e.height,a=this._fitStoreyMaps?s.storeyAABB:s.modelAABB,l=a[0],u=a[1],c=a[2],A=a[3],h=a[4],d=a[5],p=A-l,f=h-u,v=d-c,g=re.vec3([l+p*n,u+.5*f,c+v*o]),m=re.vec3([0,-1,0]),_=re.addVec3(g,m,uF),y=this.viewer.camera.worldForward,b=re.lookAtMat4v(g,_,y,cF),x=this.viewer.scene.pick({pickSurface:i.pickSurface,pickInvisible:!0,matrix:b});return x}},{key:"storeyMapToWorldPos",value:function(e,t){var i=e.storeyId,r=this.storeys[i];if(!r)return this.error("IfcBuildingStorey not found with this ID: "+i),null;var s=1-t[0]/e.width,n=1-t[1]/e.height,o=this._fitStoreyMaps?r.storeyAABB:r.modelAABB,a=o[0],l=o[1],u=o[2],c=o[3],A=o[4],h=o[5],d=c-a,p=A-l,f=h-u,v=re.vec3([a+d*s,l+.5*p,u+f*n]);return v}},{key:"getStoreyContainingWorldPos",value:function(e){for(var t in this.storeys){var i=this.storeys[t];if(re.point3AABB3AbsoluteIntersect(i.storeyAABB,e))return t}return null}},{key:"getStoreyInVerticalRange",value:function(e){for(var t in this.storeys){var i=this.storeys[t],r=[0,0,0,0,0,0],s=[0,0,0];if(r[1]=i.storeyAABB[1],r[4]=i.storeyAABB[4],s[1]=e[1],re.point3AABB3AbsoluteIntersect(r,s))return t}return null}},{key:"isPositionAboveOrBelowBuilding",value:function(e){var t=Object.keys(this.storeys),i=[t[0],t[t.length-1]];return e[1]this.storeys[i[1]].storeyAABB[4]?i[1]:null}},{key:"worldPosToStoreyMap",value:function(e,t,i){var r=e.storeyId,s=this.storeys[r];if(!s)return this.error("IfcBuildingStorey not found with this ID: "+r),!1;var n=this._fitStoreyMaps?s.storeyAABB:s.modelAABB,o=n[0],a=n[1],l=n[2],u=n[3]-o,c=n[4]-a,A=n[5]-l,h=this.viewer.camera.worldUp,d=h[0]>h[1]&&h[0]>h[2],p=!d&&h[1]>h[0]&&h[1]>h[2];!d&&!p&&h[2]>h[0]&&(h[2],h[1]);var f=e.width/u,v=p?e.height/A:e.height/c;return i[0]=Math.floor(e.width-(t[0]-o)*f),i[1]=Math.floor(e.height-(t[2]-l)*v),i[0]>=0&&i[0]=0&&i[1]<=e.height}},{key:"worldDirToStoreyMap",value:function(e,t,i){var r=this.viewer.camera,s=r.eye,n=r.look,o=re.subVec3(n,s,uF),a=r.worldUp,l=a[0]>a[1]&&a[0]>a[2],u=!l&&a[1]>a[0]&&a[1]>a[2];!l&&!u&&a[2]>a[0]&&(a[2],a[1]),l?(i[0]=o[1],i[1]=o[2]):u?(i[0]=o[0],i[1]=o[2]):(i[0]=o[0],i[1]=o[1]),re.normalizeVec2(i)}},{key:"destroy",value:function(){this.viewer.scene.off(this._onModelLoaded),f(x(i.prototype),"destroy",this).call(this)}}]),i}(),dF=new Float64Array([0,0,1]),pF=new Float64Array(4),fF=function(){function e(t){B(this,e),this.id=null,this._viewer=t.viewer,this._plugin=t,this._visible=!1,this._pos=re.vec3(),this._origin=re.vec3(),this._rtcPos=re.vec3(),this._baseDir=re.vec3(),this._rootNode=null,this._displayMeshes=null,this._affordanceMeshes=null,this._ignoreNextSectionPlaneDirUpdate=!1,this._createNodes(),this._bindEvents()}return C(e,[{key:"_setSectionPlane",value:function(e){var t=this;this._sectionPlane&&(this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._onSectionPlanePos=null,this._onSectionPlaneDir=null,this._sectionPlane=null),e&&(this.id=e.id,this._setPos(e.pos),this._setDir(e.dir),this._sectionPlane=e,this._onSectionPlanePos=e.on("pos",(function(){t._setPos(t._sectionPlane.pos)})),this._onSectionPlaneDir=e.on("dir",(function(){t._ignoreNextSectionPlaneDirUpdate?t._ignoreNextSectionPlaneDirUpdate=!1:t._setDir(t._sectionPlane.dir)})))}},{key:"sectionPlane",get:function(){return this._sectionPlane}},{key:"_setPos",value:function(e){this._pos.set(e),He(this._pos,this._origin,this._rtcPos),this._rootNode.origin=this._origin,this._rootNode.position=this._rtcPos}},{key:"_setDir",value:function(e){this._baseDir.set(e),this._rootNode.quaternion=re.vec3PairToQuaternion(dF,e,pF)}},{key:"_setSectionPlaneDir",value:function(e){this._sectionPlane&&(this._ignoreNextSectionPlaneDirUpdate=!0,this._sectionPlane.dir=e)}},{key:"setVisible",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[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)}}},{key:"getVisible",value:function(){return this._visible}},{key:"setCulled",value:function(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)}},{key:"_createNodes",value:function(){var e=!1,t=this._viewer.scene,i=.01;this._rootNode=new Ln(t,{position:[0,0,0],scale:[5,5,5]});var r=this._rootNode,s={arrowHead:new Ki(r,yn({radiusTop:.001,radiusBottom:.07,radialSegments:32,heightSegments:1,height:.2,openEnded:!1})),arrowHeadBig:new Ki(r,yn({radiusTop:.001,radiusBottom:.09,radialSegments:32,heightSegments:1,height:.25,openEnded:!1})),axis:new Ki(r,yn({radiusTop:i,radiusBottom:i,radialSegments:20,heightSegments:1,height:1,openEnded:!1}))},n={red:new qi(r,{diffuse:[1,0,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),green:new qi(r,{diffuse:[0,1,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),blue:new qi(r,{diffuse:[0,0,1],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightRed:new er(r,{edges:!1,fill:!0,fillColor:[1,0,0],fillAlpha:.6})};this._displayMeshes={plane:r.addChild(new mn(r,{geometry:new Ki(r,{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 qi(r,{emissive:[0,0,0],diffuse:[0,0,0],backfaces:!0}),opacity:.6,ghosted:!0,pickable:!1,collidable:!0,clippable:!1,visible:!1,scale:[2.4,2.4,1]}),e),planeFrame:r.addChild(new mn(r,{geometry:new Ki(r,uo({center:[0,0,0],radius:1.7,tube:.02,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new qi(r,{emissive:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],shininess:0}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,.1],rotation:[0,0,45]}),e),center:r.addChild(new mn(r,{geometry:new Ki(r,bn({radius:.05})),material:n.center,pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),zAxisArrow:r.addChild(new mn(r,{geometry:s.arrowHead,material:n.blue,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[.8,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),zShaft:r.addChild(new mn(r,{geometry:s.axis,material:n.blue,matrix:function(){var e=re.translateMat4c(0,.5,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[1,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),clippable:!1,pickable:!1,collidable:!0,visible:!1}),e)},this._affordanceMeshes={planeFrame:r.addChild(new mn(r,{geometry:new Ki(r,uo({center:[0,0,0],radius:2,tube:i,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new qi(r,{ambient:[1,1,1],diffuse:[0,0,0],emissive:[1,1,0]}),highlighted:!0,highlightMaterial:new er(r,{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]}),e),zAxisArrow:r.addChild(new mn(r,{geometry:s.arrowHeadBig,material:n.blue,matrix:function(){var e=re.translateMat4c(0,1.1,0,re.identityMat4()),t=re.rotationMat4v(-90*re.DEGTORAD,[.8,0,0],re.identityMat4());return re.mulMat4(t,e,re.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e)}}},{key:"_bindEvents",value:function(){var e=this,t=this._rootNode,i=re.vec2(),r=this._viewer.camera,s=this._viewer.scene,n=0,o=!1,a=re.vec3([0,0,0]),l=-1;this._onCameraViewMatrix=s.camera.on("viewMatrix",(function(){})),this._onCameraProjMatrix=s.camera.on("projMatrix",(function(){})),this._onSceneTick=s.on("tick",(function(){o=!1;var i=Math.abs(re.lenVec3(re.subVec3(s.camera.eye,e._pos,a)));if(i!==l&&"perspective"===r.projection){var u=.07*(Math.tan(r.perspective.fov*re.DEGTORAD)*i);t.scale=[u,u,u],l=i}if("ortho"===r.projection){var A=r.ortho.scale/10;t.scale=[A,A,A],l=i}0!==n&&(c(n),n=0)}));var u=function(){var e=new Float64Array(2);return function(t){if(t){for(var i=t.target,r=0,s=0;i.offsetParent;)r+=i.offsetLeft,s+=i.offsetTop,i=i.offsetParent;e[0]=t.pageX-r,e[1]=t.pageY-s}else t=window.event,e[0]=t.x,e[1]=t.y;return e}}(),c=function(t){var i=e._sectionPlane.pos,r=e._sectionPlane.dir;re.addVec3(i,re.mulVec3Scalar(r,.1*t*e._plugin.getDragSensitivity(),re.vec3())),e._sectionPlane.pos=i},A=!1;this._plugin._controlElement.addEventListener("mousedown",this._canvasMouseDownListener=function(t){if(t.preventDefault(),e._visible&&(e._viewer.cameraControl.pointerEnabled=!1,1===t.which)){A=!0;var r=u(t);i[0]=r[0],i[1]=r[1]}}),this._plugin._controlElement.addEventListener("mousemove",this._canvasMouseMoveListener=function(t){if(e._visible&&A&&!o){var r=u(t),s=r[0],n=r[1];c(n-i[1]),i[0]=s,i[1]=n}}),this._plugin._controlElement.addEventListener("mouseup",this._canvasMouseUpListener=function(t){e._visible&&(e._viewer.cameraControl.pointerEnabled=!0,A&&(t.which,A=!1))}),this._plugin._controlElement.addEventListener("wheel",this._canvasWheelListener=function(t){e._visible&&(n+=Math.max(-1,Math.min(1,40*-t.deltaY)))});var h,d,p=null;this._plugin._controlElement.addEventListener("touchstart",this._handleTouchStart=function(t){t.stopPropagation(),t.preventDefault(),e._visible&&(h=t.touches[0].clientY,p=h,n=0)}),this._plugin._controlElement.addEventListener("touchmove",this._handleTouchMove=function(t){t.stopPropagation(),t.preventDefault(),e._visible&&(o||(o=!0,d=t.touches[0].clientY,null!==p&&(n+=d-p),p=d))}),this._plugin._controlElement.addEventListener("touchend",this._handleTouchEnd=function(t){t.stopPropagation(),t.preventDefault(),e._visible&&(h=null,d=null,n=0)})}},{key:"_destroy",value:function(){this._unbindEvents(),this._destroyNodes()}},{key:"_unbindEvents",value:function(){var e=this._viewer,t=e.scene,i=t.canvas.canvas,r=e.camera,s=this._plugin._controlElement;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.removeEventListener("touchstart",this._handleTouchStart),s.removeEventListener("touchmove",this._handleTouchMove),s.removeEventListener("touchend",this._handleTouchEnd),r.off(this._onCameraViewMatrix),r.off(this._onCameraProjMatrix)}},{key:"_destroyNodes",value:function(){this._setSectionPlane(null),this._rootNode.destroy(),this._displayMeshes={},this._affordanceMeshes={}}}]),e}(),vF=function(){function e(t,i,r){var s=this;B(this,e),this.id=r.id,this._sectionPlane=r,this._mesh=new mn(i,{id:r.id,geometry:new Ki(i,Xi({xSize:.5,ySize:.5,zSize:.001})),material:new qi(i,{emissive:[1,1,1],diffuse:[0,0,0],backfaces:!1}),edgeMaterial:new ir(i,{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),highlightMaterial:new er(i,{fill:!0,fillColor:[.5,1,.5],fillAlpha:.7,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),selectedMaterial:new er(i,{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});var n=re.vec3([0,0,0]),o=re.vec3(),a=re.vec3([0,0,1]),l=re.vec4(4),u=re.vec3(),c=function(){var e=s._sectionPlane.scene.center,t=[-s._sectionPlane.dir[0],-s._sectionPlane.dir[1],-s._sectionPlane.dir[2]];re.subVec3(e,s._sectionPlane.pos,n);var i=-re.dotVec3(t,n);re.normalizeVec3(t),re.mulVec3Scalar(t,i,o);var r=re.vec3PairToQuaternion(a,s._sectionPlane.dir,l);u[0]=.1*o[0],u[1]=.1*o[1],u[2]=.1*o[2],s._mesh.quaternion=r,s._mesh.position=u};this._onSectionPlanePos=this._sectionPlane.on("pos",c),this._onSectionPlaneDir=this._sectionPlane.on("dir",c),this._highlighted=!1,this._selected=!1}return C(e,[{key:"setHighlighted",value:function(e){this._highlighted=!!e,this._mesh.highlighted=this._highlighted,this._mesh.highlightMaterial.fillColor=e?[0,.7,0]:[0,0,0]}},{key:"getHighlighted",value:function(){return this._highlighted}},{key:"setSelected",value:function(e){this._selected=!!e,this._mesh.edgeMaterial.edgeWidth=e?3:1,this._mesh.highlightMaterial.edgeWidth=e?3:1}},{key:"getSelected",value:function(){return this._selected}},{key:"destroy",value:function(){this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._mesh.destroy()}}]),e}(),gF=function(){function e(t,i){var r=this;if(B(this,e),!(i.onHoverEnterPlane&&i.onHoverLeavePlane&&i.onClickedNothing&&i.onClickedPlane))throw"Missing config(s): onHoverEnterPlane, onHoverLeavePlane, onClickedNothing || onClickedPlane";this.plugin=t,this._viewer=t.viewer,this._onHoverEnterPlane=i.onHoverEnterPlane,this._onHoverLeavePlane=i.onHoverLeavePlane,this._onClickedNothing=i.onClickedNothing,this._onClickedPlane=i.onClickedPlane,this._visible=!0,this._planes={},this._canvas=i.overviewCanvas,this._scene=new hr(this._viewer,{canvasId:this._canvas.id,transparent:!0}),this._scene.clearLights(),new Ti(this._scene,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new Ti(this._scene,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new Ti(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;var s=this._scene.camera,n=re.rotationMat4c(-90*re.DEGTORAD,1,0,0),o=re.vec3(),a=re.vec3(),l=re.vec3();this._synchCamera=function(){var e=r._viewer.camera.eye,t=r._viewer.camera.look,i=r._viewer.camera.up;re.mulVec3Scalar(re.normalizeVec3(re.subVec3(e,t,o)),7),r._zUp?(re.transformVec3(n,o,a),re.transformVec3(n,i,l),s.look=[0,0,0],s.eye=re.transformVec3(n,o,a),s.up=re.transformPoint3(n,i,l)):(s.look=[0,0,0],s.eye=o,s.up=i)},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",(function(e){r._scene.camera.perspective.fov=e}));var u=null;this._onInputMouseMove=this._scene.input.on("mousemove",(function(e){var t=r._scene.pick({canvasPos:e});if(t){if(!u||t.entity.id!==u.id){if(u)r._planes[u.id]&&r._onHoverLeavePlane(u.id);u=t.entity,r._planes[u.id]&&r._onHoverEnterPlane(u.id)}}else u&&(r._onHoverLeavePlane(u.id),u=null)})),this._scene.canvas.canvas.addEventListener("mouseup",this._onCanvasMouseUp=function(){u?r._planes[u.id]&&r._onClickedPlane(u.id):r._onClickedNothing()}),this._scene.canvas.canvas.addEventListener("mouseout",this._onCanvasMouseOut=function(){u&&(r._onHoverLeavePlane(u.id),u=null)}),this.setVisible(i.overviewVisible)}return C(e,[{key:"addSectionPlane",value:function(e){this._planes[e.id]=new vF(this,this._scene,e)}},{key:"setPlaneHighlighted",value:function(e,t){var i=this._planes[e];i&&i.setHighlighted(t)}},{key:"setPlaneSelected",value:function(e,t){var i=this._planes[e];i&&i.setSelected(t)}},{key:"removeSectionPlane",value:function(e){var t=this._planes[e.id];t&&(t.destroy(),delete this._planes[e.id])}},{key:"setVisible",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this._visible=e,this._canvas.style.visibility=e?"visible":"hidden"}},{key:"getVisible",value:function(){return this._visible}},{key:"destroy",value:function(){this._viewer.camera.off(this._onViewerCameraMatrix),this._viewer.camera.off(this._onViewerCameraWorldAxis),this._viewer.camera.perspective.off(this._onViewerCameraFOV),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()}}]),e}(),mF=re.AABB3(),_F=re.vec3(),yF=function(e){g(i,Ue);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(B(this,i),(r=t.call(this,"FaceAlignedSectionPlanesPlugin",e))._freeControls=[],r._sectionPlanes=e.scene.sectionPlanes,r._controls={},r._shownControlId=null,r._dragSensitivity=s.dragSensitivity||1,null!==s.overviewCanvasId&&void 0!==s.overviewCanvasId){var n=document.getElementById(s.overviewCanvasId);n?r._overview=new gF(b(r),{overviewCanvas:n,visible:s.overviewVisible,onHoverEnterPlane:function(e){r._overview.setPlaneHighlighted(e,!0)},onHoverLeavePlane:function(e){r._overview.setPlaneHighlighted(e,!1)},onClickedPlane:function(e){if(r.getShownControl()!==e){r.showControl(e);var t=r.sectionPlanes[e].pos;mF.set(r.viewer.scene.aabb),re.getAABB3Center(mF,_F),mF[0]+=t[0]-_F[0],mF[1]+=t[1]-_F[1],mF[2]+=t[2]-_F[2],mF[3]+=t[0]-_F[0],mF[4]+=t[1]-_F[1],mF[5]+=t[2]-_F[2],r.viewer.cameraFlight.flyTo({aabb:mF,fitFOV:65})}else r.hideControl()},onClickedNothing:function(){r.hideControl()}}):r.warn("Can't find overview canvas: '"+s.overviewCanvasId+"' - will create plugin without overview")}return null===s.controlElementId||void 0===s.controlElementId?r.error("Parameter expected: controlElementId"):(r._controlElement=document.getElementById(s.controlElementId),r._controlElement||r.warn("Can't find control element: '"+s.controlElementId+"' - will create plugin without control element")),r._onSceneSectionPlaneCreated=e.scene.on("sectionPlaneCreated",(function(e){r._sectionPlaneCreated(e)})),r}return C(i,[{key:"setDragSensitivity",value:function(e){this._dragSensitivity=e||1}},{key:"getDragSensitivity",value:function(){return this._dragSensitivity}},{key:"setOverviewVisible",value:function(e){this._overview&&this._overview.setVisible(e)}},{key:"getOverviewVisible",value:function(){if(this._overview)return this._overview.getVisible()}},{key:"sectionPlanes",get:function(){return this._sectionPlanes}},{key:"createSectionPlane",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};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);var t=new Pn(this.viewer.scene,{id:e.id,pos:e.pos,dir:e.dir,active:!0});return t}},{key:"_sectionPlaneCreated",value:function(e){var t=this,i=this._freeControls.length>0?this._freeControls.pop():new fF(this);i._setSectionPlane(e),i.setVisible(!1),this._controls[e.id]=i,this._overview&&this._overview.addSectionPlane(e),e.once("destroyed",(function(){t._sectionPlaneDestroyed(e)}))}},{key:"flipSectionPlanes",value:function(){var e=this.viewer.scene.sectionPlanes;for(var t in e){e[t].flipDir()}}},{key:"showControl",value:function(e){var 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)}},{key:"getShownControl",value:function(){return this._shownControlId}},{key:"hideControl",value:function(){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}},{key:"destroySectionPlane",value:function(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)}},{key:"_sectionPlaneDestroyed",value:function(e){this._overview&&this._overview.removeSectionPlane(e);var t=this._controls[e.id];t&&(t.setVisible(!1),t._setSectionPlane(null),delete this._controls[e.id],this._freeControls.push(t))}},{key:"clear",value:function(){for(var e=Object.keys(this._sectionPlanes),t=0,i=e.length;t0&&void 0!==arguments[0]?arguments[0]:{};B(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getSTL",value:function(e,t,i){e=this._cacheBusterURL(e);var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.responseType="arraybuffer",r.onreadystatechange=function(){4===r.readyState&&(200===r.status?t(r.response):i(r.statusText))},r.send(null)}}]),e}(),wF=re.vec3(),BF=function(){function e(){B(this,e)}return C(e,[{key:"load",value:function(e,t,i,r,s,n){r=r||{};var o=e.viewer.scene.canvas.spinner;o.processes++,e.dataSource.getSTL(i,(function(i){!function(e,t,i,r){try{var s=kF(i);PF(s)?CF(e,s,t,r):MF(e,FF(i),t,r)}catch(e){t.fire("error",e)}}(e,t,i,r);try{var a=kF(i);PF(a)?CF(e,a,t,r):MF(e,FF(i),t,r),o.processes--,we.scheduleTask((function(){t.fire("loaded",!0,!1)})),s&&s()}catch(i){o.processes--,e.error(i),n&&n(i),t.fire("error",i)}}),(function(i){o.processes--,e.error(i),n&&n(i),t.fire("error",i)}))}},{key:"parse",value:function(e,t,i,r){var s=e.viewer.scene.canvas.spinner;s.processes++;try{var n=kF(i);PF(n)?CF(e,n,t,r):MF(e,FF(i),t,r),s.processes--,we.scheduleTask((function(){t.fire("loaded",!0,!1)}))}catch(e){s.processes--,t.fire("error",e)}}}]),e}();function PF(e){var t=new DataView(e);if(84+50*t.getUint32(80,!0)===t.byteLength)return!0;for(var i=[115,111,108,105,100],r=0;r<5;r++)if(i[r]!==t.getUint8(r,!1))return!0;return!1}function CF(e,t,i,r){for(var s,n,o,a,l,u,c,A=new DataView(t),h=A.getUint32(80,!0),d=!1,p=null,f=null,v=null,g=!1,m=0;m<70;m++)1129270351===A.getUint32(m,!1)&&82===A.getUint8(m+4)&&61===A.getUint8(m+5)&&(d=!0,a=[],l=A.getUint8(m+6)/255,u=A.getUint8(m+7)/255,c=A.getUint8(m+8)/255,A.getUint8(m+9));for(var _=new Nn(i,{roughness:.5}),y=[],b=[],x=r.splitMeshes,w=0;w>5&31)/31,o=(E>>10&31)/31):(s=l,n=u,o=c),(x&&s!==p||n!==f||o!==v)&&(null!==p&&(g=!0),p=s,f=n,v=o)}for(var F=1;F<=3;F++){var k=B+12*F;y.push(A.getFloat32(k,!0)),y.push(A.getFloat32(k+4,!0)),y.push(A.getFloat32(k+8,!0)),b.push(P,C,M),d&&a.push(s,n,o,1)}x&&g&&(EF(i,y,b,a,_,r),y=[],b=[],a=a?[]:null,g=!1)}y.length>0&&EF(i,y,b,a,_,r)}function MF(e,t,i,r){for(var s,n,o,a,l,u,c,A=/facet([\s\S]*?)endfacet/g,h=0,d=/[\s]+([+-]?(?:\d+.\d+|\d+.|\d+|.\d+)(?:[eE][+-]?\d+)?)/.source,p=new RegExp("vertex"+d+d+d,"g"),f=new RegExp("normal"+d+d+d,"g"),v=[],g=[];null!==(a=A.exec(t));){for(l=0,u=0,c=a[0];null!==(a=f.exec(c));)s=parseFloat(a[1]),n=parseFloat(a[2]),o=parseFloat(a[3]),u++;for(;null!==(a=p.exec(c));)v.push(parseFloat(a[1]),parseFloat(a[2]),parseFloat(a[3])),g.push(s,n,o),l++;1!==u&&e.error("Error in normal of face "+h),3!==l&&e.error("Error in positions of face "+h),h++}EF(i,v,g,null,new Nn(i,{roughness:.5}),r)}function EF(e,t,i,r,s,n){for(var o=new Int32Array(t.length/3),a=0,l=o.length;a0?i:null,r=r&&r.length>0?r:null,n.smoothNormals&&re.faceToVertexNormals(t,i,n);var u=wF;je(t,t,u);var c=new Ki(e,{primitive:"triangles",positions:t,normals:i,colors:r,indices:o}),A=new mn(e,{origin:0!==u[0]||0!==u[1]||0!==u[2]?u:null,geometry:c,material:s,edges:n.edges});e.addChild(A)}function FF(e){return"string"!=typeof e?function(e){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);for(var t="",i=0,r=e.length;i1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),(r=t.call(this,"STLLoader",e,s))._sceneGraphLoader=new BF,r.dataSource=s.dataSource,r}return C(i,[{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new xF}},{key:"load",value:function(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);var t=new Ln(this.viewer.scene,he.apply(e,{isModel:!0})),i=e.src,r=e.stl;return i||r?(i?this._sceneGraphLoader.load(this,t,i,e):this._sceneGraphLoader.parse(this,t,r,e),t):(this.error("load() param expected: either 'src' or 'stl'"),t)}}]),i}(),DF=function(){function e(){B(this,e)}return C(e,[{key:"createRootNode",value:function(){return document.createElement("ul")}},{key:"createNodeElement",value:function(e,t,i,r,s){var n=document.createElement("li");if(n.id=e.nodeId,e.xrayed&&n.classList.add("xrayed-node"),e.children.length>0){var o=document.createElement("a");o.href="#",o.id="switch-".concat(e.nodeId),o.textContent="+",o.classList.add("plus"),t&&o.addEventListener("click",t),n.appendChild(o)}var a=document.createElement("input");a.id="checkbox-".concat(e.nodeId),a.type="checkbox",a.checked=e.checked,a.style["pointer-events"]="all",i&&a.addEventListener("change",i),n.appendChild(a);var l=document.createElement("span");return l.textContent=e.title,n.appendChild(l),r&&(l.oncontextmenu=r),s&&(l.onclick=s),n}},{key:"createDisabledNodeElement",value:function(e){var t=document.createElement("li"),i=document.createElement("a");i.href="#",i.textContent="!",i.classList.add("warn"),i.classList.add("warning"),t.appendChild(i);var r=document.createElement("span");return r.textContent=e,t.appendChild(r),t}},{key:"addChildren",value:function(e,t){var i=document.createElement("ul");t.forEach((function(e){i.appendChild(e)})),e.parentElement.appendChild(i)}},{key:"expand",value:function(e,t,i){e.classList.remove("plus"),e.classList.add("minus"),e.textContent="-",e.removeEventListener("click",t),e.addEventListener("click",i)}},{key:"collapse",value:function(e,t,i){if(e){var r=e.parentElement;if(r){var s=r.querySelector("ul");s&&(r.removeChild(s),e.classList.remove("minus"),e.classList.add("plus"),e.textContent="+",e.removeEventListener("click",i),e.addEventListener("click",t))}}}},{key:"isExpanded",value:function(e){return void 0!==e.parentElement.getElementsByTagName("li")[0]}},{key:"getId",value:function(e){return e.parentElement.id}},{key:"getIdFromCheckbox",value:function(e){return e.id.replace("checkbox-","")}},{key:"getSwitchElement",value:function(e){return document.getElementById("switch-".concat(e))}},{key:"isChecked",value:function(e){return e.checked}},{key:"setCheckbox",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=document.getElementById("checkbox-".concat(e));r&&(t!==r.checked&&(r.checked=t),i!==r.indeterminate&&(r.indeterminate=i,i&&(r.checked=!1)))}},{key:"setXRayed",value:function(e,t){var i=document.getElementById(e);i&&(t?i.classList.add("xrayed-node"):i.classList.remove("xrayed-node"))}},{key:"setHighlighted",value:function(e,t){var i=document.getElementById(e);i&&(t?(i.scrollIntoView({block:"center"}),i.classList.add("highlighted-node")):i.classList.remove("highlighted-node"))}}]),e}(),SF=[],TF=function(e){g(i,Ue);var t=_(i);function i(e){var r,s,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};B(this,i),(s=t.call(this,"TreeViewPlugin",e)).errors=[],s.valid=!0;var o=n.containerElement||document.getElementById(n.containerElementId);if(!(o instanceof HTMLElement))return s.error("Mandatory config expected: valid containerElementId or containerElement"),y(s);for(var a=0;;a++)if(!SF[a]){SF[a]=b(s),s._index=a,s._id="tree-".concat(a);break}if(s._containerElement=o,s._metaModels={},s._autoAddModels=!1!==n.autoAddModels,s._autoExpandDepth=n.autoExpandDepth||0,s._sortNodes=!1!==n.sortNodes,s._viewer=e,s._rootElement=null,s._muteSceneEvents=!1,s._muteTreeEvents=!1,s._rootNodes=[],s._objectNodes={},s._nodeNodes={},s._rootNames={},s._sortNodes=n.sortNodes,s._pruneEmptyNodes=n.pruneEmptyNodes,s._showListItemElementId=null,s._renderService=n.renderService||new DF,s._showIndeterminate=null!==(r=n.showIndeterminate)&&void 0!==r&&r,!s._renderService)throw new Error("TreeViewPlugin: no render service set");if(s._containerElement.oncontextmenu=function(e){e.preventDefault()},s._onObjectVisibility=s._viewer.scene.on("objectVisibility",(function(e){if(!s._muteSceneEvents){var t=e.id,i=s._objectNodes[t];if(i){var r=e.visible;if(r!==i.checked){s._muteTreeEvents=!0,i.checked=r,r?i.numVisibleEntities++:i.numVisibleEntities--,s._renderService.setCheckbox(i.nodeId,r);for(var n=i.parent;n;){n.checked=r,r?n.numVisibleEntities++:n.numVisibleEntities--;var o=s._showIndeterminate&&n.numVisibleEntities>0&&n.numVisibleEntities0,o),n=n.parent}s._muteTreeEvents=!1}}}})),s._onObjectXrayed=s._viewer.scene.on("objectXRayed",(function(e){if(!s._muteSceneEvents){var t=e.id,i=s._objectNodes[t];if(i){s._muteTreeEvents=!0;var r=e.xrayed;r!==i.xrayed&&(i.xrayed=r,s._renderService.setXRayed(i.nodeId,r),s._muteTreeEvents=!1)}}})),s._switchExpandHandler=function(e){e.preventDefault(),e.stopPropagation();var t=e.target;s._expandSwitchElement(t)},s._switchCollapseHandler=function(e){e.preventDefault(),e.stopPropagation();var t=e.target;s._collapseSwitchElement(t)},s._checkboxChangeHandler=function(e){if(!s._muteTreeEvents){s._muteSceneEvents=!0;var t=e.target,i=s._renderService.isChecked(t),r=s._renderService.getIdFromCheckbox(t),n=s._nodeNodes[r],o=s._viewer.scene.objects,a=0;s._withNodeTree(n,(function(e){var t=e.objectId,r=o[t],n=0===e.children.length;e.numVisibleEntities=i?e.numEntities:0,n&&i!==e.checked&&a++,e.checked=i,s._renderService.setCheckbox(e.nodeId,i),r&&(r.visible=i)}));for(var l=n.parent;l;){l.checked=i,i?l.numVisibleEntities+=a:l.numVisibleEntities-=a;var u=s._showIndeterminate&&l.numVisibleEntities>0&&l.numVisibleEntities0,u),l=l.parent}s._muteSceneEvents=!1}},s._hierarchy=n.hierarchy||"containment",s._autoExpandDepth=n.autoExpandDepth||0,s._autoAddModels){for(var l=Object.keys(s.viewer.metaScene.metaModels),u=0,c=l.length;u1&&void 0!==arguments[1]?arguments[1]:{};if(this._containerElement){var r=this.viewer.scene.models[e];if(!r)throw"Model not found: "+e;var s=this.viewer.metaScene.metaModels[e];s?this._metaModels[e]?this.warn("Model already added: "+e):(this._metaModels[e]=s,i&&i.rootName&&(this._rootNames[e]=i.rootName),r.on("destroyed",(function(){t.removeModel(r.id)})),this._createNodes()):this.error("MetaModel not found: "+e)}}},{key:"removeModel",value:function(e){this._containerElement&&(this._metaModels[e]&&(this._rootNames[e]&&delete this._rootNames[e],delete this._metaModels[e],this._createNodes()))}},{key:"showNode",value:function(e){this.unShowNode();var t=this._objectNodes[e];if(t){this.collapse();var i=t.nodeId,r=this._renderService.getSwitchElement(i);if(r)return this._expandSwitchElement(r),r.scrollIntoView(),!0;var s=[];s.unshift(t);for(var n=t.parent;n;)s.unshift(n),n=n.parent;for(var o=0,a=s.length;o0;return this.valid}},{key:"_validateMetaModelForStoreysHierarchy",value:function(){return!0}},{key:"_createEnabledNodes",value:function(){switch(this._pruneEmptyNodes&&this._findEmptyNodes(),this._hierarchy){case"storeys":this._createStoreysNodes(),0===this._rootNodes.length&&this.error("Failed to build storeys hierarchy");break;case"types":this._createTypesNodes();break;default:this._createContainmentNodes()}this._sortNodes&&this._doSortNodes(),this._synchNodesToEntities(),this._createTrees(),this.expandToDepth(this._autoExpandDepth)}},{key:"_createDisabledNodes",value:function(){var e=this._renderService.createRootNode();this._rootElement=e,this._containerElement.appendChild(e);var t=this._viewer.metaScene.rootMetaObjects;for(var i in t){var r=t[i],s=r.type,n=r.name,o=n&&""!==n&&"Undefined"!==n&&"Default"!==n?n:s,a=this._renderService.createDisabledNodeElement(o);e.appendChild(a)}}},{key:"_findEmptyNodes",value:function(){var e=this._viewer.metaScene.rootMetaObjects;for(var t in e)this._findEmptyNodes2(e[t])}},{key:"_findEmptyNodes2",value:function(e){var t=this.viewer,i=t.scene,r=e.children,s=e.id,n=i.objects[s];if(e._countEntities=0,n&&e._countEntities++,r)for(var o=0,a=r.length;os.aabb[n]?-1:e.aabb[n]r?1:0}},{key:"_synchNodesToEntities",value:function(){for(var e=Object.keys(this.viewer.metaScene.metaObjects),t=this._viewer.metaScene.metaObjects,i=this._viewer.scene.objects,r=0,s=e.length;r0){for(var e=0;e1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),(r=t.call(this,"ViewCull",e))._objectCullStates=UF(e.scene),r._maxTreeDepth=s.maxTreeDepth||8,r._modelInfos={},r._frustum=new Ie,r._kdRoot=null,r._frustumDirty=!1,r._kdTreeDirty=!1,r._onViewMatrix=e.scene.camera.on("viewMatrix",(function(){r._frustumDirty=!0})),r._onProjMatrix=e.scene.camera.on("projMatMatrix",(function(){r._frustumDirty=!0})),r._onModelLoaded=e.scene.on("modelLoaded",(function(e){var t=r.viewer.scene.models[e];t&&r._addModel(t)})),r._onSceneTick=e.scene.on("tick",(function(){r._doCull()})),r}return C(i,[{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"_addModel",value:function(e){var t=this,i={model:e,onDestroyed:e.on("destroyed",(function(){t._removeModel(e)}))};this._modelInfos[e.id]=i,this._kdTreeDirty=!0}},{key:"_removeModel",value:function(e){var t=this._modelInfos[e.id];t&&(t.model.off(t.onDestroyed),delete this._modelInfos[e.id],this._kdTreeDirty=!0)}},{key:"_doCull",value:function(){var e=this._frustumDirty||this._kdTreeDirty;if(this._frustumDirty&&this._buildFrustum(),this._kdTreeDirty&&this._buildKDTree(),e){var t=this._kdRoot;t&&this._visitKDNode(t)}}},{key:"_buildFrustum",value:function(){var e=this.viewer.scene.camera;De(this._frustum,e.viewMatrix,e.projMatrix),this._frustumDirty=!1}},{key:"_buildKDTree",value:function(){var e=this.viewer.scene;this._kdRoot,this._kdRoot={aabb:e.getAABB(),intersection:Ie.INTERSECT};for(var t=0,i=this._objectCullStates.numObjects;t=this._maxTreeDepth)return e.objects=e.objects||[],e.objects.push(i),void re.expandAABB3(e.aabb,s);if(e.left&&re.containsAABB3(e.left.aabb,s))this._insertEntityIntoKDTree(e.left,t,i,r+1);else if(e.right&&re.containsAABB3(e.right.aabb,s))this._insertEntityIntoKDTree(e.right,t,i,r+1);else{var n=e.aabb;OF[0]=n[3]-n[0],OF[1]=n[4]-n[1],OF[2]=n[5]-n[2];var o=0;if(OF[1]>OF[o]&&(o=1),OF[2]>OF[o]&&(o=2),!e.left){var a=n.slice();if(a[o+3]=(n[o]+n[o+3])/2,e.left={aabb:a,intersection:Ie.INTERSECT},re.containsAABB3(a,s))return void this._insertEntityIntoKDTree(e.left,t,i,r+1)}if(!e.right){var l=n.slice();if(l[o]=(n[o]+n[o+3])/2,e.right={aabb:l,intersection:Ie.INTERSECT},re.containsAABB3(l,s))return void this._insertEntityIntoKDTree(e.right,t,i,r+1)}e.objects=e.objects||[],e.objects.push(i),re.expandAABB3(e.aabb,s)}}},{key:"_visitKDNode",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ie.INTERSECT;if(t===Ie.INTERSECT||e.intersects!==t){t===Ie.INTERSECT&&(t=Se(this._frustum,e.aabb),e.intersects=t);var i=t===Ie.OUTSIDE,r=e.objects;if(r&&r.length>0)for(var s=0,n=r.length;s0&&void 0!==arguments[0]?arguments[0]:{};B(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getManifest",value:function(e,t,i){he.loadJSON(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}},{key:"getMetaModel",value:function(e,t,i){he.loadJSON(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}},{key:"getXKT",value:function(e,t,i){var r=function(){};t=t||r,i=i||r;var s=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(s){var n=!!s[2],o=s[3];o=window.decodeURIComponent(o),n&&(o=window.atob(o));try{for(var a=new ArrayBuffer(o.length),l=new Uint8Array(a),u=0;u=0;)e[t]=0}var i=new Uint8Array([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]),r=new Uint8Array([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]),s=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),n=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),o=new Array(576);t(o);var a=new Array(60);t(a);var l=new Array(512);t(l);var u=new Array(256);t(u);var c=new Array(29);t(c);var A,h,d,p=new Array(30);function f(e,t,i,r,s){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=r,this.max_length=s,this.has_stree=e&&e.length}function v(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}t(p);var g=function(e){return e<256?l[e]:l[256+(e>>>7)]},m=function(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},_=function(e,t,i){e.bi_valid>16-i?(e.bi_buf|=t<>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<>>=1,i<<=1}while(--t>0);return i>>>1},x=function(e,t,i){var r,s,n=new Array(16),o=0;for(r=1;r<=15;r++)o=o+i[r-1]<<1,n[r]=o;for(s=0;s<=t;s++){var a=e[2*s+1];0!==a&&(e[2*s]=b(n[a]++,a))}},B=function(e){var t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},P=function(e){e.bi_valid>8?m(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},C=function(e,t,i,r){var s=2*t,n=2*i;return e[s]>1;i>=1;i--)M(e,n,i);s=l;do{i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],M(e,n,1),r=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=r,n[2*s]=n[2*i]+n[2*r],e.depth[s]=(e.depth[i]>=e.depth[r]?e.depth[i]:e.depth[r])+1,n[2*i+1]=n[2*r+1]=s,e.heap[1]=s++,M(e,n,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var i,r,s,n,o,a,l=t.dyn_tree,u=t.max_code,c=t.stat_desc.static_tree,A=t.stat_desc.has_stree,h=t.stat_desc.extra_bits,d=t.stat_desc.extra_base,p=t.stat_desc.max_length,f=0;for(n=0;n<=15;n++)e.bl_count[n]=0;for(l[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;i<573;i++)(n=l[2*l[2*(r=e.heap[i])+1]+1]+1)>p&&(n=p,f++),l[2*r+1]=n,r>u||(e.bl_count[n]++,o=0,r>=d&&(o=h[r-d]),a=l[2*r],e.opt_len+=a*(n+o),A&&(e.static_len+=a*(c[2*r+1]+o)));if(0!==f){do{for(n=p-1;0===e.bl_count[n];)n--;e.bl_count[n]--,e.bl_count[n+1]+=2,e.bl_count[p]--,f-=2}while(f>0);for(n=p;0!==n;n--)for(r=e.bl_count[n];0!==r;)(s=e.heap[--i])>u||(l[2*s+1]!==n&&(e.opt_len+=(n-l[2*s+1])*l[2*s],l[2*s+1]=n),r--)}}(e,t),x(n,u,e.bl_count)},k=function(e,t,i){var r,s,n=-1,o=t[1],a=0,l=7,u=4;for(0===o&&(l=138,u=3),t[2*(i+1)+1]=65535,r=0;r<=i;r++)s=o,o=t[2*(r+1)+1],++a>=7;v<30;v++)for(p[v]=g<<7,e=0;e<1<0?(2===e.strm.data_type&&(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 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0}(e)),F(e,e.l_desc),F(e,e.d_desc),u=function(e){var t;for(k(e,e.dyn_ltree,e.l_desc.max_code),k(e,e.dyn_dtree,e.d_desc.max_code),F(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*n[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),s=e.opt_len+3+7>>>3,(l=e.static_len+3+7>>>3)<=s&&(s=l)):s=l=i+5,i+4<=s&&-1!==t?S(e,t,i,r):4===e.strategy||l===s?(_(e,2+(r?1:0),3),E(e,o,a)):(_(e,4+(r?1:0),3),function(e,t,i,r){var s;for(_(e,t-257,5),_(e,i-1,5),_(e,r-4,4),s=0;s>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(u[i]+256+1)]++,e.dyn_dtree[2*g(t)]++),e.sym_next===e.sym_end},O=function(e){_(e,2,3),y(e,256,o),function(e){16===e.bi_valid?(m(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)},N=function(e,t,i,r){for(var s=65535&e|0,n=e>>>16&65535|0,o=0;0!==i;){i-=o=i>2e3?2e3:i;do{n=n+(s=s+t[r++]|0)|0}while(--o);s%=65521,n%=65521}return s|n<<16|0},Q=new Uint32Array(function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var r=0;r<8;r++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}()),V=function(e,t,i,r){var s=Q,n=r+i;e^=-1;for(var o=r;o>>8^s[255&(e^t[o])];return-1^e},H={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"},j={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_MEM_ERROR:-4,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},G=T,z=L,W=R,K=U,X=O,J=j.Z_NO_FLUSH,Y=j.Z_PARTIAL_FLUSH,Z=j.Z_FULL_FLUSH,q=j.Z_FINISH,$=j.Z_BLOCK,ee=j.Z_OK,te=j.Z_STREAM_END,ie=j.Z_STREAM_ERROR,re=j.Z_DATA_ERROR,se=j.Z_BUF_ERROR,ne=j.Z_DEFAULT_COMPRESSION,oe=j.Z_FILTERED,ae=j.Z_HUFFMAN_ONLY,le=j.Z_RLE,ue=j.Z_FIXED,ce=j.Z_UNKNOWN,Ae=j.Z_DEFLATED,he=258,de=262,pe=42,fe=113,ve=666,ge=function(e,t){return e.msg=H[t],t},me=function(e){return 2*e-(e>4?9:0)},_e=function(e){for(var t=e.length;--t>=0;)e[t]=0},ye=function(e){var t,i,r,s=e.w_size;r=t=e.hash_size;do{i=e.head[--r],e.head[r]=i>=s?i-s:0}while(--t);r=t=s;do{i=e.prev[--r],e.prev[r]=i>=s?i-s:0}while(--t)},be=function(e,t,i){return(t<e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,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))},we=function(e,t){W(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,xe(e.strm)},Be=function(e,t){e.pending_buf[e.pending++]=t},Pe=function(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},Ce=function(e,t,i,r){var s=e.avail_in;return s>r&&(s=r),0===s?0:(e.avail_in-=s,t.set(e.input.subarray(e.next_in,e.next_in+s),i),1===e.state.wrap?e.adler=N(e.adler,t,s,i):2===e.state.wrap&&(e.adler=V(e.adler,t,s,i)),e.next_in+=s,e.total_in+=s,s)},Me=function(e,t){var i,r,s=e.max_chain_length,n=e.strstart,o=e.prev_length,a=e.nice_match,l=e.strstart>e.w_size-de?e.strstart-(e.w_size-de):0,u=e.window,c=e.w_mask,A=e.prev,h=e.strstart+he,d=u[n+o-1],p=u[n+o];e.prev_length>=e.good_match&&(s>>=2),a>e.lookahead&&(a=e.lookahead);do{if(u[(i=t)+o]===p&&u[i+o-1]===d&&u[i]===u[n]&&u[++i]===u[n+1]){n+=2,i++;do{}while(u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&no){if(e.match_start=t,o=r,r>=a)break;d=u[n+o-1],p=u[n+o]}}}while((t=A[t&c])>l&&0!=--s);return o<=e.lookahead?o:e.lookahead},Ee=function(e){var t,i,r,s=e.w_size;do{if(i=e.window_size-e.lookahead-e.strstart,e.strstart>=s+(s-de)&&(e.window.set(e.window.subarray(s,s+s-i),0),e.match_start-=s,e.strstart-=s,e.block_start-=s,e.insert>e.strstart&&(e.insert=e.strstart),ye(e),i+=s),0===e.strm.avail_in)break;if(t=Ce(e.strm,e.window,e.strstart+e.lookahead,i),e.lookahead+=t,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=be(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=be(e,e.ins_h,e.window[r+3-1]),e.prev[r&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=r,r++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookaheade.w_size?e.w_size:e.pending_buf_size-5,o=0,a=e.strm.avail_in;do{if(i=65535,s=e.bi_valid+42>>3,e.strm.avail_out(r=e.strstart-e.block_start)+e.strm.avail_in&&(i=r+e.strm.avail_in),i>s&&(i=s),i>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,xe(e.strm),r&&(r>i&&(r=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+r),e.strm.next_out),e.strm.next_out+=r,e.strm.avail_out-=r,e.strm.total_out+=r,e.block_start+=r,i-=r),i&&(Ce(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i)}while(0===o);return(a-=e.strm.avail_in)&&(a>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=a&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-a,e.strm.next_in),e.strstart),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.block_start=e.strstart),e.high_waters&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,s+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),s>e.strm.avail_in&&(s=e.strm.avail_in),s&&(Ce(e.strm,e.window,e.strstart,s),e.strstart+=s,e.insert+=s>e.w_size-e.insert?e.w_size-e.insert:s),e.high_water>3,n=(s=e.pending_buf_size-s>65535?65535:e.pending_buf_size-s)>e.w_size?e.w_size:s,((r=e.strstart-e.block_start)>=n||(r||t===q)&&t!==J&&0===e.strm.avail_in&&r<=s)&&(i=r>s?s:r,o=t===q&&0===e.strm.avail_in&&i===r?1:0,z(e,e.block_start,i,o),e.block_start+=i,xe(e.strm)),o?3:1)},ke=function(e,t){for(var i,r;;){if(e.lookahead=3&&(e.ins_h=be(e,e.ins_h,e.window[e.strstart+3-1]),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-de&&(e.match_length=Me(e,i)),e.match_length>=3)if(r=K(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=be(e,e.ins_h,e.window[e.strstart+3-1]),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=be(e,e.ins_h,e.window[e.strstart+1]);else r=K(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(r&&(we(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===q?(we(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(we(e,!1),0===e.strm.avail_out)?1:2},Ie=function(e,t){for(var i,r,s;;){if(e.lookahead=3&&(e.ins_h=be(e,e.ins_h,e.window[e.strstart+3-1]),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=2,0!==i&&e.prev_length4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){s=e.strstart+e.lookahead-3,r=K(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=s&&(e.ins_h=be(e,e.ins_h,e.window[e.strstart+3-1]),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=2,e.strstart++,r&&(we(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if((r=K(e,0,e.window[e.strstart-1]))&&we(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(r=K(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===q?(we(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(we(e,!1),0===e.strm.avail_out)?1:2};function De(e,t,i,r,s){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=r,this.func=s}var Se=[new De(0,0,0,0,Fe),new De(4,4,8,4,ke),new De(4,5,16,8,ke),new De(4,6,32,32,ke),new De(4,4,16,16,Ie),new De(8,16,32,32,Ie),new De(8,16,128,128,Ie),new De(8,32,128,256,Ie),new De(32,128,258,1024,Ie),new De(32,258,258,4096,Ie)];function Te(){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=Ae,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 Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),_e(this.dyn_ltree),_e(this.dyn_dtree),_e(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),_e(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),_e(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}var Le=function(e){if(!e)return 1;var t=e.state;return!t||t.strm!==e||t.status!==pe&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==fe&&t.status!==ve?1:0},Re=function(e){if(Le(e))return ge(e,ie);e.total_in=e.total_out=0,e.data_type=ce;var t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?pe:fe,e.adler=2===t.wrap?0:1,t.last_flush=-2,G(t),ee},Ue=function(e){var t,i=Re(e);return i===ee&&((t=e.state).window_size=2*t.w_size,_e(t.head),t.max_lazy_match=Se[t.level].max_lazy,t.good_match=Se[t.level].good_length,t.nice_match=Se[t.level].nice_length,t.max_chain_length=Se[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=2,t.match_available=0,t.ins_h=0),i},Oe=function(e,t,i,r,s,n){if(!e)return ie;var o=1;if(t===ne&&(t=6),r<0?(o=0,r=-r):r>15&&(o=2,r-=16),s<1||s>9||i!==Ae||r<8||r>15||t<0||t>9||n<0||n>ue||8===r&&1!==o)return ge(e,ie);8===r&&(r=9);var a=new Te;return e.state=a,a.strm=e,a.status=pe,a.wrap=o,a.gzhead=null,a.w_bits=r,a.w_size=1<$||t<0)return e?ge(e,ie):ie;var i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===ve&&t!==q)return ge(e,0===e.avail_out?se:ie);var r=i.last_flush;if(i.last_flush=t,0!==i.pending){if(xe(e),0===e.avail_out)return i.last_flush=-1,ee}else if(0===e.avail_in&&me(t)<=me(r)&&t!==q)return ge(e,se);if(i.status===ve&&0!==e.avail_in)return ge(e,se);if(i.status===pe&&0===i.wrap&&(i.status=fe),i.status===pe){var s=Ae+(i.w_bits-8<<4)<<8;if(s|=(i.strategy>=ae||i.level<2?0:i.level<6?1:6===i.level?2:3)<<6,0!==i.strstart&&(s|=32),Pe(i,s+=31-s%31),0!==i.strstart&&(Pe(i,e.adler>>>16),Pe(i,65535&e.adler)),e.adler=1,i.status=fe,xe(e),0!==i.pending)return i.last_flush=-1,ee}if(57===i.status)if(e.adler=0,Be(i,31),Be(i,139),Be(i,8),i.gzhead)Be(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),Be(i,255&i.gzhead.time),Be(i,i.gzhead.time>>8&255),Be(i,i.gzhead.time>>16&255),Be(i,i.gzhead.time>>24&255),Be(i,9===i.level?2:i.strategy>=ae||i.level<2?4:0),Be(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(Be(i,255&i.gzhead.extra.length),Be(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=V(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(Be(i,0),Be(i,0),Be(i,0),Be(i,0),Be(i,0),Be(i,9===i.level?2:i.strategy>=ae||i.level<2?4:0),Be(i,3),i.status=fe,xe(e),0!==i.pending)return i.last_flush=-1,ee;if(69===i.status){if(i.gzhead.extra){for(var n=i.pending,o=(65535&i.gzhead.extra.length)-i.gzindex;i.pending+o>i.pending_buf_size;){var a=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+a),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>n&&(e.adler=V(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex+=a,xe(e),0!==i.pending)return i.last_flush=-1,ee;n=0,o-=a}var l=new Uint8Array(i.gzhead.extra);i.pending_buf.set(l.subarray(i.gzindex,i.gzindex+o),i.pending),i.pending+=o,i.gzhead.hcrc&&i.pending>n&&(e.adler=V(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){var u,c=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>c&&(e.adler=V(e.adler,i.pending_buf,i.pending-c,c)),xe(e),0!==i.pending)return i.last_flush=-1,ee;c=0}u=i.gzindexc&&(e.adler=V(e.adler,i.pending_buf,i.pending-c,c)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){var A,h=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>h&&(e.adler=V(e.adler,i.pending_buf,i.pending-h,h)),xe(e),0!==i.pending)return i.last_flush=-1,ee;h=0}A=i.gzindexh&&(e.adler=V(e.adler,i.pending_buf,i.pending-h,h))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(xe(e),0!==i.pending))return i.last_flush=-1,ee;Be(i,255&e.adler),Be(i,e.adler>>8&255),e.adler=0}if(i.status=fe,xe(e),0!==i.pending)return i.last_flush=-1,ee}if(0!==e.avail_in||0!==i.lookahead||t!==J&&i.status!==ve){var d=0===i.level?Fe(i,t):i.strategy===ae?function(e,t){for(var i;;){if(0===e.lookahead&&(Ee(e),0===e.lookahead)){if(t===J)return 1;break}if(e.match_length=0,i=K(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(we(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===q?(we(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(we(e,!1),0===e.strm.avail_out)?1:2}(i,t):i.strategy===le?function(e,t){for(var i,r,s,n,o=e.window;;){if(e.lookahead<=he){if(Ee(e),e.lookahead<=he&&t===J)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&((r=o[s=e.strstart-1])===o[++s]&&r===o[++s]&&r===o[++s])){n=e.strstart+he;do{}while(r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&se.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=K(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=K(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(we(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===q?(we(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(we(e,!1),0===e.strm.avail_out)?1:2}(i,t):Se[i.level].func(i,t);if(3!==d&&4!==d||(i.status=ve),1===d||3===d)return 0===e.avail_out&&(i.last_flush=-1),ee;if(2===d&&(t===Y?X(i):t!==$&&(z(i,0,0,!1),t===Z&&(_e(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),xe(e),0===e.avail_out))return i.last_flush=-1,ee}return t!==q?ee:i.wrap<=0?te:(2===i.wrap?(Be(i,255&e.adler),Be(i,e.adler>>8&255),Be(i,e.adler>>16&255),Be(i,e.adler>>24&255),Be(i,255&e.total_in),Be(i,e.total_in>>8&255),Be(i,e.total_in>>16&255),Be(i,e.total_in>>24&255)):(Pe(i,e.adler>>>16),Pe(i,65535&e.adler)),xe(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?ee:te)},He=function(e){if(Le(e))return ie;var t=e.state.status;return e.state=null,t===fe?ge(e,re):ee},je=function(e,t){var i=t.length;if(Le(e))return ie;var r=e.state,s=r.wrap;if(2===s||1===s&&r.status!==pe||r.lookahead)return ie;if(1===s&&(e.adler=N(e.adler,t,i,0)),r.wrap=0,i>=r.w_size){0===s&&(_e(r.head),r.strstart=0,r.block_start=0,r.insert=0);var n=new Uint8Array(r.w_size);n.set(t.subarray(i-r.w_size,i),0),t=n,i=r.w_size}var o=e.avail_in,a=e.next_in,l=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,Ee(r);r.lookahead>=3;){var u=r.strstart,c=r.lookahead-2;do{r.ins_h=be(r,r.ins_h,r.window[u+3-1]),r.prev[u&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=u,u++}while(--c);r.strstart=u,r.lookahead=2,Ee(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=2,r.match_available=0,e.next_in=a,e.input=l,e.avail_in=o,r.wrap=s,ee},Ge=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},ze=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var i=t.shift();if(i){if("object"!=w(i))throw new TypeError(i+"must be non-object");for(var r in i)Ge(i,r)&&(e[r]=i[r])}}return e},We=function(e){for(var t=0,i=0,r=e.length;i=252?6:Je>=248?5:Je>=240?4:Je>=224?3:Je>=192?2:1;Xe[254]=Xe[254]=1;var Ye=function(e){if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);var t,i,r,s,n,o=e.length,a=0;for(s=0;s>>6,t[n++]=128|63&i):i<65536?(t[n++]=224|i>>>12,t[n++]=128|i>>>6&63,t[n++]=128|63&i):(t[n++]=240|i>>>18,t[n++]=128|i>>>12&63,t[n++]=128|i>>>6&63,t[n++]=128|63&i);return t},Ze=function(e,t){var i,r,s=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));var n=new Array(2*s);for(r=0,i=0;i4)n[r++]=65533,i+=a-1;else{for(o&=2===a?31:3===a?15:7;a>1&&i1?n[r++]=65533:o<65536?n[r++]=o:(o-=65536,n[r++]=55296|o>>10&1023,n[r++]=56320|1023&o)}}}return function(e,t){if(t<65534&&e.subarray&&Ke)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));for(var i="",r=0;re.length&&(t=e.length);for(var i=t-1;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+Xe[e[i]]>t?i:t},$e=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},et=Object.prototype.toString,tt=j.Z_NO_FLUSH,it=j.Z_SYNC_FLUSH,rt=j.Z_FULL_FLUSH,st=j.Z_FINISH,nt=j.Z_OK,ot=j.Z_STREAM_END,at=j.Z_DEFAULT_COMPRESSION,lt=j.Z_DEFAULT_STRATEGY,ut=j.Z_DEFLATED;function ct(e){this.options=ze({level:at,method:ut,chunkSize:16384,windowBits:15,memLevel:8,strategy:lt},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 $e,this.strm.avail_out=0;var i=Ne(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==nt)throw new Error(H[i]);if(t.header&&Qe(this.strm,t.header),t.dictionary){var r;if(r="string"==typeof t.dictionary?Ye(t.dictionary):"[object ArrayBuffer]"===et.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(i=je(this.strm,r))!==nt)throw new Error(H[i]);this._dict_set=!0}}function At(e,t){var i=new ct(t);if(i.push(e,!0),i.err)throw i.msg||H[i.err];return i.result}ct.prototype.push=function(e,t){var i,r,s=this.strm,n=this.options.chunkSize;if(this.ended)return!1;for(r=t===~~t?t:!0===t?st:tt,"string"==typeof e?s.input=Ye(e):"[object ArrayBuffer]"===et.call(e)?s.input=new Uint8Array(e):s.input=e,s.next_in=0,s.avail_in=s.input.length;;)if(0===s.avail_out&&(s.output=new Uint8Array(n),s.next_out=0,s.avail_out=n),(r===it||r===rt)&&s.avail_out<=6)this.onData(s.output.subarray(0,s.next_out)),s.avail_out=0;else{if((i=Ve(s,r))===ot)return s.next_out>0&&this.onData(s.output.subarray(0,s.next_out)),i=He(this.strm),this.onEnd(i),this.ended=!0,i===nt;if(0!==s.avail_out){if(r>0&&s.next_out>0)this.onData(s.output.subarray(0,s.next_out)),s.avail_out=0;else if(0===s.avail_in)break}else this.onData(s.output)}return!0},ct.prototype.onData=function(e){this.chunks.push(e)},ct.prototype.onEnd=function(e){e===nt&&(this.result=We(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var ht=ct,dt=At,pt=function(e,t){return(t=t||{}).raw=!0,At(e,t)},ft=function(e,t){return(t=t||{}).gzip=!0,At(e,t)},vt=16209,gt=function(e,t){var i,r,s,n,o,a,l,u,c,A,h,d,p,f,v,g,m,_,y,b,x,w,B,P,C=e.state;i=e.next_in,B=e.input,r=i+(e.avail_in-5),s=e.next_out,P=e.output,n=s-(t-e.avail_out),o=s+(e.avail_out-257),a=C.dmax,l=C.wsize,u=C.whave,c=C.wnext,A=C.window,h=C.hold,d=C.bits,p=C.lencode,f=C.distcode,v=(1<>>=_=m>>>24,d-=_,0===(_=m>>>16&255))P[s++]=65535&m;else{if(!(16&_)){if(0==(64&_)){m=p[(65535&m)+(h&(1<<_)-1)];continue t}if(32&_){C.mode=16191;break e}e.msg="invalid literal/length code",C.mode=vt;break e}y=65535&m,(_&=15)&&(d<_&&(h+=B[i++]<>>=_,d-=_),d<15&&(h+=B[i++]<>>=_=m>>>24,d-=_,!(16&(_=m>>>16&255))){if(0==(64&_)){m=f[(65535&m)+(h&(1<<_)-1)];continue i}e.msg="invalid distance code",C.mode=vt;break e}if(b=65535&m,d<(_&=15)&&(h+=B[i++]<a){e.msg="invalid distance too far back",C.mode=vt;break e}if(h>>>=_,d-=_,b>(_=s-n)){if((_=b-_)>u&&C.sane){e.msg="invalid distance too far back",C.mode=vt;break e}if(x=0,w=A,0===c){if(x+=l-_,_2;)P[s++]=w[x++],P[s++]=w[x++],P[s++]=w[x++],y-=3;y&&(P[s++]=w[x++],y>1&&(P[s++]=w[x++]))}else{x=s-b;do{P[s++]=P[x++],P[s++]=P[x++],P[s++]=P[x++],y-=3}while(y>2);y&&(P[s++]=P[x++],y>1&&(P[s++]=P[x++]))}break}}break}}while(i>3,h&=(1<<(d-=y<<3))-1,e.next_in=i,e.next_out=s,e.avail_in=i=1&&0===F[b];b--);if(x>b&&(x=b),0===b)return s[n++]=20971520,s[n++]=20971520,a.bits=1,0;for(y=1;y0&&(0===e||1!==b))return-1;for(k[1]=0,m=1;m<15;m++)k[m+1]=k[m]+F[m];for(_=0;_852||2===e&&C>592)return 1;for(;;){p=m-B,o[_]+1=d?(f=I[o[_]-d],v=E[o[_]-d]):(f=96,v=0),l=1<>B)+(u-=l)]=p<<24|f<<16|v|0}while(0!==u);for(l=1<>=1;if(0!==l?(M&=l-1,M+=l):M=0,_++,0==--F[m]){if(m===b)break;m=t[i+o[_]]}if(m>x&&(M&A)!==c){for(0===B&&(B=x),h+=y,P=1<<(w=m-B);w+B852||2===e&&C>592)return 1;s[c=M&A]=x<<24|w<<16|h-n|0}}return 0!==M&&(s[h+M]=m-B<<24|64<<16|0),a.bits=x,0},wt=j.Z_FINISH,Bt=j.Z_BLOCK,Pt=j.Z_TREES,Ct=j.Z_OK,Mt=j.Z_STREAM_END,Et=j.Z_NEED_DICT,Ft=j.Z_STREAM_ERROR,kt=j.Z_DATA_ERROR,It=j.Z_MEM_ERROR,Dt=j.Z_BUF_ERROR,St=j.Z_DEFLATED,Tt=16180,Lt=16190,Rt=16191,Ut=16192,Ot=16194,Nt=16199,Qt=16200,Vt=16206,Ht=16209,jt=function(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)};function Gt(){this.strm=null,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 Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}var zt,Wt,Kt=function(e){if(!e)return 1;var t=e.state;return!t||t.strm!==e||t.mode16211?1:0},Xt=function(e){if(Kt(e))return Ft;var t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=Tt,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,Ct},Jt=function(e){if(Kt(e))return Ft;var t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,Xt(e)},Yt=function(e,t){var i;if(Kt(e))return Ft;var r=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?Ft:(null!==r.window&&r.wbits!==t&&(r.window=null),r.wrap=i,r.wbits=t,Jt(e))},Zt=function(e,t){if(!e)return Ft;var i=new Gt;e.state=i,i.strm=e,i.window=null,i.mode=Tt;var r=Yt(e,t);return r!==Ct&&(e.state=null),r},qt=!0,$t=function(e){if(qt){zt=new Int32Array(512),Wt=new Int32Array(32);for(var 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(xt(1,e.lens,0,288,zt,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;xt(2,e.lens,0,32,Wt,0,e.work,{bits:5}),qt=!1}e.lencode=zt,e.lenbits=9,e.distcode=Wt,e.distbits=5},ei=function(e,t,i,r){var s,n=e.state;return null===n.window&&(n.wsize=1<=n.wsize?(n.window.set(t.subarray(i-n.wsize,i),0),n.wnext=0,n.whave=n.wsize):((s=n.wsize-n.wnext)>r&&(s=r),n.window.set(t.subarray(i-r,i-r+s),n.wnext),(r-=s)?(n.window.set(t.subarray(i-r,i),0),n.wnext=r,n.whave=n.wsize):(n.wnext+=s,n.wnext===n.wsize&&(n.wnext=0),n.whave>>8&255,i.check=V(i.check,M,2,0),u=0,c=0,i.mode=16181;break}if(i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&u)<<8)+(u>>8))%31){e.msg="incorrect header check",i.mode=Ht;break}if((15&u)!==St){e.msg="unknown compression method",i.mode=Ht;break}if(c-=4,x=8+(15&(u>>>=4)),0===i.wbits&&(i.wbits=x),x>15||x>i.wbits){e.msg="invalid window size",i.mode=Ht;break}i.dmax=1<>8&1),512&i.flags&&4&i.wrap&&(M[0]=255&u,M[1]=u>>>8&255,i.check=V(i.check,M,2,0)),u=0,c=0,i.mode=16182;case 16182:for(;c<32;){if(0===a)break e;a--,u+=r[n++]<>>8&255,M[2]=u>>>16&255,M[3]=u>>>24&255,i.check=V(i.check,M,4,0)),u=0,c=0,i.mode=16183;case 16183:for(;c<16;){if(0===a)break e;a--,u+=r[n++]<>8),512&i.flags&&4&i.wrap&&(M[0]=255&u,M[1]=u>>>8&255,i.check=V(i.check,M,2,0)),u=0,c=0,i.mode=16184;case 16184:if(1024&i.flags){for(;c<16;){if(0===a)break e;a--,u+=r[n++]<>>8&255,i.check=V(i.check,M,2,0)),u=0,c=0}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&i.flags&&((d=i.length)>a&&(d=a),d&&(i.head&&(x=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(r.subarray(n,n+d),x)),512&i.flags&&4&i.wrap&&(i.check=V(i.check,r,d,n)),a-=d,n+=d,i.length-=d),i.length))break e;i.length=0,i.mode=16186;case 16186:if(2048&i.flags){if(0===a)break e;d=0;do{x=r[n+d++],i.head&&x&&i.length<65536&&(i.head.name+=String.fromCharCode(x))}while(x&&d>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=Rt;break;case 16189:for(;c<32;){if(0===a)break e;a--,u+=r[n++]<>>=7&c,c-=7&c,i.mode=Vt;break}for(;c<3;){if(0===a)break e;a--,u+=r[n++]<>>=1)){case 0:i.mode=16193;break;case 1:if($t(i),i.mode=Nt,t===Pt){u>>>=2,c-=2;break e}break;case 2:i.mode=16196;break;case 3:e.msg="invalid block type",i.mode=Ht}u>>>=2,c-=2;break;case 16193:for(u>>>=7&c,c-=7&c;c<32;){if(0===a)break e;a--,u+=r[n++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=Ht;break}if(i.length=65535&u,u=0,c=0,i.mode=Ot,t===Pt)break e;case Ot:i.mode=16195;case 16195:if(d=i.length){if(d>a&&(d=a),d>l&&(d=l),0===d)break e;s.set(r.subarray(n,n+d),o),a-=d,n+=d,l-=d,o+=d,i.length-=d;break}i.mode=Rt;break;case 16196:for(;c<14;){if(0===a)break e;a--,u+=r[n++]<>>=5,c-=5,i.ndist=1+(31&u),u>>>=5,c-=5,i.ncode=4+(15&u),u>>>=4,c-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=Ht;break}i.have=0,i.mode=16197;case 16197:for(;i.have>>=3,c-=3}for(;i.have<19;)i.lens[E[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,B={bits:i.lenbits},w=xt(0,i.lens,0,19,i.lencode,0,i.work,B),i.lenbits=B.bits,w){e.msg="invalid code lengths set",i.mode=Ht;break}i.have=0,i.mode=16198;case 16198:for(;i.have>>16&255,m=65535&C,!((v=C>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<>>=v,c-=v,i.lens[i.have++]=m;else{if(16===m){for(P=v+2;c>>=v,c-=v,0===i.have){e.msg="invalid bit length repeat",i.mode=Ht;break}x=i.lens[i.have-1],d=3+(3&u),u>>>=2,c-=2}else if(17===m){for(P=v+3;c>>=v)),u>>>=3,c-=3}else{for(P=v+7;c>>=v)),u>>>=7,c-=7}if(i.have+d>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=Ht;break}for(;d--;)i.lens[i.have++]=x}}if(i.mode===Ht)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=Ht;break}if(i.lenbits=9,B={bits:i.lenbits},w=xt(1,i.lens,0,i.nlen,i.lencode,0,i.work,B),i.lenbits=B.bits,w){e.msg="invalid literal/lengths set",i.mode=Ht;break}if(i.distbits=6,i.distcode=i.distdyn,B={bits:i.distbits},w=xt(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,B),i.distbits=B.bits,w){e.msg="invalid distances set",i.mode=Ht;break}if(i.mode=Nt,t===Pt)break e;case Nt:i.mode=Qt;case Qt:if(a>=6&&l>=258){e.next_out=o,e.avail_out=l,e.next_in=n,e.avail_in=a,i.hold=u,i.bits=c,gt(e,h),o=e.next_out,s=e.output,l=e.avail_out,n=e.next_in,r=e.input,a=e.avail_in,u=i.hold,c=i.bits,i.mode===Rt&&(i.back=-1);break}for(i.back=0;g=(C=i.lencode[u&(1<>>16&255,m=65535&C,!((v=C>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<>_)])>>>16&255,m=65535&C,!(_+(v=C>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<>>=_,c-=_,i.back+=_}if(u>>>=v,c-=v,i.back+=v,i.length=m,0===g){i.mode=16205;break}if(32&g){i.back=-1,i.mode=Rt;break}if(64&g){e.msg="invalid literal/length code",i.mode=Ht;break}i.extra=15&g,i.mode=16201;case 16201:if(i.extra){for(P=i.extra;c>>=i.extra,c-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=16202;case 16202:for(;g=(C=i.distcode[u&(1<>>16&255,m=65535&C,!((v=C>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<>_)])>>>16&255,m=65535&C,!(_+(v=C>>>24)<=c);){if(0===a)break e;a--,u+=r[n++]<>>=_,c-=_,i.back+=_}if(u>>>=v,c-=v,i.back+=v,64&g){e.msg="invalid distance code",i.mode=Ht;break}i.offset=m,i.extra=15&g,i.mode=16203;case 16203:if(i.extra){for(P=i.extra;c>>=i.extra,c-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=Ht;break}i.mode=16204;case 16204:if(0===l)break e;if(d=h-l,i.offset>d){if((d=i.offset-d)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=Ht;break}d>i.wnext?(d-=i.wnext,p=i.wsize-d):p=i.wnext-d,d>i.length&&(d=i.length),f=i.window}else f=s,p=o-i.offset,d=i.length;d>l&&(d=l),l-=d,i.length-=d;do{s[o++]=f[p++]}while(--d);0===i.length&&(i.mode=Qt);break;case 16205:if(0===l)break e;s[o++]=i.length,l--,i.mode=Qt;break;case Vt:if(i.wrap){for(;c<32;){if(0===a)break e;a--,u|=r[n++]<=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 $e,this.strm.avail_out=0;var i=ii(this.strm,t.windowBits);if(i!==Ai)throw new Error(H[i]);if(this.header=new ai,ni(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=Ye(t.dictionary):"[object ArrayBuffer]"===li.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=oi(this.strm,t.dictionary))!==Ai))throw new Error(H[i])}function mi(e,t){var i=new gi(t);if(i.push(e),i.err)throw i.msg||H[i.err];return i.result}gi.prototype.push=function(e,t){var i,r,s,n=this.strm,o=this.options.chunkSize,a=this.options.dictionary;if(this.ended)return!1;for(r=t===~~t?t:!0===t?ci:ui,"[object ArrayBuffer]"===li.call(e)?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;){for(0===n.avail_out&&(n.output=new Uint8Array(o),n.next_out=0,n.avail_out=o),(i=ri(n,r))===di&&a&&((i=oi(n,a))===Ai?i=ri(n,r):i===fi&&(i=di));n.avail_in>0&&i===hi&&n.state.wrap>0&&0!==e[n.next_in];)ti(n),i=ri(n,r);switch(i){case pi:case fi:case di:case vi:return this.onEnd(i),this.ended=!0,!1}if(s=n.avail_out,n.next_out&&(0===n.avail_out||i===hi))if("string"===this.options.to){var l=qe(n.output,n.next_out),u=n.next_out-l,c=Ze(n.output,l);n.next_out=u,n.avail_out=o-u,u&&n.output.set(n.output.subarray(l,l+u),0),this.onData(c)}else this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out));if(i!==Ai||0!==s){if(i===hi)return i=si(this.strm),this.onEnd(i),this.ended=!0,!0;if(0===n.avail_in)break}}return!0},gi.prototype.onData=function(e){this.chunks.push(e)},gi.prototype.onEnd=function(e){e===Ai&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=We(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var _i=function(e,t){return(t=t||{}).raw=!0,mi(e,t)},yi=ht,bi=dt,xi=pt,wi=ft,Bi=gi,Pi=mi,Ci=_i,Mi=mi,Ei=j,Fi={Deflate:yi,deflate:bi,deflateRaw:xi,gzip:wi,Inflate:Bi,inflate:Pi,inflateRaw:Ci,ungzip:Mi,constants:Ei};e.Deflate=yi,e.Inflate=Bi,e.constants=Ei,e.default=Fi,e.deflate=bi,e.deflateRaw=xi,e.gzip=wi,e.inflate=Pi,e.inflateRaw=Ci,e.ungzip=Mi,Object.defineProperty(e,"__esModule",{value:!0})}));var VF=Object.freeze({__proto__:null}),HF=window.pako||VF;HF.inflate||(HF=HF.default);var jF,GF=(jF=new Float32Array(3),function(e){return jF[0]=e[0]/255,jF[1]=e[1]/255,jF[2]=e[2]/255,jF});var zF={version:1,parse:function(e,t,i,r,s,n){var o=function(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]}}(i),a=function(e){return{positions:new Uint16Array(HF.inflate(e.positions).buffer),normals:new Int8Array(HF.inflate(e.normals).buffer),indices:new Uint32Array(HF.inflate(e.indices).buffer),edgeIndices:new Uint32Array(HF.inflate(e.edgeIndices).buffer),meshPositions:new Uint32Array(HF.inflate(e.meshPositions).buffer),meshIndices:new Uint32Array(HF.inflate(e.meshIndices).buffer),meshEdgesIndices:new Uint32Array(HF.inflate(e.meshEdgesIndices).buffer),meshColors:new Uint8Array(HF.inflate(e.meshColors).buffer),entityIDs:HF.inflate(e.entityIDs,{to:"string"}),entityMeshes:new Uint32Array(HF.inflate(e.entityMeshes).buffer),entityIsObjects:new Uint8Array(HF.inflate(e.entityIsObjects).buffer),positionsDecodeMatrix:new Float32Array(HF.inflate(e.positionsDecodeMatrix).buffer)}}(o);!function(e,t,i,r,s,n){n.getNextId(),r.positionsCompression="precompressed",r.normalsCompression="precompressed";for(var o=i.positions,a=i.normals,l=i.indices,u=i.edgeIndices,c=i.meshPositions,A=i.meshIndices,h=i.meshEdgesIndices,d=i.meshColors,p=JSON.parse(i.entityIDs),f=i.entityMeshes,v=i.entityIsObjects,g=c.length,m=f.length,_=0;_v[t]?1:0}));for(var E=0;E1||(F[R]=k)}for(var U=0;U1,V=$F(g.subarray(4*O,4*O+3)),H=g[4*O+3]/255,j=a.subarray(d[O],N?a.length:d[O+1]),G=l.subarray(d[O],N?l.length:d[O+1]),z=u.subarray(p[O],N?u.length:p[O+1]),W=c.subarray(f[O],N?c.length:f[O+1]),K=A.subarray(v[O],v[O]+16);if(Q){var X="".concat(o,"-geometry.").concat(O);r.createGeometry({id:X,primitive:"triangles",positionsCompressed:j,normalsCompressed:G,indices:z,edgeIndices:W,positionsDecodeMatrix:K})}else{var J="".concat(o,"-").concat(O);_[F[O]],r.createMesh(he.apply({},{id:J,primitive:"triangles",positionsCompressed:j,normalsCompressed:G,indices:z,edgeIndices:W,positionsDecodeMatrix:K,color:V,opacity:H}))}}for(var Y=0,Z=0;Z1){var oe="".concat(o,"-instance.").concat(Y++),ae="".concat(o,"-geometry.").concat(ne),le=16*b[Z],ue=h.subarray(le,le+16);r.createMesh(he.apply({},{id:oe,geometryId:ae,matrix:ue})),re.push(oe)}else re.push(ne)}re.length>0&&r.createEntity(he.apply({},{id:ee,isObject:!0,meshIds:re}))}}(0,0,a,r,0,n)}},tk=window.pako||VF;tk.inflate||(tk=tk.default);var ik=function(){var e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();var rk={version:5,parse:function(e,t,i,r,s,n){var o=function(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]}}(i),a=function(e){return{positions:new Float32Array(tk.inflate(e.positions).buffer),normals:new Int8Array(tk.inflate(e.normals).buffer),indices:new Uint32Array(tk.inflate(e.indices).buffer),edgeIndices:new Uint32Array(tk.inflate(e.edgeIndices).buffer),matrices:new Float32Array(tk.inflate(e.matrices).buffer),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(tk.inflate(e.eachPrimitivePositionsAndNormalsPortion).buffer),eachPrimitiveIndicesPortion:new Uint32Array(tk.inflate(e.eachPrimitiveIndicesPortion).buffer),eachPrimitiveEdgeIndicesPortion:new Uint32Array(tk.inflate(e.eachPrimitiveEdgeIndicesPortion).buffer),eachPrimitiveColor:new Uint8Array(tk.inflate(e.eachPrimitiveColor).buffer),primitiveInstances:new Uint32Array(tk.inflate(e.primitiveInstances).buffer),eachEntityId:tk.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(tk.inflate(e.eachEntityPrimitiveInstancesPortion).buffer),eachEntityMatricesPortion:new Uint32Array(tk.inflate(e.eachEntityMatricesPortion).buffer)}}(o);!function(e,t,i,r,s,n){var o=n.getNextId();r.positionsCompression="disabled",r.normalsCompression="precompressed";for(var a=i.positions,l=i.normals,u=i.indices,c=i.edgeIndices,A=i.matrices,h=i.eachPrimitivePositionsAndNormalsPortion,d=i.eachPrimitiveIndicesPortion,p=i.eachPrimitiveEdgeIndicesPortion,f=i.eachPrimitiveColor,v=i.primitiveInstances,g=JSON.parse(i.eachEntityId),m=i.eachEntityPrimitiveInstancesPortion,_=i.eachEntityMatricesPortion,y=h.length,b=v.length,x=new Uint8Array(y),w=g.length,B=0;B1||(P[D]=C)}for(var S=0;S1,R=ik(f.subarray(4*S,4*S+3)),U=f[4*S+3]/255,O=a.subarray(h[S],T?a.length:h[S+1]),N=l.subarray(h[S],T?l.length:h[S+1]),Q=u.subarray(d[S],T?u.length:d[S+1]),V=c.subarray(p[S],T?c.length:p[S+1]);if(L){var H="".concat(o,"-geometry.").concat(S);r.createGeometry({id:H,primitive:"triangles",positionsCompressed:O,normalsCompressed:N,indices:Q,edgeIndices:V})}else{var j=S;g[P[S]],r.createMesh(he.apply({},{id:j,primitive:"triangles",positionsCompressed:O,normalsCompressed:N,indices:Q,edgeIndices:V,color:R,opacity:U}))}}for(var G=0,z=0;z1){var ee="instance."+G++,te="geometry"+$,ie=16*_[z],re=A.subarray(ie,ie+16);r.createMesh(he.apply({},{id:ee,geometryId:te,matrix:re})),Z.push(ee)}else Z.push($)}Z.length>0&&r.createEntity(he.apply({},{id:X,isObject:!0,meshIds:Z}))}}(0,0,a,r,0,n)}},sk=window.pako||VF;sk.inflate||(sk=sk.default);var nk,ok=(nk=new Float32Array(3),function(e){return nk[0]=e[0]/255,nk[1]=e[1]/255,nk[2]=e[2]/255,nk});var ak={version:6,parse:function(e,t,i,r,s,n){var o=function(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],matrices:e[4],reusedPrimitivesDecodeMatrix:e[5],eachPrimitivePositionsAndNormalsPortion:e[6],eachPrimitiveIndicesPortion:e[7],eachPrimitiveEdgeIndicesPortion:e[8],eachPrimitiveColorAndOpacity:e[9],primitiveInstances:e[10],eachEntityId:e[11],eachEntityPrimitiveInstancesPortion:e[12],eachEntityMatricesPortion:e[13],eachTileAABB:e[14],eachTileEntitiesPortion:e[15]}}(i),a=function(e){function t(e,t){return 0===e.length?[]:sk.inflate(e,t).buffer}return{positions:new Uint16Array(t(e.positions)),normals:new Int8Array(t(e.normals)),indices:new Uint32Array(t(e.indices)),edgeIndices:new Uint32Array(t(e.edgeIndices)),matrices:new Float32Array(t(e.matrices)),reusedPrimitivesDecodeMatrix:new Float32Array(t(e.reusedPrimitivesDecodeMatrix)),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(t(e.eachPrimitivePositionsAndNormalsPortion)),eachPrimitiveIndicesPortion:new Uint32Array(t(e.eachPrimitiveIndicesPortion)),eachPrimitiveEdgeIndicesPortion:new Uint32Array(t(e.eachPrimitiveEdgeIndicesPortion)),eachPrimitiveColorAndOpacity:new Uint8Array(t(e.eachPrimitiveColorAndOpacity)),primitiveInstances:new Uint32Array(t(e.primitiveInstances)),eachEntityId:sk.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(t(e.eachEntityPrimitiveInstancesPortion)),eachEntityMatricesPortion:new Uint32Array(t(e.eachEntityMatricesPortion)),eachTileAABB:new Float64Array(t(e.eachTileAABB)),eachTileEntitiesPortion:new Uint32Array(t(e.eachTileEntitiesPortion))}}(o);!function(e,t,i,r,s,n){for(var o=n.getNextId(),a=i.positions,l=i.normals,u=i.indices,c=i.edgeIndices,A=i.matrices,h=i.reusedPrimitivesDecodeMatrix,d=i.eachPrimitivePositionsAndNormalsPortion,p=i.eachPrimitiveIndicesPortion,f=i.eachPrimitiveEdgeIndicesPortion,v=i.eachPrimitiveColorAndOpacity,g=i.primitiveInstances,m=JSON.parse(i.eachEntityId),_=i.eachEntityPrimitiveInstancesPortion,y=i.eachEntityMatricesPortion,b=i.eachTileAABB,x=i.eachTileEntitiesPortion,w=d.length,B=g.length,P=m.length,C=x.length,M=new Uint32Array(w),E=0;E1,ie=ee===w-1,se=a.subarray(d[ee],ie?a.length:d[ee+1]),ne=l.subarray(d[ee],ie?l.length:d[ee+1]),oe=u.subarray(p[ee],ie?u.length:p[ee+1]),ae=c.subarray(f[ee],ie?c.length:f[ee+1]),le=ok(v.subarray(4*ee,4*ee+3)),ue=v[4*ee+3]/255,ce=n.getNextId();if(te){var Ae="".concat(o,"-geometry.").concat(D,".").concat(ee);N[Ae]||(r.createGeometry({id:Ae,primitive:"triangles",positionsCompressed:se,indices:oe,edgeIndices:ae,positionsDecodeMatrix:h}),N[Ae]=!0),r.createMesh(he.apply(Z,{id:ce,geometryId:Ae,origin:k,matrix:G,color:le,opacity:ue})),X.push(ce)}else r.createMesh(he.apply(Z,{id:ce,origin:k,primitive:"triangles",positionsCompressed:se,normalsCompressed:ne,indices:oe,edgeIndices:ae,positionsDecodeMatrix:O,color:le,opacity:ue})),X.push(ce)}X.length>0&&r.createEntity(he.apply(Y,{id:H,isObject:!0,meshIds:X}))}}}(e,t,a,r,0,n)}},lk=window.pako||VF;lk.inflate||(lk=lk.default);var uk=function(){var 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 ck(e){for(var t=[],i=0,r=e.length;i1,ne=ie===M-1,oe=uk(x.subarray(6*te,6*te+3)),ae=x[6*te+3]/255,le=x[6*te+4]/255,ue=x[6*te+5]/255,ce=n.getNextId();if(se){var Ae=b[te],de=h.slice(Ae,Ae+16),pe="".concat(o,"-geometry.").concat(R,".").concat(ie);if(!j[pe]){var fe=void 0,ve=void 0,ge=void 0,me=void 0,_e=void 0,ye=void 0;switch(p[ie]){case 0:fe="solid",ve=a.subarray(f[ie],ne?a.length:f[ie+1]),ge=l.subarray(v[ie],ne?l.length:v[ie+1]),_e=c.subarray(m[ie],ne?c.length:m[ie+1]),ye=A.subarray(_[ie],ne?A.length:_[ie+1]);break;case 1:fe="surface",ve=a.subarray(f[ie],ne?a.length:f[ie+1]),ge=l.subarray(v[ie],ne?l.length:v[ie+1]),_e=c.subarray(m[ie],ne?c.length:m[ie+1]),ye=A.subarray(_[ie],ne?A.length:_[ie+1]);break;case 2:fe="points",ve=a.subarray(f[ie],ne?a.length:f[ie+1]),me=ck(u.subarray(g[ie],ne?u.length:g[ie+1]));break;case 3:fe="lines",ve=a.subarray(f[ie],ne?a.length:f[ie+1]),_e=c.subarray(m[ie],ne?c.length:m[ie+1]);break;default:continue}r.createGeometry({id:pe,primitive:fe,positionsCompressed:ve,normalsCompressed:ge,colors:me,indices:_e,edgeIndices:ye,positionsDecodeMatrix:d}),j[pe]=!0}r.createMesh(he.apply($,{id:ce,geometryId:pe,origin:T,matrix:de,color:oe,metallic:le,roughness:ue,opacity:ae})),Y.push(ce)}else{var be=void 0,xe=void 0,we=void 0,Be=void 0,Pe=void 0,Ce=void 0;switch(p[ie]){case 0:be="solid",xe=a.subarray(f[ie],ne?a.length:f[ie+1]),we=l.subarray(v[ie],ne?l.length:v[ie+1]),Pe=c.subarray(m[ie],ne?c.length:m[ie+1]),Ce=A.subarray(_[ie],ne?A.length:_[ie+1]);break;case 1:be="surface",xe=a.subarray(f[ie],ne?a.length:f[ie+1]),we=l.subarray(v[ie],ne?l.length:v[ie+1]),Pe=c.subarray(m[ie],ne?c.length:m[ie+1]),Ce=A.subarray(_[ie],ne?A.length:_[ie+1]);break;case 2:be="points",xe=a.subarray(f[ie],ne?a.length:f[ie+1]),Be=ck(u.subarray(g[ie],ne?u.length:g[ie+1]));break;case 3:be="lines",xe=a.subarray(f[ie],ne?a.length:f[ie+1]),Pe=c.subarray(m[ie],ne?c.length:m[ie+1]);break;default:continue}r.createMesh(he.apply($,{id:ce,origin:T,primitive:be,positionsCompressed:xe,normalsCompressed:we,colors:Be,indices:Pe,edgeIndices:Ce,positionsDecodeMatrix:H,color:oe,metallic:le,roughness:ue,opacity:ae})),Y.push(ce)}}Y.length>0&&r.createEntity(he.apply(q,{id:W,isObject:!0,meshIds:Y}))}}}(e,t,a,r,0,n)}},hk=window.pako||VF;hk.inflate||(hk=hk.default);var dk=re.vec4(),pk=re.vec4();var fk=function(){var 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 vk(e){for(var t=[],i=0,r=e.length;i1,ye=me===S-1,be=fk(M.subarray(6*ge,6*ge+3)),xe=M[6*ge+3]/255,we=M[6*ge+4]/255,Be=M[6*ge+5]/255,Pe=n.getNextId();if(_e){var Ce=C[ge],Me=g.slice(Ce,Ce+16),Ee="".concat(o,"-geometry.").concat(Y,".").concat(me),Fe=J[Ee];if(!Fe){Fe={batchThisMesh:!t.reuseGeometries};var ke=!1;switch(_[me]){case 0:Fe.primitiveName="solid",Fe.geometryPositions=h.subarray(y[me],ye?h.length:y[me+1]),Fe.geometryNormals=d.subarray(b[me],ye?d.length:b[me+1]),Fe.geometryIndices=f.subarray(w[me],ye?f.length:w[me+1]),Fe.geometryEdgeIndices=v.subarray(B[me],ye?v.length:B[me+1]),ke=Fe.geometryPositions.length>0&&Fe.geometryIndices.length>0;break;case 1:Fe.primitiveName="surface",Fe.geometryPositions=h.subarray(y[me],ye?h.length:y[me+1]),Fe.geometryNormals=d.subarray(b[me],ye?d.length:b[me+1]),Fe.geometryIndices=f.subarray(w[me],ye?f.length:w[me+1]),Fe.geometryEdgeIndices=v.subarray(B[me],ye?v.length:B[me+1]),ke=Fe.geometryPositions.length>0&&Fe.geometryIndices.length>0;break;case 2:Fe.primitiveName="points",Fe.geometryPositions=h.subarray(y[me],ye?h.length:y[me+1]),Fe.geometryColors=vk(p.subarray(x[me],ye?p.length:x[me+1])),ke=Fe.geometryPositions.length>0;break;case 3:Fe.primitiveName="lines",Fe.geometryPositions=h.subarray(y[me],ye?h.length:y[me+1]),Fe.geometryIndices=f.subarray(w[me],ye?f.length:w[me+1]),ke=Fe.geometryPositions.length>0&&Fe.geometryIndices.length>0;break;default:continue}if(ke||(Fe=null),Fe&&(Fe.geometryPositions.length,Fe.batchThisMesh)){Fe.decompressedPositions=new Float32Array(Fe.geometryPositions.length);for(var Ie=Fe.geometryPositions,De=Fe.decompressedPositions,Se=0,Te=Ie.length;Se0&&je.length>0;break;case 1:Ne="surface",Qe=h.subarray(y[me],ye?h.length:y[me+1]),Ve=d.subarray(b[me],ye?d.length:b[me+1]),je=f.subarray(w[me],ye?f.length:w[me+1]),Ge=v.subarray(B[me],ye?v.length:B[me+1]),ze=Qe.length>0&&je.length>0;break;case 2:Ne="points",Qe=h.subarray(y[me],ye?h.length:y[me+1]),He=vk(p.subarray(x[me],ye?p.length:x[me+1])),ze=Qe.length>0;break;case 3:Ne="lines",Qe=h.subarray(y[me],ye?h.length:y[me+1]),je=f.subarray(w[me],ye?f.length:w[me+1]),ze=Qe.length>0&&je.length>0;break;default:continue}ze&&(r.createMesh(he.apply(fe,{id:Pe,origin:K,primitive:Ne,positionsCompressed:Qe,normalsCompressed:Ve,colorsCompressed:He,indices:je,edgeIndices:Ge,positionsDecodeMatrix:ie,color:be,metallic:we,roughness:Be,opacity:xe})),Ae.push(Pe))}}Ae.length>0&&r.createEntity(he.apply(pe,{id:ae,isObject:!0,meshIds:Ae}))}}}(e,t,a,r,s,n)}},mk=window.pako||VF;mk.inflate||(mk=mk.default);var _k=re.vec4(),yk=re.vec4();var bk=function(){var e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();var xk={version:9,parse:function(e,t,i,r,s,n){var o=function(e){return{metadata:e[0],positions:e[1],normals:e[2],colors:e[3],indices:e[4],edgeIndices:e[5],matrices:e[6],reusedGeometriesDecodeMatrix:e[7],eachGeometryPrimitiveType:e[8],eachGeometryPositionsPortion:e[9],eachGeometryNormalsPortion:e[10],eachGeometryColorsPortion:e[11],eachGeometryIndicesPortion:e[12],eachGeometryEdgeIndicesPortion:e[13],eachMeshGeometriesPortion:e[14],eachMeshMatricesPortion:e[15],eachMeshMaterial:e[16],eachEntityId:e[17],eachEntityMeshesPortion:e[18],eachTileAABB:e[19],eachTileEntitiesPortion:e[20]}}(i),a=function(e){function t(e,t){return 0===e.length?[]:mk.inflate(e,t).buffer}return{metadata:JSON.parse(mk.inflate(e.metadata,{to:"string"})),positions:new Uint16Array(t(e.positions)),normals:new Int8Array(t(e.normals)),colors:new Uint8Array(t(e.colors)),indices:new Uint32Array(t(e.indices)),edgeIndices:new Uint32Array(t(e.edgeIndices)),matrices:new Float32Array(t(e.matrices)),reusedGeometriesDecodeMatrix:new Float32Array(t(e.reusedGeometriesDecodeMatrix)),eachGeometryPrimitiveType:new Uint8Array(t(e.eachGeometryPrimitiveType)),eachGeometryPositionsPortion:new Uint32Array(t(e.eachGeometryPositionsPortion)),eachGeometryNormalsPortion:new Uint32Array(t(e.eachGeometryNormalsPortion)),eachGeometryColorsPortion:new Uint32Array(t(e.eachGeometryColorsPortion)),eachGeometryIndicesPortion:new Uint32Array(t(e.eachGeometryIndicesPortion)),eachGeometryEdgeIndicesPortion:new Uint32Array(t(e.eachGeometryEdgeIndicesPortion)),eachMeshGeometriesPortion:new Uint32Array(t(e.eachMeshGeometriesPortion)),eachMeshMatricesPortion:new Uint32Array(t(e.eachMeshMatricesPortion)),eachMeshMaterial:new Uint8Array(t(e.eachMeshMaterial)),eachEntityId:JSON.parse(mk.inflate(e.eachEntityId,{to:"string"})),eachEntityMeshesPortion:new Uint32Array(t(e.eachEntityMeshesPortion)),eachTileAABB:new Float64Array(t(e.eachTileAABB)),eachTileEntitiesPortion:new Uint32Array(t(e.eachTileEntitiesPortion))}}(o);!function(e,t,i,r,s,n){var o=n.getNextId(),a=i.metadata,l=i.positions,u=i.normals,c=i.colors,A=i.indices,h=i.edgeIndices,d=i.matrices,p=i.reusedGeometriesDecodeMatrix,f=i.eachGeometryPrimitiveType,v=i.eachGeometryPositionsPortion,g=i.eachGeometryNormalsPortion,m=i.eachGeometryColorsPortion,_=i.eachGeometryIndicesPortion,y=i.eachGeometryEdgeIndicesPortion,b=i.eachMeshGeometriesPortion,x=i.eachMeshMatricesPortion,w=i.eachMeshMaterial,B=i.eachEntityId,P=i.eachEntityMeshesPortion,C=i.eachTileAABB,M=i.eachTileEntitiesPortion,E=v.length,F=b.length,k=P.length,I=M.length;s&&s.loadData(a,{includeTypes:t.includeTypes,excludeTypes:t.excludeTypes,globalizeObjectIds:t.globalizeObjectIds});for(var D=new Uint32Array(E),S=0;S1,ae=ne===E-1,le=bk(w.subarray(6*se,6*se+3)),ue=w[6*se+3]/255,ce=w[6*se+4]/255,Ae=w[6*se+5]/255,de=n.getNextId();if(oe){var pe=x[se],fe=d.slice(pe,pe+16),ve="".concat(o,"-geometry.").concat(O,".").concat(ne),ge=U[ve];if(!ge){ge={batchThisMesh:!t.reuseGeometries};var me=!1;switch(f[ne]){case 0:ge.primitiveName="solid",ge.geometryPositions=l.subarray(v[ne],ae?l.length:v[ne+1]),ge.geometryNormals=u.subarray(g[ne],ae?u.length:g[ne+1]),ge.geometryIndices=A.subarray(_[ne],ae?A.length:_[ne+1]),ge.geometryEdgeIndices=h.subarray(y[ne],ae?h.length:y[ne+1]),me=ge.geometryPositions.length>0&&ge.geometryIndices.length>0;break;case 1:ge.primitiveName="surface",ge.geometryPositions=l.subarray(v[ne],ae?l.length:v[ne+1]),ge.geometryNormals=u.subarray(g[ne],ae?u.length:g[ne+1]),ge.geometryIndices=A.subarray(_[ne],ae?A.length:_[ne+1]),ge.geometryEdgeIndices=h.subarray(y[ne],ae?h.length:y[ne+1]),me=ge.geometryPositions.length>0&&ge.geometryIndices.length>0;break;case 2:ge.primitiveName="points",ge.geometryPositions=l.subarray(v[ne],ae?l.length:v[ne+1]),ge.geometryColors=c.subarray(m[ne],ae?c.length:m[ne+1]),me=ge.geometryPositions.length>0;break;case 3:ge.primitiveName="lines",ge.geometryPositions=l.subarray(v[ne],ae?l.length:v[ne+1]),ge.geometryIndices=A.subarray(_[ne],ae?A.length:_[ne+1]),me=ge.geometryPositions.length>0&&ge.geometryIndices.length>0;break;default:continue}if(me||(ge=null),ge&&(ge.geometryPositions.length,ge.batchThisMesh)){ge.decompressedPositions=new Float32Array(ge.geometryPositions.length),ge.transformedAndRecompressedPositions=new Uint16Array(ge.geometryPositions.length);for(var _e=ge.geometryPositions,ye=ge.decompressedPositions,be=0,xe=_e.length;be0&&Ie.length>0;break;case 1:Me="surface",Ee=l.subarray(v[ne],ae?l.length:v[ne+1]),Fe=u.subarray(g[ne],ae?u.length:g[ne+1]),Ie=A.subarray(_[ne],ae?A.length:_[ne+1]),De=h.subarray(y[ne],ae?h.length:y[ne+1]),Se=Ee.length>0&&Ie.length>0;break;case 2:Me="points",Ee=l.subarray(v[ne],ae?l.length:v[ne+1]),ke=c.subarray(m[ne],ae?c.length:m[ne+1]),Se=Ee.length>0;break;case 3:Me="lines",Ee=l.subarray(v[ne],ae?l.length:v[ne+1]),Ie=A.subarray(_[ne],ae?A.length:_[ne+1]),Se=Ee.length>0&&Ie.length>0;break;default:continue}Se&&(r.createMesh(he.apply(te,{id:de,origin:L,primitive:Me,positionsCompressed:Ee,normalsCompressed:Fe,colorsCompressed:ke,indices:Ie,edgeIndices:De,positionsDecodeMatrix:G,color:le,metallic:ce,roughness:Ae,opacity:ue})),q.push(de))}}q.length>0&&r.createEntity(he.apply(ee,{id:X,isObject:!0,meshIds:q}))}}}(e,t,a,r,s,n)}},wk=window.pako||VF;wk.inflate||(wk=wk.default);var Bk=re.vec4(),Pk=re.vec4();var Ck=function(){var 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 Mk(e,t){var i=[];if(t.length>1)for(var r=0,s=t.length-1;r1)for(var n=0,o=e.length/3-1;n0,W=9*V,K=1===c[W+0],X=c[W+1];c[W+2],c[W+3];var J=c[W+4],Y=c[W+5],Z=c[W+6],q=c[W+7],$=c[W+8];if(z){var ee=new Uint8Array(l.subarray(j,G)).buffer,te="".concat(o,"-texture-").concat(V);if(K)r.createTexture({id:te,buffers:[ee],minFilter:J,magFilter:Y,wrapS:Z,wrapT:q,wrapR:$});else{var ie=new Blob([ee],{type:10001===X?"image/jpeg":10002===X?"image/png":"image/gif"}),se=(window.URL||window.webkitURL).createObjectURL(ie),ne=document.createElement("img");ne.src=se,r.createTexture({id:te,image:ne,minFilter:J,magFilter:Y,wrapS:Z,wrapT:q,wrapR:$})}}}for(var oe=0;oe=0?"".concat(o,"-texture-").concat(ue):null,normalsTextureId:Ae>=0?"".concat(o,"-texture-").concat(Ae):null,metallicRoughnessTextureId:ce>=0?"".concat(o,"-texture-").concat(ce):null,emissiveTextureId:de>=0?"".concat(o,"-texture-").concat(de):null,occlusionTextureId:pe>=0?"".concat(o,"-texture-").concat(pe):null})}for(var fe=new Uint32Array(U),ve=0;ve1,je=Ve===U-1,Ge=F[Qe],ze=Ge>=0?"".concat(o,"-textureSet-").concat(Ge):null,We=Ck(k.subarray(6*Qe,6*Qe+3)),Ke=k[6*Qe+3]/255,Xe=k[6*Qe+4]/255,Je=k[6*Qe+5]/255,Ye=n.getNextId();if(He){var Ze=E[Qe],qe=m.slice(Ze,Ze+16),$e="".concat(o,"-geometry.").concat(be,".").concat(Ve),et=ye[$e];if(!et){et={batchThisMesh:!t.reuseGeometries};var tt=!1;switch(y[Ve]){case 0:et.primitiveName="solid",et.geometryPositions=A.subarray(b[Ve],je?A.length:b[Ve+1]),et.geometryNormals=h.subarray(x[Ve],je?h.length:x[Ve+1]),et.geometryUVs=p.subarray(B[Ve],je?p.length:B[Ve+1]),et.geometryIndices=f.subarray(P[Ve],je?f.length:P[Ve+1]),et.geometryEdgeIndices=v.subarray(C[Ve],je?v.length:C[Ve+1]),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;case 1:et.primitiveName="surface",et.geometryPositions=A.subarray(b[Ve],je?A.length:b[Ve+1]),et.geometryNormals=h.subarray(x[Ve],je?h.length:x[Ve+1]),et.geometryUVs=p.subarray(B[Ve],je?p.length:B[Ve+1]),et.geometryIndices=f.subarray(P[Ve],je?f.length:P[Ve+1]),et.geometryEdgeIndices=v.subarray(C[Ve],je?v.length:C[Ve+1]),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;case 2:et.primitiveName="points",et.geometryPositions=A.subarray(b[Ve],je?A.length:b[Ve+1]),et.geometryColors=d.subarray(w[Ve],je?d.length:w[Ve+1]),tt=et.geometryPositions.length>0;break;case 3:et.primitiveName="lines",et.geometryPositions=A.subarray(b[Ve],je?A.length:b[Ve+1]),et.geometryIndices=f.subarray(P[Ve],je?f.length:P[Ve+1]),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;case 4:et.primitiveName="lines",et.geometryPositions=A.subarray(b[Ve],je?A.length:b[Ve+1]),et.geometryIndices=Mk(et.geometryPositions,f.subarray(P[Ve],je?f.length:P[Ve+1])),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;default:continue}if(tt||(et=null),et&&(et.geometryPositions.length,et.batchThisMesh)){et.decompressedPositions=new Float32Array(et.geometryPositions.length),et.transformedAndRecompressedPositions=new Uint16Array(et.geometryPositions.length);for(var it=et.geometryPositions,rt=et.decompressedPositions,st=0,nt=it.length;st0&&ft.length>0;break;case 1:ct="surface",At=A.subarray(b[Ve],je?A.length:b[Ve+1]),ht=h.subarray(x[Ve],je?h.length:x[Ve+1]),dt=p.subarray(B[Ve],je?p.length:B[Ve+1]),ft=f.subarray(P[Ve],je?f.length:P[Ve+1]),vt=v.subarray(C[Ve],je?v.length:C[Ve+1]),gt=At.length>0&&ft.length>0;break;case 2:ct="points",At=A.subarray(b[Ve],je?A.length:b[Ve+1]),pt=d.subarray(w[Ve],je?d.length:w[Ve+1]),gt=At.length>0;break;case 3:ct="lines",At=A.subarray(b[Ve],je?A.length:b[Ve+1]),ft=f.subarray(P[Ve],je?f.length:P[Ve+1]),gt=At.length>0&&ft.length>0;break;case 4:ct="lines",ft=Mk(At=A.subarray(b[Ve],je?A.length:b[Ve+1]),f.subarray(P[Ve],je?f.length:P[Ve+1])),gt=At.length>0&&ft.length>0;break;default:continue}gt&&(r.createMesh(he.apply(Oe,{id:Ye,textureSetId:ze,origin:me,primitive:ct,positionsCompressed:At,normalsCompressed:ht,uv:dt&&dt.length>0?dt:null,colorsCompressed:pt,indices:ft,edgeIndices:vt,positionsDecodeMatrix:Me,color:We,metallic:Xe,roughness:Je,opacity:Ke})),Le.push(Ye))}}Le.length>0&&r.createEntity(he.apply(Ue,{id:Ie,isObject:!0,meshIds:Le}))}}}(e,t,a,r,s,n)}},Fk=re.vec4(),kk=re.vec4();var Ik=function(){var 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 Dk(e,t){var i=[];if(t.length>1)for(var r=0,s=t.length-1;r1)for(var n=0,o=e.length/3-1;n1)for(var u=new Uint8Array(e,o,a),c=l/2,A=u.length/l,h=0;h0,W=9*V,K=1===c[W+0],X=c[W+1];c[W+2],c[W+3];var J=c[W+4],Y=c[W+5],Z=c[W+6],q=c[W+7],$=c[W+8];if(z){var ee=new Uint8Array(l.subarray(j,G)).buffer,te="".concat(o,"-texture-").concat(V);if(K)r.createTexture({id:te,buffers:[ee],minFilter:J,magFilter:Y,wrapS:Z,wrapT:q,wrapR:$});else{var ie=new Blob([ee],{type:10001===X?"image/jpeg":10002===X?"image/png":"image/gif"}),se=(window.URL||window.webkitURL).createObjectURL(ie),ne=document.createElement("img");ne.src=se,r.createTexture({id:te,image:ne,minFilter:J,magFilter:Y,wrapS:Z,wrapT:q,wrapR:$})}}}for(var oe=0;oe=0?"".concat(o,"-texture-").concat(ue):null,normalsTextureId:Ae>=0?"".concat(o,"-texture-").concat(Ae):null,metallicRoughnessTextureId:ce>=0?"".concat(o,"-texture-").concat(ce):null,emissiveTextureId:de>=0?"".concat(o,"-texture-").concat(de):null,occlusionTextureId:pe>=0?"".concat(o,"-texture-").concat(pe):null})}for(var fe=new Uint32Array(U),ve=0;ve1,je=Ve===U-1,Ge=F[Qe],ze=Ge>=0?"".concat(o,"-textureSet-").concat(Ge):null,We=Ik(k.subarray(6*Qe,6*Qe+3)),Ke=k[6*Qe+3]/255,Xe=k[6*Qe+4]/255,Je=k[6*Qe+5]/255,Ye=n.getNextId();if(He){var Ze=E[Qe],qe=m.slice(Ze,Ze+16),$e="".concat(o,"-geometry.").concat(be,".").concat(Ve),et=ye[$e];if(!et){et={batchThisMesh:!t.reuseGeometries};var tt=!1;switch(y[Ve]){case 0:et.primitiveName="solid",et.geometryPositions=A.subarray(b[Ve],je?A.length:b[Ve+1]),et.geometryNormals=h.subarray(x[Ve],je?h.length:x[Ve+1]),et.geometryUVs=p.subarray(B[Ve],je?p.length:B[Ve+1]),et.geometryIndices=f.subarray(P[Ve],je?f.length:P[Ve+1]),et.geometryEdgeIndices=v.subarray(C[Ve],je?v.length:C[Ve+1]),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;case 1:et.primitiveName="surface",et.geometryPositions=A.subarray(b[Ve],je?A.length:b[Ve+1]),et.geometryNormals=h.subarray(x[Ve],je?h.length:x[Ve+1]),et.geometryUVs=p.subarray(B[Ve],je?p.length:B[Ve+1]),et.geometryIndices=f.subarray(P[Ve],je?f.length:P[Ve+1]),et.geometryEdgeIndices=v.subarray(C[Ve],je?v.length:C[Ve+1]),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;case 2:et.primitiveName="points",et.geometryPositions=A.subarray(b[Ve],je?A.length:b[Ve+1]),et.geometryColors=d.subarray(w[Ve],je?d.length:w[Ve+1]),tt=et.geometryPositions.length>0;break;case 3:et.primitiveName="lines",et.geometryPositions=A.subarray(b[Ve],je?A.length:b[Ve+1]),et.geometryIndices=f.subarray(P[Ve],je?f.length:P[Ve+1]),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;case 4:et.primitiveName="lines",et.geometryPositions=A.subarray(b[Ve],je?A.length:b[Ve+1]),et.geometryIndices=Dk(et.geometryPositions,f.subarray(P[Ve],je?f.length:P[Ve+1])),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;default:continue}if(tt||(et=null),et&&(et.geometryPositions.length,et.batchThisMesh)){et.decompressedPositions=new Float32Array(et.geometryPositions.length),et.transformedAndRecompressedPositions=new Uint16Array(et.geometryPositions.length);for(var it=et.geometryPositions,rt=et.decompressedPositions,st=0,nt=it.length;st0&&ft.length>0;break;case 1:ct="surface",At=A.subarray(b[Ve],je?A.length:b[Ve+1]),ht=h.subarray(x[Ve],je?h.length:x[Ve+1]),dt=p.subarray(B[Ve],je?p.length:B[Ve+1]),ft=f.subarray(P[Ve],je?f.length:P[Ve+1]),vt=v.subarray(C[Ve],je?v.length:C[Ve+1]),gt=At.length>0&&ft.length>0;break;case 2:ct="points",At=A.subarray(b[Ve],je?A.length:b[Ve+1]),pt=d.subarray(w[Ve],je?d.length:w[Ve+1]),gt=At.length>0;break;case 3:ct="lines",At=A.subarray(b[Ve],je?A.length:b[Ve+1]),ft=f.subarray(P[Ve],je?f.length:P[Ve+1]),gt=At.length>0&&ft.length>0;break;case 4:ct="lines",ft=Dk(At=A.subarray(b[Ve],je?A.length:b[Ve+1]),f.subarray(P[Ve],je?f.length:P[Ve+1])),gt=At.length>0&&ft.length>0;break;default:continue}gt&&(r.createMesh(he.apply(Oe,{id:Ye,textureSetId:ze,origin:me,primitive:ct,positionsCompressed:At,normalsCompressed:ht,uv:dt&&dt.length>0?dt:null,colorsCompressed:pt,indices:ft,edgeIndices:vt,positionsDecodeMatrix:Me,color:We,metallic:Xe,roughness:Je,opacity:Ke})),Le.push(Ye))}}Le.length>0&&r.createEntity(he.apply(Ue,{id:Ie,isObject:!0,meshIds:Le}))}}}(e,t,o,r,s,n)}},Tk={};Tk[zF.version]=zF,Tk[XF.version]=XF,Tk[ZF.version]=ZF,Tk[ek.version]=ek,Tk[rk.version]=rk,Tk[ak.version]=ak,Tk[Ak.version]=Ak,Tk[gk.version]=gk,Tk[xk.version]=xk,Tk[Ek.version]=Ek,Tk[Sk.version]=Sk;var Lk=function(e){g(r,Ue);var t,i=_(r);function r(e){var t,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return B(this,r),(t=i.call(this,"XKTLoader",e,s))._maxGeometryBatchSize=s.maxGeometryBatchSize,t.textureTranscoder=s.textureTranscoder,t.dataSource=s.dataSource,t.objectDefaults=s.objectDefaults,t.includeTypes=s.includeTypes,t.excludeTypes=s.excludeTypes,t.excludeUnclassifiedObjects=s.excludeUnclassifiedObjects,t.reuseGeometries=s.reuseGeometries,t}return C(r,[{key:"supportedVersions",get:function(){return Object.keys(Tk)}},{key:"textureTranscoder",get:function(){return this._textureTranscoder},set:function(e){this._textureTranscoder=e}},{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new QF}},{key:"objectDefaults",get:function(){return this._objectDefaults},set:function(e){this._objectDefaults=e||UE}},{key:"includeTypes",get:function(){return this._includeTypes},set:function(e){this._includeTypes=e}},{key:"excludeTypes",get:function(){return this._excludeTypes},set:function(e){this._excludeTypes=e}},{key:"excludeUnclassifiedObjects",get:function(){return this._excludeUnclassifiedObjects},set:function(e){this._excludeUnclassifiedObjects=!!e}},{key:"globalizeObjectIds",get:function(){return this._globalizeObjectIds},set:function(e){this._globalizeObjectIds=!!e}},{key:"reuseGeometries",get:function(){return this._reuseGeometries},set:function(e){this._reuseGeometries=!1!==e}},{key:"load",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(t.id&&this.viewer.scene.components[t.id]&&(this.error("Component with this ID already exists in viewer: "+t.id+" - will autogenerate this ID"),delete t.id),!(t.src||t.xkt||t.manifestSrc||t.manifest))return this.error("load() param expected: src, xkt, manifestSrc or manifestData"),c;var i={},r=t.includeTypes||this._includeTypes,s=t.excludeTypes||this._excludeTypes,n=t.objectDefaults||this._objectDefaults;if(i.reuseGeometries=null!==t.reuseGeometries&&void 0!==t.reuseGeometries?t.reuseGeometries:!1!==this._reuseGeometries,r){i.includeTypesMap={};for(var o=0,a=r.length;o=t.length?n():e._dataSource.getMetaModel("".concat(m).concat(t[a]),(function(t){h.loadData(t,{includeTypes:r,excludeTypes:s,globalizeObjectIds:i.globalizeObjectIds}),a++,e.scheduleTask(l,200)}),o)}()},y=function(r,s,n){var o=0;!function a(){c.destroyed||o>=r.length?s():e._dataSource.getXKT("".concat(m).concat(r[o]),(function(r){e._parseModel(r,t,i,c,null,v),c.preFinalize(),o++,e.scheduleTask(a,200)}),n)}()},b=function(r,s,n){var o=0;!function a(){c.destroyed||o>=r.length?s():e._dataSource.getXKT("".concat(m).concat(r[o]),(function(r){e._parseModel(r,t,i,c,h,v),c.preFinalize(),o++,e.scheduleTask(a,200)}),n)}()};if(t.manifest){var x=t.manifest,w=x.xktFiles;if(!w||0===w.length)return void p("load(): Failed to load model manifest - manifest not valid");var B=x.metaModelFiles;B?_(B,(function(){y(w,d,p)}),p):b(w,d,p)}else this._dataSource.getManifest(t.manifestSrc,(function(e){if(!c.destroyed){var t=e.xktFiles;if(t&&0!==t.length){var i=e.metaModelFiles;i?_(i,(function(){y(t,d,p)}),p):b(t,d,p)}else p("load(): Failed to load model manifest - manifest not valid")}}),p)}return c}},{key:"_loadModel",value:function(e,t,i,r,s,n,o,a){var l=this;this._dataSource.getXKT(t.src,(function(e){l._parseModel(e,t,i,r,s,n),r.preFinalize(),o()}),a)}},{key:"_parseModel",value:(t=u(a().mark((function e(t,i,r,s,n,o){var l,u,c,A,h,d,p,f,v;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!s.destroyed){e.next=2;break}return e.abrupt("return");case 2:if(l=new DataView(t),u=new Uint8Array(t),c=l.getUint32(0,!0),A=Tk[c]){e.next=9;break}return this.error("Unsupported .XKT file version: "+c+" - this XKTLoaderPlugin supports versions "+Object.keys(Tk)),e.abrupt("return");case 9:if(!A.parseArrayBuffer){e.next=12;break}return A.parseArrayBuffer(this.viewer,r,t,s,n,o),e.abrupt("return");case 12:for(h=l.getUint32(4,!0),d=[],p=4*(h+2),f=0;fe.size)throw new RangeError("offset:"+t+", length:"+i+", size:"+e.size);return e.slice?e.slice(t,t+i):e.webkitSlice?e.webkitSlice(t,t+i):e.mozSlice?e.mozSlice(t,t+i):e.msSlice?e.msSlice(t,t+i):void 0}(e,t,i))}catch(e){s(e)}}}function p(){}function f(e){var i,r=this;r.init=function(e){i=new Blob([],{type:o}),e()},r.writeUint8Array=function(e,r){i=new Blob([i,t?e:e.buffer],{type:o}),r()},r.getData=function(t,r){var s=new FileReader;s.onload=function(e){t(e.target.result)},s.onerror=r,s.readAsText(i,e)}}function v(t){var i=this,r="",s="";i.init=function(e){r+="data:"+(t||"")+";base64,",e()},i.writeUint8Array=function(t,i){var n,o=s.length,a=s;for(s="",n=0;n<3*Math.floor((o+t.length)/3)-o;n++)a+=String.fromCharCode(t[n]);for(;n2?r+=e.btoa(a):s=a,i()},i.getData=function(t){t(r+e.btoa(s))}}function g(e){var i,r=this;r.init=function(t){i=new Blob([],{type:e}),t()},r.writeUint8Array=function(r,s){i=new Blob([i,t?r:r.buffer],{type:e}),s()},r.getData=function(e){e(i)}}function m(e,t,i,r,s,o,a,l,u,c){var A,h,d,p=0,f=t.sn;function v(){e.removeEventListener("message",g,!1),l(h,d)}function g(t){var i=t.data,s=i.data,n=i.error;if(n)return n.toString=function(){return"Error: "+this.message},void u(n);if(i.sn===f)switch("number"==typeof i.codecTime&&(e.codecTime+=i.codecTime),"number"==typeof i.crcTime&&(e.crcTime+=i.crcTime),i.type){case"append":s?(h+=s.length,r.writeUint8Array(s,(function(){m()}),c)):m();break;case"flush":d=i.crc,s?(h+=s.length,r.writeUint8Array(s,(function(){v()}),c)):v();break;case"progress":a&&a(A+i.loaded,o);break;case"importScripts":case"newTask":case"echo":break;default:console.warn("zip.js:launchWorkerProcess: unknown message: ",i)}}function m(){(A=p*n)<=o?i.readUint8Array(s+A,Math.min(n,o-A),(function(i){a&&a(A,o);var r=0===A?t:{sn:f};r.type="append",r.data=i;try{e.postMessage(r,[i.buffer])}catch(t){e.postMessage(r)}p++}),u):e.postMessage({sn:f,type:"flush"})}h=0,e.addEventListener("message",g,!1),m()}function _(e,t,i,r,s,o,l,u,c,A){var h,d=0,p=0,f="input"===o,v="output"===o,g=new a;!function o(){var a;if((h=d*n)127?s[i-128]:String.fromCharCode(i);return r}function x(e){return decodeURIComponent(escape(e))}function w(e){var t,i="";for(t=0;t>16,i=65535&e;try{return new Date(1980+((65024&t)>>9),((480&t)>>5)-1,31&t,(63488&i)>>11,(2016&i)>>5,2*(31&i),0)}catch(e){}}(e.lastModDateRaw),1!=(1&e.bitFlag)?((r||8!=(8&e.bitFlag))&&(e.crc32=t.view.getUint32(i+10,!0),e.compressedSize=t.view.getUint32(i+14,!0),e.uncompressedSize=t.view.getUint32(i+18,!0)),4294967295!==e.compressedSize&&4294967295!==e.uncompressedSize?(e.filenameLength=t.view.getUint16(i+22,!0),e.extraFieldLength=t.view.getUint16(i+24,!0)):s("File is using Zip64 (4gb+ file size).")):s("File contains encrypted entry.")}function P(t,n,o){var a=0;function l(){}l.prototype.getData=function(r,n,l,c){var A=this;function h(e,t){c&&!function(e){var t=u(4);return t.view.setUint32(0,e),A.crc32==t.view.getUint32(0)}(t)?o("CRC failed."):r.getData((function(e){n(e)}))}function d(e){o(e||s)}function p(e){o(e||"Error while writing file data.")}t.readUint8Array(A.offset,30,(function(s){var n,f=u(s.length,s);1347093252==f.view.getUint32(0)?(B(A,f,4,!1,o),n=A.offset+30+A.filenameLength+A.extraFieldLength,r.init((function(){0===A.compressionMethod?y(A._worker,a++,t,r,n,A.compressedSize,c,h,l,d,p):function(t,i,r,s,n,o,a,l,u,c,A){var h=a?"output":"none";e.zip.useWebWorkers?m(t,{sn:i,codecClass:"Inflater",crcType:h},r,s,n,o,u,l,c,A):_(new e.zip.Inflater,r,s,n,o,h,u,l,c,A)}(A._worker,a++,t,r,n,A.compressedSize,c,h,l,d,p)}),p)):o(i)}),d)};var c={getEntries:function(e){var s=this._worker;!function(e){t.size<22?o(i):s(22,(function(){s(Math.min(65558,t.size),(function(){o(i)}))}));function s(i,s){t.readUint8Array(t.size-i,i,(function(t){for(var i=t.length-22;i>=0;i--)if(80===t[i]&&75===t[i+1]&&5===t[i+2]&&6===t[i+3])return void e(new DataView(t.buffer,i,22));s()}),(function(){o(r)}))}}((function(n){var a,c;a=n.getUint32(16,!0),c=n.getUint16(8,!0),a<0||a>=t.size?o(i):t.readUint8Array(a,t.size-a,(function(t){var r,n,a,A,h=0,d=[],p=u(t.length,t);for(r=0;r>>8^i[255&(t^e[r])];this.crc=t},a.prototype.get=function(){return~this.crc},a.prototype.table=function(){var e,t,i,r=[];for(e=0;e<256;e++){for(i=e,t=0;t<8;t++)1&i?i=i>>>1^3988292384:i>>>=1;r[e]=i}return r}(),l.prototype.append=function(e,t){return e},l.prototype.flush=function(){},A.prototype=new c,A.prototype.constructor=A,h.prototype=new c,h.prototype.constructor=h,d.prototype=new c,d.prototype.constructor=d,p.prototype.getData=function(e){e(this.data)},f.prototype=new p,f.prototype.constructor=f,v.prototype=new p,v.prototype.constructor=v,g.prototype=new p,g.prototype.constructor=g;var F={deflater:["z-worker.js","deflate.js"],inflater:["z-worker.js","inflate.js"]};function k(t,i,r){if(null===e.zip.workerScripts||null===e.zip.workerScriptsPath){var s;if(e.zip.workerScripts){if(s=e.zip.workerScripts[t],!Array.isArray(s))return void r(new Error("zip.workerScripts."+t+" is not an array!"));s=function(e){var t=document.createElement("a");return e.map((function(e){return t.href=e,t.href}))}(s)}else(s=F[t].slice(0))[0]=(e.zip.workerScriptsPath||"")+s[0];var n=new Worker(s[0]);n.codecTime=n.crcTime=0,n.postMessage({type:"importScripts",scripts:s.slice(1)}),n.addEventListener("message",(function e(t){var s=t.data;if(s.error)return n.terminate(),void r(s.error);"importScripts"===s.type&&(n.removeEventListener("message",e),n.removeEventListener("error",o),i(n))})),n.addEventListener("error",o)}else r(new Error("Either zip.workerScripts or zip.workerScriptsPath may be set, not both."));function o(e){n.terminate(),r(e)}}function I(e){console.error(e)}e.zip={Reader:c,Writer:p,BlobReader:d,Data64URIReader:h,TextReader:A,BlobWriter:g,Data64URIWriter:v,TextWriter:f,createReader:function(e,t,i){i=i||I,e.init((function(){P(e,t,i)}),i)},createWriter:function(e,t,i,r){i=i||I,r=!!r,e.init((function(){E(e,t,i,r)}),i)},useWebWorkers:!0,workerScriptsPath:null,workerScripts:null}}(Uk);var Ok=Uk.zip;!function(e){var t,i,r=e.Reader,s=e.Writer;try{i=0===new Blob([new DataView(new ArrayBuffer(0))]).size}catch(e){}function n(e){var t=this;function i(i,r){var s;t.data?i():((s=new XMLHttpRequest).addEventListener("load",(function(){t.size||(t.size=Number(s.getResponseHeader("Content-Length"))||Number(s.response.byteLength)),t.data=new Uint8Array(s.response),i()}),!1),s.addEventListener("error",r,!1),s.open("GET",e),s.responseType="arraybuffer",s.send())}t.size=0,t.init=function(r,s){if(function(e){var t=document.createElement("a");return t.href=e,"http:"===t.protocol||"https:"===t.protocol}(e)){var n=new XMLHttpRequest;n.addEventListener("load",(function(){t.size=Number(n.getResponseHeader("Content-Length")),t.size?r():i(r,s)}),!1),n.addEventListener("error",s,!1),n.open("HEAD",e),n.send()}else i(r,s)},t.readUint8Array=function(e,r,s,n){i((function(){s(new Uint8Array(t.data.subarray(e,e+r)))}),n)}}function o(e){var t=this;t.size=0,t.init=function(i,r){var s=new XMLHttpRequest;s.addEventListener("load",(function(){t.size=Number(s.getResponseHeader("Content-Length")),"bytes"==s.getResponseHeader("Accept-Ranges")?i():r("HTTP Range not supported.")}),!1),s.addEventListener("error",r,!1),s.open("HEAD",e),s.send()},t.readUint8Array=function(t,i,r,s){!function(t,i,r,s){var n=new XMLHttpRequest;n.open("GET",e),n.responseType="arraybuffer",n.setRequestHeader("Range","bytes="+t+"-"+(t+i-1)),n.addEventListener("load",(function(){r(n.response)}),!1),n.addEventListener("error",s,!1),n.send()}(t,i,(function(e){r(new Uint8Array(e))}),s)}}function a(e){var t=this;t.size=0,t.init=function(i,r){t.size=e.byteLength,i()},t.readUint8Array=function(t,i,r,s){r(new Uint8Array(e.slice(t,t+i)))}}function l(){var e,t=this;t.init=function(t,i){e=new Uint8Array,t()},t.writeUint8Array=function(t,i,r){var s=new Uint8Array(e.length+t.length);s.set(e),s.set(t,e.length),e=s,i()},t.getData=function(t){t(e.buffer)}}function u(e,t){var r,s=this;s.init=function(t,i){e.createWriter((function(e){r=e,t()}),i)},s.writeUint8Array=function(e,s,n){var o=new Blob([i?e:e.buffer],{type:t});r.onwrite=function(){r.onwrite=null,s()},r.onerror=n,r.write(o)},s.getData=function(t){e.file(t)}}n.prototype=new r,n.prototype.constructor=n,o.prototype=new r,o.prototype.constructor=o,a.prototype=new r,a.prototype.constructor=a,l.prototype=new s,l.prototype.constructor=l,u.prototype=new s,u.prototype.constructor=u,e.FileWriter=u,e.HttpReader=n,e.HttpRangeReader=o,e.ArrayBufferReader=a,e.ArrayBufferWriter=l,e.fs&&((t=e.fs.ZipDirectoryEntry).prototype.addHttpContent=function(i,r,s){return function(i,r,s,n){if(i.directory)return n?new t(i.fs,r,s,i):new e.fs.ZipFileEntry(i.fs,r,s,i);throw"Parent entry is not a directory."}(this,i,{data:r,Reader:s?o:n})},t.prototype.importHttpContent=function(e,t,i,r){this.importZip(t?new o(e):new n(e),i,r)},e.fs.FS.prototype.importHttpContent=function(e,i,r,s){this.entries=[],this.root=new t(this),this.root.importHttpContent(e,i,r,s)})}(Ok);var Nk=["4.2"],Qk=function(){function e(t){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};B(this,e),this.supportedSchemas=Nk,this._xrayOpacity=.7,this._src=null,this._options=i,this.viewpoint=null,i.workerScriptsPath?(Ok.workerScriptsPath=i.workerScriptsPath,this.src=i.src,this.xrayOpacity=.7,this.displayEffect=i.displayEffect,this.createMetaModel=i.createMetaModel):t.error("Config expected: workerScriptsPath")}return C(e,[{key:"load",value:function(e,t,i,r,s,n){switch(r.materialType){case"MetallicMaterial":t._defaultMaterial=new Nn(t,{baseColor:[1,1,1],metallic:.6,roughness:.6});break;case"SpecularMaterial":t._defaultMaterial=new Hn(t,{diffuse:[1,1,1],specular:re.vec3([1,1,1]),glossiness:.5});break;default:t._defaultMaterial=new qi(t,{reflectivity:.75,shiness:100,diffuse:[1,1,1]})}t._wireframeMaterial=new Rn(t,{color:[0,0,0],lineWidth:2});var o=t.scene.canvas.spinner;o.processes++,Vk(e,t,i,r,(function(){o.processes--,s&&s(),t.fire("loaded",!0,!1)}),(function(e){o.processes--,t.error(e),n&&n(e),t.fire("error",e)}),(function(e){console.log("Error, Will Robinson: "+e)}))}}]),e}(),Vk=function(e,t,i,r,s,n){!function(e,t,i){var r=new Jk;r.load(e,(function(){t(r)}),(function(e){i("Error loading ZIP archive: "+e)}))}(i,(function(i){Hk(e,i,r,t,s,n)}),n)},Hk=function(){return function(t,i,r,s,n){var o={plugin:t,zip:i,edgeThreshold:30,materialType:r.materialType,scene:s.scene,modelNode:s,info:{references:{}},materials:{}};r.createMetaModel&&(o.metaModelData={modelId:s.id,metaObjects:[{name:s.id,type:"Default",id:s.id}]}),s.scene.loading++,function(t,i){t.zip.getFile("Manifest.xml",(function(r,s){for(var n=s.children,o=0,a=n.length;o0){for(var o=n.trim().split(" "),a=new Int16Array(o.length),l=0,u=0,c=o.length;u0){i.primitive="triangles";for(var n=[],o=0,a=s.length;o=t.length)i();else{var a=t[n].id,l=a.lastIndexOf(":");l>0&&(a=a.substring(l+1));var u=a.lastIndexOf("#");u>0&&(a=a.substring(0,u)),r[a]?s(n+1):function(e,t,i){e.zip.getFile(t,(function(t,r){!function(e,t,i){for(var r,s=t.children,n=0,o=s.length;n0)for(var r=0,s=t.length;r1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),r=t.call(this,"XML3DLoader",e,s),s.workerScriptsPath?(r._workerScriptsPath=s.workerScriptsPath,r._loader=new Qk(b(r),s),r.supportedSchemas=r._loader.supportedSchemas,r):(r.error("Config expected: workerScriptsPath"),y(r))}return C(i,[{key:"load",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e.workerScriptsPath=this._workerScriptsPath,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);var t=new Ln(this.viewer.scene,he.apply(e,{isModel:!0})),i=e.src;return i?(this._loader.load(this,t,i,e),t):(this.error("load() param expected: src"),t)}}]),i}(),qk=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};B(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getIFC",value:function(e,t,i){e=this._cacheBusterURL(e);var r=function(){};t=t||r,i=i||r;var s=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(s){var n=!!s[2],o=s[3];o=window.decodeURIComponent(o),n&&(o=window.atob(o));try{for(var a=new ArrayBuffer(o.length),l=new Uint8Array(a),u=0;u1&&void 0!==arguments[1]?arguments[1]:{};if(B(this,i),(r=t.call(this,"ifcLoader",e,s)).dataSource=s.dataSource,r.objectDefaults=s.objectDefaults,r.includeTypes=s.includeTypes,r.excludeTypes=s.excludeTypes,r.excludeUnclassifiedObjects=s.excludeUnclassifiedObjects,!s.WebIFC)throw"Parameter expected: WebIFC";if(!s.IfcAPI)throw"Parameter expected: IfcAPI";return r._webIFC=s.WebIFC,r._ifcAPI=s.IfcAPI,r}return C(i,[{key:"supportedVersions",get:function(){return["2x3","4"]}},{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new qk}},{key:"objectDefaults",get:function(){return this._objectDefaults},set:function(e){this._objectDefaults=e||UE}},{key:"includeTypes",get:function(){return this._includeTypes},set:function(e){this._includeTypes=e}},{key:"excludeTypes",get:function(){return this._excludeTypes},set:function(e){this._excludeTypes=e}},{key:"excludeUnclassifiedObjects",get:function(){return this._excludeUnclassifiedObjects},set:function(e){this._excludeUnclassifiedObjects=!!e}},{key:"globalizeObjectIds",get:function(){return this._globalizeObjectIds},set:function(e){this._globalizeObjectIds=!!e}},{key:"load",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};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);var t=new Qh(this.viewer.scene,he.apply(e,{isModel:!0}));if(!e.src&&!e.ifc)return this.error("load() param expected: src or IFC"),t;var i={autoNormals:!0};if(!1!==e.loadMetadata){var r=e.includeTypes||this._includeTypes,s=e.excludeTypes||this._excludeTypes,n=e.objectDefaults||this._objectDefaults;if(r){i.includeTypesMap={};for(var o=0,a=r.length;o0){for(var l=n.Name.value,u=[],c=0,A=a.length;c0&&void 0!==arguments[0]?arguments[0]:{};B(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getLAS",value:function(e,t,i){e=this._cacheBusterURL(e);var r=function(){};t=t||r,i=i||r;var s=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(s){var n=!!s[2],o=s[3];o=window.decodeURIComponent(o),n&&(o=window.atob(o));try{for(var a=new ArrayBuffer(o.length),l=new Uint8Array(a),u=0;u1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),(r=t.call(this,"lasLoader",e,s)).dataSource=s.dataSource,r.skip=s.skip,r.fp64=s.fp64,r.colorDepth=s.colorDepth,r}return C(i,[{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new eI}},{key:"skip",get:function(){return this._skip},set:function(e){this._skip=e||1}},{key:"fp64",get:function(){return this._fp64},set:function(e){this._fp64=!!e}},{key:"colorDepth",get:function(){return this._colorDepth},set:function(e){this._colorDepth=e||"auto"}},{key:"load",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.id&&this.viewer.scene.components[t.id]&&(this.error("Component with this ID already exists in viewer: "+t.id+" - will autogenerate this ID"),delete t.id);var i=new Qh(this.viewer.scene,he.apply(t,{maxGeometryBatchSize:5e5,isModel:!0}));if(!t.src&&!t.las)return this.error("load() param expected: src or las"),i;var r={las:{skip:this._skip,fp64:this._fp64,colorDepth:this._colorDepth}};if(t.src)this._loadModel(t.src,t,r,i);else{var s=this.viewer.scene.canvas.spinner;s.processes++,this._parseModel(t.las,t,r,i).then((function(){s.processes--}),(function(t){s.processes--,e.error(t),i.fire("error",t)}))}return i}},{key:"_loadModel",value:function(e,t,i,r){var s=this,n=this.viewer.scene.canvas.spinner;n.processes++,this._dataSource.getLAS(t.src,(function(e){s._parseModel(e,t,i,r).then((function(){n.processes--}),(function(e){n.processes--,s.error(e),r.fire("error",e)}))}),(function(e){n.processes--,s.error(e),r.fire("error",e)}))}},{key:"_parseModel",value:function(e,t,i,r){var s=this;function n(e){var i=e.value;if(t.rotateX&&i)for(var r=0,s=i.length;r=e.length)return[e];for(var i=[],r=0;r0&&void 0!==arguments[0]?arguments[0]:{};B(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getCityJSON",value:function(e,t,i){he.loadJSON(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}}]),e}();function cI(e,t,i){i=i||2;var r,s,n,o,a,l,u,c=t&&t.length,A=c?t[0]*i:e.length,h=AI(e,0,A,i,!0),d=[];if(!h||h.next===h.prev)return d;if(c&&(h=function(e,t,i,r){var s,n,o,a=[];for(s=0,n=t.length;s80*i){r=n=e[0],s=o=e[1];for(var p=i;pn&&(n=a),l>o&&(o=l);u=0!==(u=Math.max(n-r,o-s))?1/u:0}return dI(h,d,i,r,s,u),d}function AI(e,t,i,r,s){var n,o;if(s===LI(e,t,i,r)>0)for(n=t;n=t;n-=r)o=DI(n,e[n],e[n+1],o);return o&&CI(o,o.next)&&(SI(o),o=o.next),o}function hI(e,t){if(!e)return e;t||(t=e);var i,r=e;do{if(i=!1,r.steiner||!CI(r,r.next)&&0!==PI(r.prev,r,r.next))r=r.next;else{if(SI(r),(r=t=r.prev)===r.next)break;i=!0}}while(i||r!==t);return t}function dI(e,t,i,r,s,n,o){if(e){!o&&n&&function(e,t,i,r){var s=e;do{null===s.z&&(s.z=bI(s.x,s.y,t,i,r)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next}while(s!==e);s.prevZ.nextZ=null,s.prevZ=null,function(e){var t,i,r,s,n,o,a,l,u=1;do{for(i=e,e=null,n=null,o=0;i;){for(o++,r=i,a=0,t=0;t0||l>0&&r;)0!==a&&(0===l||!r||i.z<=r.z)?(s=i,i=i.nextZ,a--):(s=r,r=r.nextZ,l--),n?n.nextZ=s:e=s,s.prevZ=n,n=s;i=r}n.nextZ=null,u*=2}while(o>1)}(s)}(e,r,s,n);for(var a,l,u=e;e.prev!==e.next;)if(a=e.prev,l=e.next,n?fI(e,r,s,n):pI(e))t.push(a.i/i),t.push(e.i/i),t.push(l.i/i),SI(e),e=l.next,u=l.next;else if((e=l)===u){o?1===o?dI(e=vI(hI(e),t,i),t,i,r,s,n,2):2===o&&gI(e,t,i,r,s,n):dI(hI(e),t,i,r,s,n,1);break}}}function pI(e){var t=e.prev,i=e,r=e.next;if(PI(t,i,r)>=0)return!1;for(var s=e.next.next;s!==e.prev;){if(wI(t.x,t.y,i.x,i.y,r.x,r.y,s.x,s.y)&&PI(s.prev,s,s.next)>=0)return!1;s=s.next}return!0}function fI(e,t,i,r){var s=e.prev,n=e,o=e.next;if(PI(s,n,o)>=0)return!1;for(var a=s.xn.x?s.x>o.x?s.x:o.x:n.x>o.x?n.x:o.x,c=s.y>n.y?s.y>o.y?s.y:o.y:n.y>o.y?n.y:o.y,A=bI(a,l,t,i,r),h=bI(u,c,t,i,r),d=e.prevZ,p=e.nextZ;d&&d.z>=A&&p&&p.z<=h;){if(d!==e.prev&&d!==e.next&&wI(s.x,s.y,n.x,n.y,o.x,o.y,d.x,d.y)&&PI(d.prev,d,d.next)>=0)return!1;if(d=d.prevZ,p!==e.prev&&p!==e.next&&wI(s.x,s.y,n.x,n.y,o.x,o.y,p.x,p.y)&&PI(p.prev,p,p.next)>=0)return!1;p=p.nextZ}for(;d&&d.z>=A;){if(d!==e.prev&&d!==e.next&&wI(s.x,s.y,n.x,n.y,o.x,o.y,d.x,d.y)&&PI(d.prev,d,d.next)>=0)return!1;d=d.prevZ}for(;p&&p.z<=h;){if(p!==e.prev&&p!==e.next&&wI(s.x,s.y,n.x,n.y,o.x,o.y,p.x,p.y)&&PI(p.prev,p,p.next)>=0)return!1;p=p.nextZ}return!0}function vI(e,t,i){var r=e;do{var s=r.prev,n=r.next.next;!CI(s,n)&&MI(s,r,r.next,n)&&kI(s,n)&&kI(n,s)&&(t.push(s.i/i),t.push(r.i/i),t.push(n.i/i),SI(r),SI(r.next),r=e=n),r=r.next}while(r!==e);return hI(r)}function gI(e,t,i,r,s,n){var o=e;do{for(var a=o.next.next;a!==o.prev;){if(o.i!==a.i&&BI(o,a)){var l=II(o,a);return o=hI(o,o.next),l=hI(l,l.next),dI(o,t,i,r,s,n),void dI(l,t,i,r,s,n)}a=a.next}o=o.next}while(o!==e)}function mI(e,t){return e.x-t.x}function _I(e,t){if(t=function(e,t){var i,r=t,s=e.x,n=e.y,o=-1/0;do{if(n<=r.y&&n>=r.next.y&&r.next.y!==r.y){var a=r.x+(n-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(a<=s&&a>o){if(o=a,a===s){if(n===r.y)return r;if(n===r.next.y)return r.next}i=r.x=r.x&&r.x>=c&&s!==r.x&&wI(ni.x||r.x===i.x&&yI(i,r)))&&(i=r,h=l)),r=r.next}while(r!==u);return i}(e,t),t){var i=II(t,e);hI(t,t.next),hI(i,i.next)}}function yI(e,t){return PI(e.prev,e,t.prev)<0&&PI(t.next,e,e.next)<0}function bI(e,t,i,r,s){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-i)*s)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*s)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function xI(e){var t=e,i=e;do{(t.x=0&&(e-o)*(r-a)-(i-o)*(t-a)>=0&&(i-o)*(n-a)-(s-o)*(r-a)>=0}function BI(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){var i=e;do{if(i.i!==e.i&&i.next.i!==e.i&&i.i!==t.i&&i.next.i!==t.i&&MI(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}(e,t)&&(kI(e,t)&&kI(t,e)&&function(e,t){var i=e,r=!1,s=(e.x+t.x)/2,n=(e.y+t.y)/2;do{i.y>n!=i.next.y>n&&i.next.y!==i.y&&s<(i.next.x-i.x)*(n-i.y)/(i.next.y-i.y)+i.x&&(r=!r),i=i.next}while(i!==e);return r}(e,t)&&(PI(e.prev,e,t.prev)||PI(e,t.prev,t))||CI(e,t)&&PI(e.prev,e,e.next)>0&&PI(t.prev,t,t.next)>0)}function PI(e,t,i){return(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y)}function CI(e,t){return e.x===t.x&&e.y===t.y}function MI(e,t,i,r){var s=FI(PI(e,t,i)),n=FI(PI(e,t,r)),o=FI(PI(i,r,e)),a=FI(PI(i,r,t));return s!==n&&o!==a||(!(0!==s||!EI(e,i,t))||(!(0!==n||!EI(e,r,t))||(!(0!==o||!EI(i,e,r))||!(0!==a||!EI(i,t,r)))))}function EI(e,t,i){return t.x<=Math.max(e.x,i.x)&&t.x>=Math.min(e.x,i.x)&&t.y<=Math.max(e.y,i.y)&&t.y>=Math.min(e.y,i.y)}function FI(e){return e>0?1:e<0?-1:0}function kI(e,t){return PI(e.prev,e,e.next)<0?PI(e,t,e.next)>=0&&PI(e,e.prev,t)>=0:PI(e,t,e.prev)<0||PI(e,e.next,t)<0}function II(e,t){var i=new TI(e.i,e.x,e.y),r=new TI(t.i,t.x,t.y),s=e.next,n=t.prev;return e.next=t,t.prev=e,i.next=s,s.prev=i,r.next=i,i.prev=r,n.next=r,r.prev=n,r}function DI(e,t,i,r){var s=new TI(e,t,i);return r?(s.next=r.next,s.prev=r,r.next.prev=s,r.next=s):(s.prev=s,s.next=s),s}function SI(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function TI(e,t,i){this.i=e,this.x=t,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function LI(e,t,i,r){for(var s=0,n=t,o=i-r;n0&&(r+=e[s-1].length,i.holes.push(r))}return i};var RI=re.vec2(),UI=re.vec3(),OI=re.vec3(),NI=re.vec3(),QI=function(e){g(i,Ue);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),(r=t.call(this,"cityJSONLoader",e,s)).dataSource=s.dataSource,r}return C(i,[{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new uI}},{key:"load",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};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);var t=new Qh(this.viewer.scene,he.apply(e,{isModel:!0,edges:!0}));if(!e.src&&!e.cityJSON)return this.error("load() param expected: src or cityJSON"),t;var i={};if(e.src)this._loadModel(e.src,e,i,t);else{var r=this.viewer.scene.canvas.spinner;r.processes++,this._parseModel(e.cityJSON,e,i,t),r.processes--}return t}},{key:"_loadModel",value:function(e,t,i,r){var s=this,n=this.viewer.scene.canvas.spinner;n.processes++,this._dataSource.getCityJSON(t.src,(function(e){s._parseModel(e,t,i,r),n.processes--}),(function(e){n.processes--,s.error(e),r.fire("error",e)}))}},{key:"_parseModel",value:function(e,t,i,r){if(!r.destroyed){var s=e.transform?this._transformVertices(e.vertices,e.transform,i.rotateX):e.vertices,n=t.stats||{};n.sourceFormat=e.type||"CityJSON",n.schemaVersion=e.version||"",n.title="",n.author="",n.created="",n.numMetaObjects=0,n.numPropertySets=0,n.numObjects=0,n.numGeometries=0,n.numTriangles=0,n.numVertices=0;var o=!1!==t.loadMetadata,a=o?{id:re.createUUID(),name:"Model",type:"Model"}:null,l=o?{id:"",projectId:"",author:"",createdAt:"",schema:e.version||"",creatingApplication:"",metaObjects:[a],propertySets:[]}:null,u={data:e,vertices:s,sceneModel:r,loadMetadata:o,metadata:l,rootMetaObject:a,nextId:0,stats:n};if(this._parseCityJSON(u),r.finalize(),o){var c=r.id;this.viewer.metaScene.createMetaModel(c,u.metadata,i)}r.scene.once("tick",(function(){r.destroyed||(r.scene.fire("modelLoaded",r.id),r.fire("loaded",!0,!1))}))}}},{key:"_transformVertices",value:function(e,t,i){for(var r=[],s=t.scale||re.vec3([1,1,1]),n=t.translate||re.vec3([0,0,0]),o=0,a=0;o0){for(var u=[],c=0,A=t.geometry.length;c0){var _=g[m[0]];if(void 0!==_.value)d=v[_.value];else{var y=_.values;if(y){p=[];for(var b=0,x=y.length;b0&&(r.createEntity({id:i,meshIds:u,isObject:!0}),e.stats.numObjects++)}}},{key:"_parseGeometrySurfacesWithOwnMaterials",value:function(e,t,i,r){switch(t.type){case"MultiPoint":case"MultiLineString":break;case"MultiSurface":case"CompositeSurface":var s=t.boundaries;this._parseSurfacesWithOwnMaterials(e,i,s,r);break;case"Solid":for(var n=t.boundaries,o=0;o0&&c.push(u.length);var f=this._extractLocalIndices(e,a[p],A,d);u.push.apply(u,h(f))}if(3===u.length)d.indices.push(u[0]),d.indices.push(u[1]),d.indices.push(u[2]);else if(u.length>3){for(var v=[],g=0;g0&&o.indices.length>0){var f=""+e.nextId++;s.createMesh({id:f,primitive:"triangles",positions:o.positions,indices:o.indices,color:i&&i.diffuseColor?i.diffuseColor:[.8,.8,.8],opacity:1}),r.push(f),e.stats.numGeometries++,e.stats.numVertices+=o.positions.length/3,e.stats.numTriangles+=o.indices.length/3}}},{key:"_parseSurfacesWithSharedMaterial",value:function(e,t,i,r){for(var s=e.vertices,n=0;n0&&a.push(o.length);var u=this._extractLocalIndices(e,t[n][l],i,r);o.push.apply(o,h(u))}if(3===o.length)r.indices.push(o[0]),r.indices.push(o[1]),r.indices.push(o[2]);else if(o.length>3){for(var c=[],A=0;A0&&void 0!==arguments[0]?arguments[0]:{};B(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getDotBIM",value:function(e,t,i){he.loadJSON(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}}]),e}(),HI=function(e){g(i,Ue);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),(r=t.call(this,"DotBIMLoader",e,s)).dataSource=s.dataSource,r.objectDefaults=s.objectDefaults,r}return C(i,[{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new VI}},{key:"objectDefaults",get:function(){return this._objectDefaults},set:function(e){this._objectDefaults=e||UE}},{key:"load",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.id&&this.viewer.scene.components[t.id]&&(this.error("Component with this ID already exists in viewer: "+t.id+" - will autogenerate this ID"),delete t.id);var i=new Qh(this.viewer.scene,he.apply(t,{isModel:!0,backfaces:t.backfaces,dtxEnabled:t.dtxEnabled,rotation:t.rotation,origin:t.origin})),r=i.id;if(!t.src&&!t.dotBIM)return this.error("load() param expected: src or dotBIM"),i;var s,n,o=t.objectDefaults||this._objectDefaults||UE;if(t.includeTypes){s={};for(var a=0,l=t.includeTypes.length;a=0?c:2*Math.PI-c}return s0||o>0||a>0))}}(),n=[],o=(r?t:t.slice(0).reverse()).map((function(e){return{idx:e}}));o.forEach((function(e,t){e.prev=o[(t-1+o.length)%o.length],e.next=o[(t+1)%o.length]}));for(var a=re.vec2(),l=re.vec2();o.length>2;){for(var u=0,c=function(){if(u>=o.length)throw"isCCW = ".concat(r,"; earIdx = ").concat(u,"; len = ").concat(o.length);var t=o[u],i=e[t.prev.idx],n=e[t.idx],c=e[t.next.idx];if(re.subVec2(i,n,a),re.subVec2(c,n,l),a[0]*l[1]-a[1]*l[0]>=0&&o.every((function(r){return r===t||r===t.prev||r===t.next||!s(e[r.idx],i,n,c)})))return"break";++u};;){if("break"===c())break}var A=o[u];o.splice(u,1),n.push([A.idx,A.next.idx,A.prev.idx]),A.prev.next=A.next,A.next.prev=A.prev}return[e,n,r]},zI=function(e,t){var i=e.canvas.canvas,r=i.parentNode,s=document.createElement("div");r.insertBefore(s,i);var n=5;s.style.background=t,s.style.border="2px solid white",s.style.margin="0 0",s.style.zIndex="100",s.style.position="absolute",s.style.pointerEvents="none",s.style.display="none";var o=new ot(e,{}),a=function(e){return e+"px"},l=function(){var e=o.canvasPos.slice();lt(i,r,e),s.style.left=a(e[0]-3-n/2),s.style.top=a(e[1]-3-n/2),s.style.borderRadius=a(2*n),s.style.width=a(n),s.style.height=a(n)},u=e.camera.on("viewMatrix",l),c=e.camera.on("projMatrix",l);return{update:function(e){e&&(o.worldPos=e,l()),s.style.display=e?"":"none"},setHighlighted:function(e){n=e?10:5,l()},getCanvasPos:function(){return o.canvasPos},getWorldPos:function(){return o.worldPos},destroy:function(){s.parentNode.removeChild(s),e.camera.off(u),e.camera.off(c),o.destroy()}}},WI=function(e,t,i){var r=null,s=function(s){if(s){r&&r.destroy();try{var n,o,a=GI(s.map((function(e){return[e[0],e[2]]}))),l=A(a,2),u=l[0],c=l[1],d=(n=[]).concat.apply(n,h(u.map((function(e){return[e[0],s[0][1],e[1]]})))),p=(o=[]).concat.apply(o,h(c));r=new mn(e,{pickable:!1,geometry:new Ki(e,{positions:d,indices:p,normals:re.buildNormals(d,p)}),material:new qi(e,{alpha:void 0!==i?i:.5,backfaces:!0,diffuse:jI(t)})})}catch(e){r=null}}r&&(r.visible=!!s)};return s(null),{updateBase:s,destroy:function(){return r&&r.destroy()}}},KI=function(e,t){return function(i,r,s){var n=e.scene,o=n.canvas.canvas,a=function(e,t){return t[0]=e.clientX,t[1]=e.clientY,lt(o.ownerDocument.documentElement,o,t),t},l=function(e){var i=re.vec3(),r=re.vec3();return re.canvasPosToWorldRay(o,n.camera.viewMatrix,n.camera.projMatrix,n.camera.projection,e,i,r),t(i,r)},u=!1,c=function(){u=!1},A=function(){c(),o.removeEventListener("mousedown",d),o.removeEventListener("mousemove",p),e.cameraControl.off(f),o.removeEventListener("mouseup",v)},h=re.vec2(),d=function(e){1===e.which&&(a(e,h),u=!0)};o.addEventListener("mousedown",d);var p=function(e){var t=a(e,re.vec2());u&&re.distVec2(h,t)>20&&(c(),i())};o.addEventListener("mousemove",p);var f=e.cameraControl.on("rayMove",(function(e){var t=e.canvasPos;r(t,l(t))})),v=function(e){if(1===e.which&&u){A();var t=a(e,re.vec2());s(t,l(t))}};return o.addEventListener("mouseup",v),A}},XI=function(e,t,i,r){var s=-(re.dotVec3(i,t)-e)/re.dotVec3(r,t),n=re.vec3();return re.mulVec3Scalar(r,s,n),re.addVec3(i,n,n),n},JI=function(e){g(i,Ce);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(B(this,i),(r=t.call(this,e.viewer.scene,s)).plugin=e,r._container=s.container,!r._container)throw"config missing: container";return r._eventSubs={},r.plugin.viewer.scene,r._geometry=s.geometry,s.onMouseOver,s.onMouseLeave,s.onContextMenu,r._alpha="alpha"in s&&void 0!==s.alpha?s.alpha:.5,r.color=s.color,r._visible=!0,r._rebuildMesh(),r}return C(i,[{key:"_rebuildMesh",value:function(){var e,t=this.plugin.viewer.scene,i=this._geometry.planeCoordinates.slice(),r=this._geometry.height<0,s=this._geometry.altitude+(r?this._geometry.height:0),n=this._geometry.height*(r?-1:1),o=A(GI(i),3),a=o[0],l=o[1],u=o[2],d=[],p=[],f=function(e){var t,i=d.length,r=c(a);try{for(r.s();!(t=r.n()).done;){var o=t.value;d.push([o[0],s+(e?n:0),o[1]])}}catch(e){r.e(e)}finally{r.f()}var u,A=c(l);try{for(A.s();!(u=A.n()).done;){var f=u.value;p.push.apply(p,h((e?f:f.slice(0).reverse()).map((function(e){return e+i}))))}}catch(e){A.e(e)}finally{A.f()}};f(!1),f(!0);for(var v=function(e){var t=a[e],i=a[(a.length+e+(u?1:-1))%a.length],r=s,o=s+n,l=d.length;d.push([t[0],r,t[1]],[i[0],r,i[1]],[i[0],o,i[1]],[t[0],o,t[1]]),p.push.apply(p,h([0,1,2,0,2,3].map((function(e){return e+l}))))},g=0;gb?1:0;x|=C,w.push(C)}switch(x){case 0:case 1:m.push(y);break;case 2:break;case 3:for(var M=[],E=0;E=3&&m.push(M)}}}catch(e){_.e(e)}finally{_.f()}i=m}}catch(e){d.e(e)}finally{d.f()}if(0===i.length)return null;var U,O=re.vec3([0,0,0]),N=new Set,Q=c(i);try{for(Q.s();!(U=Q.n()).done;){var V,H=c(U.value);try{for(H.s();!(V=H.n()).done;){var j=V.value,G=j.map((function(e){return e.toFixed(3)})).join(":");N.has(G)||(N.add(G),re.addVec3(O,j,O))}}catch(e){H.e(e)}finally{H.f()}}}catch(e){Q.e(e)}finally{Q.f()}return re.mulVec3Scalar(O,1/N.size,O),O}},{key:"center",get:function(){return this._center}},{key:"altitude",get:function(){return this._geometry.altitude},set:function(e){this._geometry.altitude=e,this._rebuildMesh()}},{key:"height",get:function(){return this._geometry.height},set:function(e){this._geometry.height=e,this._rebuildMesh()}},{key:"highlighted",get:function(){return this._highlighted},set:function(e){this._highlighted=e,this._zoneMesh&&(this._zoneMesh.highlighted=e)}},{key:"color",get:function(){return this._color},set:function(e){this._color=e,this._zoneMesh&&(this._zoneMesh.material.diffuse=jI(this._color))}},{key:"alpha",get:function(){return this._alpha},set:function(e){this._alpha=e,this._zoneMesh&&(this._zoneMesh.material.alpha=this._alpha)}},{key:"edges",get:function(){return this._edges},set:function(e){this._edges=e,this._zoneMesh&&(this._zoneMesh.edges=this._edges)}},{key:"visible",get:function(){return this._visible},set:function(e){this._visible=!!e,this._zoneMesh.visible=this._visible,this._needUpdate()}},{key:"getJSON",value:function(){return{id:this.id,geometry:this._geometry,alpha:this._alpha,color:this._color}}},{key:"duplicate",value:function(){return this.plugin.createZone({id:re.createUUID(),geometry:{planeCoordinates:this._geometry.planeCoordinates.map((function(e){return e.slice()})),altitude:this._geometry.altitude,height:this._geometry.height},alpha:this._alpha,color:this._color})}},{key:"destroy",value:function(){this._zoneMesh.destroy(),f(x(i.prototype),"destroy",this).call(this)}}]),i}(),YI=function(e){g(i,Ce);var t=_(i);function i(e,r,s){var n;return B(this,i),(n=t.call(this,e.viewer.scene)).zonesPlugin=e,n.pointerLens=r.pointerLens,n.createSelect3dPoint=s,n._deactivate=null,n}return C(i,[{key:"active",get:function(){return!!this._deactivate}},{key:"activate",value:function(e,t,i,r){if(!this._deactivate){if("object"===w(e)&&null!==e){var s=e,n=function(e,t){if(e in s)return s[e];if(void 0!==t)return t;throw"config missing: "+e};e=n("altitude"),t=n("height"),i=n("color","#008000"),r=n("alpha",.5)}var o=this.zonesPlugin,a=o.viewer,l=a.scene,u=this,c=this.createSelect3dPoint(a,(function(t,i){return XI(e,re.vec3([0,1,0]),t,i)}));!function s(){var n=WI(l,i,r),a=function(e,t,i,r,s,n){var o=zI(e,t),a=zI(e,t),l=i?function(e){i.visible=!!e,e&&(i.canvasPos=e)}:function(){},u=r((function(){l(null),o.update(null)}),(function(e,t){l(e),o.update(t)}),(function(e,t){o.update(t),u=r((function(){l(null),a.update(null),s(null)}),(function(e,i){l(e),a.update(i),s(re.distVec3(t,i)>.01&&[t,i])}),(function(e,i){a.update(i),o.destroy(),a.destroy(),l(null),n([t,i])}))}));return{deactivate:function(){u(),o.destroy(),a.destroy(),l(null)}}}(l,i,u.pointerLens,c,(function(e){if(e){var t=e[0],i=e[1],r=function(e){return Math.min(t[e],i[e])},s=function(e){return Math.max(t[e],i[e])},o=r(0),a=r(1),l=r(2),u=s(0);s(1);var c=s(2);n.updateBase([[o,a,c],[u,a,c],[u,a,l],[o,a,l]])}else n.updateBase(null)}),(function(a){n.destroy();var l=function(e,t,i,r,s,n,o){var a=function(i){return Math.min(e[i],t[i])},l=function(i){return Math.max(e[i],t[i])},u=a(0),c=a(2),A=l(0),h=l(2);return o.createZone({id:re.createUUID(),geometry:{planeCoordinates:[[u,h],[A,h],[A,c],[u,c]],altitude:i,height:r},alpha:n,color:s})}(a[0],a[1],e,t,i,r,o),c=!0;u._deactivate=function(){c=!1},u.fire("zoneEnd",l),c&&s()})).deactivate;u._deactivate=function(){a(),n.destroy()}}()}}},{key:"deactivate",value:function(){this._deactivate&&(this._deactivate(),this._deactivate=null)}},{key:"destroy",value:function(){this.deactivate(),f(x(i.prototype),"destroy",this).call(this)}}]),i}(),ZI=function(e){g(i,YI);var t=_(i);function i(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),t.call(this,e,r,(function(e,t){return KI(e,t)}))}return C(i)}(),qI=function(e){g(i,YI);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};B(this,i);var n=new Re(e.viewer);return(r=t.call(this,e,s,(function(e,t){return ht(e,n,t)}))).pointerCircle=n,r}return C(i,[{key:"destroy",value:function(){this.pointerCircle.destroy(),f(x(i.prototype),"destroy",this).call(this)}}]),i}(),$I=function(e){g(i,Ue);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),(r=t.call(this,"Zones",e))._pointerLens=s.pointerLens,r._container=s.container||document.body,r._zones=[],r.defaultColor=void 0!==s.defaultColor?s.defaultColor:"#00BBFF",r.zIndex=s.zIndex||1e4,r._onMouseOver=function(e,t){r.fire("mouseOver",{plugin:b(r),zone:t,event:e})},r._onMouseLeave=function(e,t){r.fire("mouseLeave",{plugin:b(r),zone:t,event:e})},r._onContextMenu=function(e,t){r.fire("contextMenu",{plugin:b(r),zone:t,event:e})},r}return C(i,[{key:"createZone",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.viewer.scene.components[t.id]&&(this.error("Viewer scene component with this ID already exists: "+t.id),delete t.id);var i=new JI(this,{id:t.id,plugin:this,container:this._container,geometry:t.geometry,alpha:t.alpha,color:t.color,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._zones.push(i),i.on("destroyed",(function(){var t=e._zones.indexOf(i);t>=0&&e._zones.splice(t,1)})),this.fire("zoneCreated",i),i}},{key:"zones",get:function(){return this._zones}},{key:"destroy",value:function(){f(x(i.prototype),"destroy",this).call(this)}}]),i}(),eD=function(e,t,i,r,s,n,o,a,l){var u,c=n?function(e){n.visible=!!e,e&&(n.canvasPos=e)}:function(){},A=[function(){return c(null)}],h=WI(e,r,s);return A.push((function(){return h.destroy()})),function n(d){var p=zI(e,r),f=d.length>0&&function(e,t,i){var r=e.canvas.canvas,s=new ot(e,{});s.worldPos=i;var n=new ot(e,{}),o=r.ownerDocument.body,a=new dt(o,{color:t,thickness:1,thicknessClickable:6});a.setVisible(!1);var l=function(){var e=s.canvasPos.slice(),t=n.canvasPos.slice();lt(r,o,e),lt(r,o,t),a.setStartAndEnd(e[0],e[1],t[0],t[1])},u=e.camera.on("viewMatrix",l),c=e.camera.on("projMatrix",l);return{update:function(e){e&&(n.worldPos=e,l()),a.setVisible(!!e)},destroy:function(){e.camera.off(u),e.camera.off(c),s.destroy(),n.destroy(),a.destroy()}}}(e,r,d[d.length-1].getWorldPos());A.push((function(){p.destroy(),f&&f.destroy()}));var v=d.length>0&&d[0],g=function(e){var t=v&&v.getCanvasPos();return t&&re.distVec2(t,e)<10&&{canvasPos:t,worldPos:v.getWorldPos()}},m=function(){var e=function(e,t,i){return t[0]<=Math.max(e[0],i[0])&&t[0]>=Math.min(e[0],i[0])&&t[1]<=Math.max(e[1],i[1])&&t[1]>=Math.min(e[1],i[1])},t=function(e,t,i){var r=(t[1]-e[1])*(i[0]-t[0])-(t[0]-e[0])*(i[1]-t[1]);return 0===r?0:r>0?1:2};return function(i,r){for(var s=i[i.length-2],n=i[i.length-1],o=r?1:0;o2?d.map((function(e){return e.getWorldPos()})):null)}),(function(e,t){var i=d.length>2&&g(e);if(v&&v.setHighlighted(!!i),c(i?i.canvasPos:e),p.update(!i&&t),f&&f.update(i?i.worldPos:t),d.length>=2){var r=d.map((function(e){return e.getWorldPos()})).concat(i?[]:[t]),s=m(r.map((function(e){return[e[0],e[2]]})),i);h.updateBase(s?null:r)}else h.updateBase(null)}),(function(e,a){var u=d.length>2&&g(e),c=d.map((function(e){return e.getWorldPos()})).concat(u?[]:[a]);h.updateBase(c);var v=c.map((function(e){return[e[0],e[2]]}));d.length>2&&m(v,u)?(A.pop()(),n(d)):u?(p.update(a),A.forEach((function(e){return e()})),l(o.createZone({id:re.createUUID(),geometry:{planeCoordinates:v,altitude:t,height:i},alpha:s,color:r}))):(p.update(a),f&&f.update(a),n(d.concat(p)))}))}([]),{closeSurface:function(){throw"TODO"},deactivate:function(){u(),A.forEach((function(e){return e()}))}}},tD=function(e){g(i,Ce);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),(r=t.call(this,e.viewer.scene)).zonesPlugin=e,r.pointerLens=s.pointerLens,r._action=null,r}return C(i,[{key:"active",get:function(){return!!this._action}},{key:"activate",value:function(e,t,i,r){if("object"===w(e)&&null!==e){var s=e,n=function(e,t){if(e in s)return s[e];if(void 0!==t)return t;throw"config missing: "+e};e=n("altitude"),t=n("height"),i=n("color","#008000"),r=n("alpha",.5)}if(!this._action){var o=this.zonesPlugin,a=o.viewer,l=a.scene,u=this,c=KI(a,(function(t,i){return XI(e,re.vec3([0,1,0]),t,i)}));!function s(){u._action=eD(l,e,t,i,r,u.pointerLens,o,c,(function(e){var t=!0;u._action={deactivate:function(){t=!1}},u.fire("zoneEnd",e),t&&s()}))}()}}},{key:"deactivate",value:function(){this._action&&(this._action.deactivate(),this._action=null)}},{key:"destroy",value:function(){this.deactivate(),f(x(i.prototype),"destroy",this).call(this)}}]),i}(),iD=function(e){g(i,Ce);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return B(this,i),(r=t.call(this,e.viewer.scene)).zonesPlugin=e,r.pointerLens=s.pointerLens,r.pointerCircle=new Re(e.viewer),r._action=null,r}return C(i,[{key:"active",get:function(){return!!this._action}},{key:"activate",value:function(e,t,i,r){if("object"===w(e)&&null!==e){var s=e,n=function(e,t){if(e in s)return s[e];if(void 0!==t)return t;throw"config missing: "+e};e=n("altitude"),t=n("height"),i=n("color","#008000"),r=n("alpha",.5)}if(!this._action){var o=this.zonesPlugin,a=o.viewer,l=a.scene,u=this,c=ht(a,this.pointerCircle,(function(t,i){return XI(e,re.vec3([0,1,0]),t,i)}));!function s(){u._action=eD(l,e,t,i,r,u.pointerLens,o,c,(function(e){var t=!0;u._action={deactivate:function(){t=!1}},u.fire("zoneEnd",e),t&&s()}))}()}}},{key:"deactivate",value:function(){this._action&&(this._action.deactivate(),this._action=null)}},{key:"destroy",value:function(){this.deactivate(),f(x(i.prototype),"destroy",this).call(this)}}]),i}(),rD=function(e){g(i,Ce);var t=_(i);function i(e,r,s,n){var o;B(this,i);var a=e.plugin.viewer,l=a.scene;o=t.call(this,l);var u=e._geometry.altitude,c=e._geometry.planeCoordinates.map((function(t){var i=l.canvas.canvas.ownerDocument.body,r=new ut(l,{},i,{fillColor:e._color});return r.worldPos=re.vec3([t[0],u,t[1]]),r.on("worldPos",(function(){t[0]=r.worldPos[0],t[1]=r.worldPos[2];try{e._rebuildMesh()}catch(t){e._zoneMesh&&(e._zoneMesh.destroy(),e._zoneMesh=null)}})),r})),A=At({viewer:a,handleMouseEvents:s,handleTouchEvents:n,pointerLens:r&&r.pointerLens,dots:c,ray2WorldPos:function(e,t){return XI(u,re.vec3([0,1,0]),e,t)},onEnd:function(t,i){return e._zoneMesh&&o.fire("edited"),!!e._zoneMesh}}),h=function(){A(),c.forEach((function(e){return e.destroy()}))},d=e.on("destroyed",h);return o._deactivate=function(){e.off("destroyed",d),h()},o}return C(i,[{key:"deactivate",value:function(){this._deactivate(),f(x(i.prototype),"destroy",this).call(this)}}]),i}(),sD=function(e){g(i,rD);var t=_(i);function i(e,r){return B(this,i),t.call(this,e,r,!0,!1)}return C(i)}(),nD=function(e){g(i,rD);var t=_(i);function i(e,r){return B(this,i),t.call(this,e,r,!1,!0)}return C(i)}(),oD=function(e){g(i,Ce);var t=_(i);function i(e,r,s,n){var o;B(this,i);var a=e.plugin.viewer,l=a.scene,u=l.canvas.canvas,c=b(o=t.call(this,l)),A=e._geometry.altitude,d=r&&r.pointerLens,p=d?function(e){d.visible=!!e,e&&(d.canvasPos=e)}:function(){},f=function(e){var t,i,r=re.vec3(),s=re.vec3();return re.canvasPosToWorldRay(u,l.camera.viewMatrix,l.camera.projMatrix,l.camera.projection,e,r,s),t=r,i=s,XI(A,re.vec3([0,1,0]),t,i)},v=function(e,t){return t[0]=e.clientX,t[1]=e.clientY,lt(u.ownerDocument.documentElement,u,t),t},g=function(e,t){var i=function(e){e.preventDefault(),t(e)};return u.addEventListener(e,i),function(){return u.removeEventListener(e,i)}},m=function(){},_=function(t,i,r,s){var n,o,l,A,h=s(t),d=v(h,re.vec2()),_=a.scene.pick({canvasPos:d,includeEntities:[e._zoneMesh.id]});if((_&&_.entity&&_.entity.zone)===e){m(),u.style.cursor="move",a.cameraControl.active=!1;var y=(n=e._geometry.planeCoordinates.map((function(e){return e.slice()})),o=f(d),l=re.vec2([o[0],o[2]]),A=re.vec2(),function(t){var i=f(t);A[0]=i[0],A[1]=i[2],re.subVec2(l,A,A),e._geometry.planeCoordinates.forEach((function(e,t){re.subVec2(n[t],A,e)}));try{e._rebuildMesh()}catch(t){e._zoneMesh&&(e._zoneMesh.destroy(),e._zoneMesh=null)}}),b=g(i,(function(e){var t=s(e);if(t){var i=v(t,re.vec2());y(i),p(i)}})),x=g(r,(function(e){var t=s(e);if(t){var i=v(t,re.vec2());y(i),p(null),m(),c.fire("translated")}}));m=function(){m=function(){},u.style.cursor="default",a.cameraControl.active=!0,b(),x()}}},y=[];s&&y.push(g("mousedown",(function(e){1===e.which&&_(e,"mousemove","mouseup",(function(e){return 1===e.which&&e}))}))),n&&y.push(g("touchstart",(function(e){if(1===e.touches.length){var t=e.touches[0].identifier;_(e,"touchmove","touchend",(function(e){return h(e.changedTouches).find((function(e){return e.identifier===t}))}))}})));var x=function(){m(),y.forEach((function(e){return e()})),p(null)},w=e.on("destroyed",x);return o._deactivate=function(){e.off("destroyed",w),x()},o}return C(i,[{key:"deactivate",value:function(){this._deactivate(),f(x(i.prototype),"destroy",this).call(this)}}]),i}(),aD=function(e){g(i,oD);var t=_(i);function i(e,r){return B(this,i),t.call(this,e,r,!0,!1)}return C(i)}(),lD=function(e){g(i,oD);var t=_(i);function i(e,r){return B(this,i),t.call(this,e,r,!1,!0)}return C(i)}();export{Ur as AlphaFormat,Li as AmbientLight,wt as AngleMeasurementEditMouseControl,Bt as AngleMeasurementEditTouchControl,mt as AngleMeasurementsControl,_t as AngleMeasurementsMouseControl,yt as AngleMeasurementsPlugin,bt as AngleMeasurementsTouchControl,Ft as AnnotationsPlugin,Bn as AxisGizmoPlugin,Kh as BCFViewpointsPlugin,po as Bitmap,Mr as ByteType,Od as CameraMemento,md as CameraPath,Pd as CameraPathAnimation,QI as CityJSONLoaderPlugin,pr as ClampToEdgeWrapping,Ce as Component,Cs as CompressedMediaType,wa as Configs,J as ContextMenu,jd as CubicBezierCurve,fd as Curve,sh as DefaultLoadingManager,Hr as DepthFormat,jr as DepthStencilFormat,Ti as DirLight,ad as DistanceMeasurementEditControl,ld as DistanceMeasurementEditMouseControl,ud as DistanceMeasurementEditTouchControl,rd as DistanceMeasurementsControl,sd as DistanceMeasurementsMouseControl,nd as DistanceMeasurementsPlugin,od as DistanceMeasurementsTouchControl,ut as Dot3D,VI as DotBIMDefaultDataSource,HI as DotBIMLoaderPlugin,ir as EdgeMaterial,er as EmphasisMaterial,yF as FaceAlignedSectionPlanesPlugin,cd as FastNavPlugin,Dr as FloatType,qn as Fresnel,Ie as Frustum,ke as FrustumPlane,ws as GIFMediaType,Ad as GLTFDefaultDataSource,OE as GLTFLoaderPlugin,Sr as HalfFloatType,kd as ImagePlane,kr as IntType,Bs as JPEGMediaType,ch as KTX2TextureTranscoder,aI as LASLoaderPlugin,Rn as LambertMaterial,Rd as LightMap,Hh as LineSet,bs as LinearEncoding,br as LinearFilter,Pr as LinearMipMapLinearFilter,wr as LinearMipMapNearestFilter,Br as LinearMipmapLinearFilter,xr as LinearMipmapNearestFilter,nh as Loader,rh as LoadingManager,hd as LocaleService,Vr as LuminanceAlphaFormat,Qr as LuminanceFormat,G as Map,ot as Marker,Te as MarqueePicker,Le as MarqueePickerMouseControl,mn as Mesh,Mo as MeshSurfaceArea,_o as MeshVolume,Nn as MetallicMaterial,fr as MirroredRepeatWrapping,Qd as ModelMemento,HE as NavCubePlugin,vr as NearestFilter,yr as NearestMipMapLinearFilter,gr as NearestMipMapNearestFilter,_r as NearestMipmapLinearFilter,mr as NearestMipmapNearestFilter,Ln as Node,qE as OBJLoaderPlugin,ne as ObjectsKdTree3,Hd as ObjectsMemento,Ps as PNGMediaType,Gd as Path,Wd as PerformanceModel,qi as PhongMaterial,Ut as PickResult,Ue as Plugin,Id as PointLight,Re as PointerCircle,Y as PointerLens,zd as QuadraticBezierCurve,oe as Queue,Nr as RGBAFormat,Xr as RGBAIntegerFormat,gs as RGBA_ASTC_10x10_Format,ps as RGBA_ASTC_10x5_Format,fs as RGBA_ASTC_10x6_Format,vs as RGBA_ASTC_10x8_Format,ms as RGBA_ASTC_12x10_Format,_s as RGBA_ASTC_12x12_Format,os as RGBA_ASTC_4x4_Format,as as RGBA_ASTC_5x4_Format,ls as RGBA_ASTC_5x5_Format,us as RGBA_ASTC_6x5_Format,cs as RGBA_ASTC_6x6_Format,As as RGBA_ASTC_8x5_Format,hs as RGBA_ASTC_8x6_Format,ds as RGBA_ASTC_8x8_Format,ys as RGBA_BPTC_Format,ns as RGBA_ETC2_EAC_Format,is as RGBA_PVRTC_2BPPV1_Format,ts as RGBA_PVRTC_4BPPV1_Format,Yr as RGBA_S3TC_DXT1_Format,Zr as RGBA_S3TC_DXT3_Format,qr as RGBA_S3TC_DXT5_Format,Or as RGBFormat,rs as RGB_ETC1_Format,ss as RGB_ETC2_Format,es as RGB_PVRTC_2BPPV1_Format,$r as RGB_PVRTC_4BPPV1_Format,Jr as RGB_S3TC_DXT1_Format,Wr as RGFormat,Kr as RGIntegerFormat,Ki as ReadableGeometry,Gr as RedFormat,zr as RedIntegerFormat,Ld as ReflectionMap,dr as RepeatWrapping,xF as STLDefaultDataSource,IF as STLLoaderPlugin,Qh as SceneModel,Do as SceneModelMesh,Ih as SceneModelTransform,Pn as SectionPlane,oF as SectionPlanesPlugin,Er as ShortType,Kd as Skybox,bF as SkyboxesPlugin,Hn as SpecularMaterial,vd as SplineCurve,Ud as SpriteMarker,hF as StoreyViewsPlugin,Zn as Texture,Xd as TextureTranscoder,TF as TreeViewPlugin,Cr as UnsignedByteType,Rr as UnsignedInt248Type,Ir as UnsignedIntType,Tr as UnsignedShort4444Type,Lr as UnsignedShort5551Type,Fr as UnsignedShortType,to as VBOGeometry,NF as ViewCullPlugin,Ub as Viewer,$k as WebIFCLoaderPlugin,lh as WorkerPool,QF as XKTDefaultDataSource,Lk as XKTLoaderPlugin,Zk as XML3DLoaderPlugin,rD as ZoneEditControl,sD as ZoneEditMouseControl,nD as ZoneEditTouchControl,oD as ZoneTranslateControl,aD as ZoneTranslateMouseControl,lD as ZoneTranslateTouchControl,ZI as ZonesMouseControl,$I as ZonesPlugin,tD as ZonesPolysurfaceMouseControl,iD as ZonesPolysurfaceTouchControl,qI as ZonesTouchControl,ct as activateDraggableDot,At as activateDraggableDots,Xi as buildBoxGeometry,no as buildBoxLinesGeometry,oo as buildBoxLinesGeometryFromAABB,yn as buildCylinderGeometry,ao as buildGridGeometry,ho as buildLineGeometry,lo as buildPlaneGeometry,co as buildPolylineGeometry,Ao as buildPolylineGeometryFromCurve,bn as buildSphereGeometry,uo as buildTorusGeometry,wn as buildVectorTextGeometry,Ve as createRTCViewMat,Se as frustumIntersectsAABB3,hh as getKTX2TextureTranscoder,ze as getPlaneRTCPos,fo as isTriangleMeshSolid,ro as load3DSGeometry,so as loadOBJGeometry,re as math,Eo as meshSurfaceArea,yo as meshVolume,Ge as rtcToWorldPos,xs as sRGBEncoding,De as setFrustum,ae as stats,ht as touchPointSelector,lt as transformToNode,he as utils,He as worldToRTCPos,je as worldToRTCPositions};