@xeokit/xeokit-sdk 2.4.0-alpha-71 → 2.4.0-alpha-72
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* @author https://github.com/tmarti, with support from https://tribia.com/
|
|
8
8
|
* @license MIT
|
|
9
9
|
*/
|
|
10
|
-
function es(e,t){t.length;const s=e.length,n=[],i=[],a=e=>{for(let s=0,n=e.meshIds.length;s<n;s++)if(t[e.meshIds[s]].geometryId)return!0;return!1};for(let r=0;r<s;r++){const s=e[r];if(a(s)){i.push(r);continue}const l=h.collapseAABB3();let o=0;s.meshIds.forEach((e=>{const s=t[e];let n,i;if(s.positionsCompressed){const e=wt.getPositionsBounds(s.positionsCompressed);n=wt.decompressPosition(e.min,s.positionsDecodeMatrix,[]),i=wt.decompressPosition(e.max,s.positionsDecodeMatrix,[])}else{const e=wt.getPositionsBounds(s.positions);n=e.min,i=e.max}n[0]+=s.origin[0],n[1]+=s.origin[1],n[2]+=s.origin[2],i[0]+=s.origin[0],i[1]+=s.origin[1],i[2]+=s.origin[2],h.expandAABB3Point3(l,n),h.expandAABB3Point3(l,i),o+=s.numPrimitives})),n[r]={aabb:l,numPrimitives:o,entityId:s.id}}let r,l=[],o={};if(Object.keys(n).length>0){r=function(e){const t=[];for(let s=0,n=e.length;s<n;s++){const n=e[s];n&&t.push({minX:n.aabb[0],minY:n.aabb[1],minZ:n.aabb[2],maxX:n.aabb[3],maxY:n.aabb[4],maxZ:n.aabb[5],entity:{id:s,xeokitId:n.entityId,meshes:[{numPrimitives:n.numPrimitives}]},numPrimitives:n.numPrimitives})}const s=new Zt(4);return s.load(t),s}(n);let e=$t({aabbTree:r});l=e.orderedEntityIds,o=e.clusteringResult.entityIdToClusterIdMapping}return{orderedClusteredIndexes:l,entityIdToClusterIdMapping:o,instancedIndexes:i,rTreeBasedAabbTree:r}}const ts=h.vec3(),ss=180/Math.PI,ns=new Float32Array(262144);for(let e=-256;e<256;e++)for(let t=-256;t<256;t++){const s=(e+256<<9)+(t+256),n=Math.max(Math.abs(e),Math.abs(t));ns[s]=Math.atan2(e/n,t/n)}function is(e,t){const s=256/Math.max(Math.abs(e),Math.abs(t)),n=Math.round(e*s)+255,i=Math.round(t*s)+255;return ns[(n<<9)+i]}class as{constructor(){this._aabbTree=null,this._orderedMeshList=[],this._orderedEntityList=[],this._frustumProps={dirty:!0,wMultiply:1,hMultiply:1},this._cullFrame=0,this.finalized=!1}initializeVFCState(e,t){if(this.finalized)throw"Already finalized";const s=es(e,t);this._aabbTree=s.rTreeBasedAabbTree;for(let n=0,i=s.orderedClusteredIndexes.length;n<i;n++){const i=s.orderedClusteredIndexes[n],a=s.entityIdToClusterIdMapping[i],r=e[i],l=[];for(let e=0,s=r.meshIds.length;e<s;e++){const s=r.meshIds[e];t[s].id=this._orderedMeshList.length,l.push(this._orderedMeshList.length),this._orderedMeshList.push({clusterNumber:a,mesh:t[s]})}r.meshIds=l,this._orderedEntityList.push(r)}for(let n=0,i=s.instancedIndexes.length;n<i;n++){let i=e[s.instancedIndexes[n]];const a=[];for(let e=0,s=i.meshIds.length;e<s;e++){const s=i.meshIds[e];t[s].id=this._orderedMeshList.length,a.push(this._orderedMeshList.length),this._orderedMeshList.push({clusterNumber:99999,mesh:t[s]})}i.meshIds=a,this._orderedEntityList.push(i)}}finalize(e,t){if(this.finalized)throw"Already finalized";let s=-1;for(let n=0,i=this._orderedMeshList.length;n<i;n++){const{clusterNumber:i,mesh:a}=this._orderedMeshList[n];-1!==s&&s!==i&&t.call(e),e._createMesh(a),s=i}for(let t=0,s=this._orderedEntityList.length;t<s;t++)e._createEntity(this._orderedEntityList[t]);this._orderedMeshList=[],this._orderedEntityList=[],this.finalized=!0}applyViewFrustumCulling(e){if(!this.finalized)throw"Not finalized";if(!this._aabbTree)return;this._canvasElement||(this._canvasElement=e.scene.canvas.canvas),this._camera||(this._camera=e.scene.camera),this._ensureFrustumPropsUpdated(e),this._initializeCullingDataIfNeeded(e);const t=this._searchVisibleNodesWithFrustumCulling();this._cullFrame++,this._markVisibleFrameOfVisibleNodes(t,this._cullFrame),this._cullNonVisibleNodes(e,this._cullFrame)}_initializeCullingDataIfNeeded(e){if(this._internalNodesList)return;if(!this._aabbTree)return;const t=this._aabbTree.all();let s=0;t.forEach((e=>{s=Math.max(s,e.entity.id)}));const n=new Array(s+1);t.forEach((t=>{n[t.entity.id]=e.objects[t.entity.xeokitId]})),this._internalNodesList=n,this._lastVisibleFrameOfNodes=new Array(n.length),this._lastVisibleFrameOfNodes.fill(0)}_searchVisibleNodesWithFrustumCulling(){return this._aabbTree.searchCustom(((e,t)=>this._aabbIntersectsCameraFrustum(e,t)),(e=>this._aabbContainedInCameraFrustum(e)))}_markVisibleFrameOfVisibleNodes(e,t){const s=this._lastVisibleFrameOfNodes;for(let n=0,i=e.length;n<i;n++)s[e[n].entity.id]=t}_cullNonVisibleNodes(e,t){const s=this._internalNodesList,n=this._lastVisibleFrameOfNodes;for(let e=0,i=s.length;e<i;e++)s[e]&&(s[e].culledVFC=n[e]!==t)}_getPointsForBBox(e){const t=[];for(let s=0;s<8;s++)t.push(new Float32Array([1&s?e.maxX:e.minX,2&s?e.maxY:e.minY,4&s?e.maxZ:e.minZ]));return t}_aabbIntersectsCameraFrustum(e,t){if(t)return!0;if("ortho"===this._camera.projection)return this._frustumProps.dirty=!1,!0;const s=this._aabbIntersectsCameraFrustum_internal(e);return!!((4096&s||!(1&s||2&s)||1&s)&&(8192&s||!(16&s||32&s)||16&s)&&(16384&s||!(256&s||512&s)||256&s))}_aabbContainedInCameraFrustum(e){if("ortho"===this._camera.projection)return this._frustumProps.dirty=!1,!0;const t=e._check;return 1&t&&16&t&&256&t}_ensureFrustumPropsUpdated(e){const t=Math.min(this._canvasElement.width,this._canvasElement.height);this._frustumProps.wMultiply=this._canvasElement.width/t,this._frustumProps.hMultiply=this._canvasElement.height/t;const s=this._canvasElement.width/this._canvasElement.height;let n=this._camera.perspective.fov;s<1&&(n/=s),n=Math.min(n,120),this._frustumProps.fov=n;const i=h.inverseMat4(e.worldMatrix,h.mat4()),a=h.transformVec3(i,this._camera.eye,[0,0,0]),r=h.transformVec3(i,this._camera.look,[0,0,0]);this._frustumProps.forward=h.normalizeVec3(h.subVec3(r,a,[0,0,0]),[0,0,0]),this._frustumProps.up=h.normalizeVec3(this._camera.up,[0,0,0]),this._frustumProps.right=h.normalizeVec3(h.cross3Vec3(this._frustumProps.forward,this._frustumProps.up,[0,0,0]),[0,0,0]),this._frustumProps.eye=a.slice(),this._frustumProps.CAM_FACTOR_1=this._frustumProps.fov/2*this._frustumProps.wMultiply/ss,this._frustumProps.CAM_FACTOR_2=this._frustumProps.fov/2*this._frustumProps.hMultiply/ss}_aabbIntersectsCameraFrustum_internal(e){const t=e._points||this._getPointsForBBox(e);e._points=t;let s=819;for(let e=0,n=t.length;e<n;e++){const n=t[e],i=ts;i[0]=n[0]-this._frustumProps.eye[0],i[1]=n[1]-this._frustumProps.eye[1],i[2]=n[2]-this._frustumProps.eye[2];const a=h.dotVec3(i,this._frustumProps.forward);a<0?(s|=4,s&=-2):(s|=8,s&=-3);const r=is(h.dotVec3(i,this._frustumProps.right),a);Math.abs(r)>this._frustumProps.CAM_FACTOR_1?(s|=r<0?64:128,s&=-17):s&=-33;const l=is(h.dotVec3(i,this._frustumProps.up),a);Math.abs(l)>this._frustumProps.CAM_FACTOR_2?(s|=l<0?1024:2048,s&=-257):s&=-513}return 4&s&&8&s&&(s|=4096),64&s&&128&s&&(s|=8192),1024&s&&2048&s&&(s|=16384),e._check=s,s}}class rs{constructor(e,t){this.sceneModel=t,this.entities=[],this.meshes=[],this.finalized=!1}addEntity(e){if(this.finalized)throw"Already finalized";this.entities.push(e)}addMesh(e){if(this.finalized)throw"Already finalized";this.meshes.push(e)}finalize(e){if(this.finalized)throw"Already finalized";this.finalized=!0,this.VFCState=new as,this.VFCState.initializeVFCState(this.entities,this.meshes),this.VFCState.finalize(this.sceneModel,e),this._onSceneRendering=this.sceneModel.scene.on("rendering",(()=>this.applyViewFrustumCulling.call(this)))}applyViewFrustumCulling(){this.finalized&&this.VFCState.applyViewFrustumCulling(this.sceneModel)}destroy(){this.finalized&&this.sceneModel.off(this._onSceneRendering)}}class ls extends C{constructor(e,t={}){super(e,t),this._scene=e,this._vfcManagers={},this._vfcManagerList=[],this.enabled=t.enabled,this._init()}_init(){this._scene.on("rendering",(()=>{for(let e=0,t=this._vfcManagerList.length;e<t;e++)this._vfcManagerList[e].applyViewFrustumCulling()}))}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}get enabled(){return this._enabled}getVFCManager(e){const t=new rs(this.scene,e);return this._vfcManagers[t.id]=t,this._vfcManagerList=Object.values(this._vfcManagers),t}putVFCManager(e){delete this._vfcManagers[e.id],this._vfcManagerList=Object.values(this._vfcManagers)}destroy(){super.destroy()}}function os(e,t){const s={};let n,i;for(let a=0,r=t.length;a<r;a++)n=t[a],i=e.component[n],i?i.isEntity?s[n]=!0:e.warn("pick(): Component is not an Entity: "+n):e.warn("pick(): Component not found: "+n);return s}class cs extends C{get type(){return"Scene"}constructor(e,t={}){super(null,t);const s=t.canvasElement||document.getElementById(t.canvasId);if(!(s instanceof HTMLCanvasElement))throw"Mandatory config expected: valid canvasId or canvasElement";const n=!!t.transparent,i=!!t.alphaDepthMask;this._aabbDirty=!0,this.viewer=e,this.occlusionTestCountdown=0,this.loading=0,this.startTime=(new Date).getTime(),this.models={},this.objects={},this._numObjects=0,this.visibleObjects={},this._numVisibleObjects=0,this.xrayedObjects={},this._numXRayedObjects=0,this.highlightedObjects={},this._numHighlightedObjects=0,this.selectedObjects={},this._numSelectedObjects=0,this.colorizedObjects={},this._numColorizedObjects=0,this.opacityObjects={},this._numOpacityObjects=0,this.offsetObjects={},this._numOffsetObjects=0,this._modelIds=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this._opacityObjectIds=null,this._offsetObjectIds=null,this._collidables={},this._compilables={},this._needRecompile=!1,this.types={},this.components={},this.sectionPlanes={},this.lights={},this.lightMaps={},this.reflectionMaps={},this.bitmaps={},this.lineSets={},this.realWorldOffset=t.realWorldOffset||new Float64Array([0,0,0]),this.canvas=new he(this,{dontClear:!0,canvas:s,spinnerElementId:t.spinnerElementId,transparent:n,webgl2:!1!==t.webgl2,contextAttr:t.contextAttr||{},backgroundColor:t.backgroundColor,backgroundColorFromAmbientLight:t.backgroundColorFromAmbientLight,premultipliedAlpha:t.premultipliedAlpha}),this.canvas.on("boundary",(()=>{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new He(this,{transparent:n,alphaDepthMask:i}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1;let e=null;this.getHash=function(){if(e)return e;const t=this.sectionPlanes;if(0===t.length)return this.hash=";";const s=[];for(let e=0,n=t.length;e<n;e++)s.push("cp");return s.push(";"),e=s.join(""),e},this.addSectionPlane=function(t){this.sectionPlanes.push(t),e=null},this.removeSectionPlane=function(t){for(let s=0,n=this.sectionPlanes.length;s<n;s++)if(this.sectionPlanes[s].id===t.id)return this.sectionPlanes.splice(s,1),void(e=null)}},this._lightsState=new function(){const e=h.vec4([0,0,0,0]),t=h.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let s=null,n=null;this.getHash=function(){if(s)return s;const e=[],t=this.lights;let n;for(let s=0,i=t.length;s<i;s++)n=t[s],e.push("/"),e.push(n.type),e.push("world"===n.space?"w":"v"),n.castsShadow&&e.push("sh");return this.lightMaps.length>0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),s=e.join(""),s},this.addLight=function(e){this.lights.push(e),n=null,s=null},this.removeLight=function(e){for(let t=0,i=this.lights.length;t<i;t++){if(this.lights[t].id===e.id)return this.lights.splice(t,1),n&&n.id===e.id&&(n=null),void(s=null)}},this.addReflectionMap=function(e){this.reflectionMaps.push(e),s=null},this.removeReflectionMap=function(e){for(let t=0,n=this.reflectionMaps.length;t<n;t++)if(this.reflectionMaps[t].id===e.id)return this.reflectionMaps.splice(t,1),void(s=null)},this.addLightMap=function(e){this.lightMaps.push(e),s=null},this.removeLightMap=function(e){for(let t=0,n=this.lightMaps.length;t<n;t++)if(this.lightMaps[t].id===e.id)return this.lightMaps.splice(t,1),void(s=null)},this.getAmbientColorAndIntensity=function(){if(!n)for(let e=0,t=this.lights.length;e<t;e++){const t=this.lights[e];if("ambient"===t.type){n=t;break}}if(n){const e=n.color,s=n.intensity;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=s,t}return e}},this.input=new Ue(this,{dontClear:!0,element:this.canvas.canvas,keyboardEventsElement:t.keyboardEventsElement}),this.metrics=new xt(this,{units:t.units,scale:t.scale,origin:t.origin}),this.sao=new Lt(this,{enabled:t.saoEnabled}),this.ticksPerRender=t.ticksPerRender,this.ticksPerOcclusionTest=t.ticksPerOcclusionTest,this.passes=t.passes,this.clearEachPass=t.clearEachPass,this.gammaInput=t.gammaInput,this.gammaOutput=t.gammaOutput,this.gammaFactor=t.gammaFactor,this._entityOffsetsEnabled=!!t.entityOffsetsEnabled,this._logarithmicDepthBufferEnabled=!!t.logarithmicDepthBufferEnabled,this._dtxEnabled=!1!==t.dtxEnabled,this._pbrEnabled=!!t.pbrEnabled,this._colorTextureEnabled=!1!==t.colorTextureEnabled,this._dtxEnabled=!!t.dtxEnabled,P._addScene(this),this._initDefaults(),this._viewport=new je(this,{id:"default.viewport",autoBoundary:!0,dontClear:!0}),this._camera=new ot(this,{id:"default.camera",dontClear:!0}),new ht(this,{color:[1,1,1],intensity:.7}),new ut(this,{dir:[.8,-.5,-.5],color:[.67,.67,1],intensity:.7,space:"world"}),new ut(this,{dir:[-.8,-1,.5],color:[1,1,.9],intensity:.9,space:"world"}),this._camera.on("dirty",(()=>{this._renderer.imageDirty()})),this.lod=new Xt(this,{enabled:t.lodEnabled}),this.vfc=new ls(this,{enabled:t.vfcEnabled})}_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=h.createUUID();this.components[e.id]=e;const t=e.type;let s=this.types[e.type];s||(s=this.types[t]={}),s[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,s=e.type;delete this.components[t];const n=this.types[s];n&&(delete n[t],y.isEmptyObject(n)&&delete this.types[s]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_objectHighlightedUpdated(e,t=!0){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null,t&&this.fire("objectHighlighted",e,!0)}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const s=this.components[t];s._webglContextRestored&&s._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&P.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const s=this._passes,n=this._clearEachPass;let i,a;for(i=0;i<s;i++)t.pass=i,this.fire("rendering",t,!0),a=n||0===i,this._renderer.render({pass:i,clear:a,force:e}),this.fire("rendered",t,!0);this._saveAmbientColor()}_recompile(){for(const e in this._compilables)this._compilables.hasOwnProperty(e)&&this._compilables[e].compile();this._renderer.shadowsDirty(),this.fire("compile",this,!0)}_saveAmbientColor(){const e=this.canvas;if(e.transparent||e.backgroundImage||e.backgroundColor)this._lastAmbientColor=null;else{const t=this._lightsState.getAmbientColorAndIntensity();this._lastAmbientColor&&this._lastAmbientColor[0]===t[0]&&this._lastAmbientColor[1]===t[1]&&this._lastAmbientColor[2]===t[2]&&this._lastAmbientColor[3]===t[3]||(e.backgroundColor=t,this._lastAmbientColor||(this._lastAmbientColor=h.vec4([0,0,0,1])),this._lastAmbientColor.set(t))}}get modelIds(){return this._modelIds||(this._modelIds=Object.keys(this.models)),this._modelIds}get numObjects(){return this._numObjects}get objectIds(){return this._objectIds||(this._objectIds=Object.keys(this.objects)),this._objectIds}get numVisibleObjects(){return this._numVisibleObjects}get visibleObjectIds(){return this._visibleObjectIds||(this._visibleObjectIds=Object.keys(this.visibleObjects)),this._visibleObjectIds}get numXRayedObjects(){return this._numXRayedObjects}get xrayedObjectIds(){return this._xrayedObjectIds||(this._xrayedObjectIds=Object.keys(this.xrayedObjects)),this._xrayedObjectIds}get numHighlightedObjects(){return this._numHighlightedObjects}get highlightedObjectIds(){return this._highlightedObjectIds||(this._highlightedObjectIds=Object.keys(this.highlightedObjects)),this._highlightedObjectIds}get numSelectedObjects(){return this._numSelectedObjects}get selectedObjectIds(){return this._selectedObjectIds||(this._selectedObjectIds=Object.keys(this.selectedObjects)),this._selectedObjectIds}get numColorizedObjects(){return this._numColorizedObjects}get colorizedObjectIds(){return this._colorizedObjectIds||(this._colorizedObjectIds=Object.keys(this.colorizedObjects)),this._colorizedObjectIds}get opacityObjectIds(){return this._opacityObjectIds||(this._opacityObjectIds=Object.keys(this.opacityObjects)),this._opacityObjectIds}get offsetObjectIds(){return this._offsetObjectIds||(this._offsetObjectIds=Object.keys(this.offsetObjects)),this._offsetObjectIds}set ticksPerRender(e){null==e?e=1:(!y.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerRender': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._ticksPerRender&&(this._ticksPerRender=e)}get ticksPerRender(){return this._ticksPerRender}set ticksPerOcclusionTest(e){null==e?e=20:(!y.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerOcclusionTest': '"+e+"' - should be an integer greater than zero."),e=20),e!==this._ticksPerOcclusionTest&&(this._ticksPerOcclusionTest=e)}get ticksPerOcclusionTest(){return this._ticksPerOcclusionTest}set passes(e){null==e?e=1:(!y.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'passes': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._passes&&(this._passes=e,this.glRedraw())}get passes(){return this._passes}set clearEachPass(e){(e=!!e)!==this._clearEachPass&&(this._clearEachPass=e,this.glRedraw())}get clearEachPass(){return this._clearEachPass}set gammaInput(e){(e=!1!==e)!==this._renderer.gammaInput&&(this._renderer.gammaInput=e,this._needRecompile=!0,this.glRedraw())}get gammaInput(){return this._renderer.gammaInput}set gammaOutput(e){(e=!!e)!==this._renderer.gammaOutput&&(this._renderer.gammaOutput=e,this._needRecompile=!0,this.glRedraw())}get gammaOutput(){return this._renderer.gammaOutput}set gammaFactor(e){(e=null==e?2.2:e)!==this._renderer.gammaFactor&&(this._renderer.gammaFactor=e,this.glRedraw())}get gammaFactor(){return this._renderer.gammaFactor}get geometry(){return this.components["default.geometry"]||bt(Et)}get material(){return this.components["default.material"]||new Ct(this,{id:"default.material",emissive:[.4,.4,.4],dontClear:!0})}get xrayMaterial(){return this.components["default.xrayMaterial"]||new Bt(this,{id:"default.xrayMaterial",preset:"sepia",dontClear:!0})}get highlightMaterial(){return this.components["default.highlightMaterial"]||new Bt(this,{id:"default.highlightMaterial",preset:"yellowHighlight",dontClear:!0})}get selectedMaterial(){return this.components["default.selectedMaterial"]||new Bt(this,{id:"default.selectedMaterial",preset:"greenSelected",dontClear:!0})}get edgeMaterial(){return this.components["default.edgeMaterial"]||new St(this,{id:"default.edgeMaterial",preset:"default",edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get pointsMaterial(){return this.components["default.pointsMaterial"]||new Ft(this,{id:"default.pointsMaterial",preset:"default",dontClear:!0})}get linesMaterial(){return this.components["default.linesMaterial"]||new Ut(this,{id:"default.linesMaterial",preset:"default",dontClear:!0})}get viewport(){return this._viewport}get camera(){return this._camera}get center(){if(this._aabbDirty||!this._center){this._center&&this._center||(this._center=h.vec3());const e=this.aabb;this._center[0]=(e[0]+e[3])/2,this._center[1]=(e[1]+e[4])/2,this._center[2]=(e[2]+e[5])/2}return this._center}get aabb(){if(this._aabbDirty){this._aabb||(this._aabb=h.AABB3());let e,t=h.MAX_DOUBLE,s=h.MAX_DOUBLE,n=h.MAX_DOUBLE,i=h.MIN_DOUBLE,a=h.MIN_DOUBLE,r=h.MIN_DOUBLE;const l=this._collidables;let o,c=!1;for(const u in l)if(l.hasOwnProperty(u)){if(o=l[u],!1===o.collidable)continue;e=o.aabb,e[0]<t&&(t=e[0]),e[1]<s&&(s=e[1]),e[2]<n&&(n=e[2]),e[3]>i&&(i=e[3]),e[4]>a&&(a=e[4]),e[5]>r&&(r=e[5]),c=!0}c||(t=-100,s=-100,n=-100,i=100,a=100,r=100),this._aabb[0]=t,this._aabb[1]=s,this._aabb[2]=n,this._aabb[3]=i,this._aabb[4]=a,this._aabb[5]=r,this._aabbDirty=!1}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const s=e.includeEntities||e.include;s&&(e.includeEntityIds=os(this,s));const n=e.excludeEntities||e.exclude;return n&&(e.excludeEntityIds=os(this,n)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=this._renderer.pick(e,t))?(t.entity&&t.entity.fire&&t.entity.fire("picked",t),t):void 0}snapPick(e){return this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapMode||"vertex")}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,s=e.length;t<s;t++)this.lights[e[t]].destroy()}clearSectionPlanes(){const e=Object.keys(this.sectionPlanes);for(let t=0,s=e.length;t<s;t++)this.sectionPlanes[e[t]].destroy()}clearBitmaps(){const e=Object.keys(this.bitmaps);for(let t=0,s=e.length;t<s;t++)this.bitmaps[e[t]].destroy()}clearLines(){const e=Object.keys(this.lineSets);for(let t=0,s=e.length;t<s;t++)this.lineSets[e[t]].destroy()}getAABB(e){if(void 0===e)return this.aabb;if(y.isString(e)){const t=this.objects[e];if(t&&t.aabb)return t.aabb;e=[e]}if(0===e.length)return this.aabb;let t,s=h.MAX_DOUBLE,n=h.MAX_DOUBLE,i=h.MAX_DOUBLE,a=h.MIN_DOUBLE,r=h.MIN_DOUBLE,l=h.MIN_DOUBLE;if(this.withObjects(e,(e=>{if(e.collidable){const o=e.aabb;o[0]<s&&(s=o[0]),o[1]<n&&(n=o[1]),o[2]<i&&(i=o[2]),o[3]>a&&(a=o[3]),o[4]>r&&(r=o[4]),o[5]>l&&(l=o[5]),t=!0}})),t){const e=h.AABB3();return e[0]=s,e[1]=n,e[2]=i,e[3]=a,e[4]=r,e[5]=l,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const s=e.visible!==t;return e.visible=t,s}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const s=e.collidable!==t;return e.collidable=t,s}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const s=e.culled!==t;return e.culled=t,s}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const s=e.selected!==t;return e.selected=t,s}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const s=e.highlighted!==t;return e.highlighted=t,s}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const s=e.xrayed!==t;return e.xrayed=t,s}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const s=e.edges!==t;return e.edges=t,s}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const s=e.opacity!==t;return e.opacity=t,s}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const s=e.pickable!==t;return e.pickable=t,s}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){y.isString(e)&&(e=[e]);let s=!1;for(let n=0,i=e.length;n<i;n++){const i=e[n];let a=this.objects[i];if(a)s=t(a)||s;else{const e=this.modelIds;for(let n=0,r=e.length;n<r;n++){const r=e[n],l=h.globalizeObjectId(r,i);a=this.objects[l],a&&(s=t(a)||s)}}}return s}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.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 us=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,s=e.scene._sectionPlanesState,n=e.scene._lightsState,i=e._geometry._state,a=e._state.billboard,r=e._state.stationary,l=s.sectionPlanes.length>0,o=!!i.compressGeometry,c=[];c.push("#version 300 es"),c.push("// Lambertian drawing vertex shader"),c.push("in vec3 position;"),c.push("uniform mat4 modelMatrix;"),c.push("uniform mat4 viewMatrix;"),c.push("uniform mat4 projMatrix;"),c.push("uniform vec4 colorize;"),c.push("uniform vec3 offset;"),o&&c.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(c.push("uniform float logDepthBufFC;"),c.push("out float vFragDepth;"),c.push("bool isPerspectiveMatrix(mat4 m) {"),c.push(" return (m[2][3] == - 1.0);"),c.push("}"),c.push("out float isPerspective;"));l&&c.push("out vec4 vWorldPosition;");if(c.push("uniform vec4 lightAmbient;"),c.push("uniform vec4 materialColor;"),c.push("uniform vec3 materialEmissive;"),i.normalsBuf){c.push("in vec3 normal;"),c.push("uniform mat4 modelNormalMatrix;"),c.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];"ambient"!==t.type&&(c.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&c.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&c.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(c.push("uniform vec3 lightPos"+e+";"),c.push("uniform vec3 lightDir"+e+";")))}o&&(c.push("vec3 octDecode(vec2 oct) {"),c.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),c.push(" if (v.z < 0.0) {"),c.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);"),c.push(" }"),c.push(" return normalize(v);"),c.push("}"))}c.push("out vec4 vColor;"),"points"===i.primitiveName&&c.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(c.push("void billboard(inout mat4 mat) {"),c.push(" mat[0][0] = 1.0;"),c.push(" mat[0][1] = 0.0;"),c.push(" mat[0][2] = 0.0;"),"spherical"===a&&(c.push(" mat[1][0] = 0.0;"),c.push(" mat[1][1] = 1.0;"),c.push(" mat[1][2] = 0.0;")),c.push(" mat[2][0] = 0.0;"),c.push(" mat[2][1] = 0.0;"),c.push(" mat[2][2] =1.0;"),c.push("}"));c.push("void main(void) {"),c.push("vec4 localPosition = vec4(position, 1.0); "),c.push("vec4 worldPosition;"),o&&c.push("localPosition = positionsDecodeMatrix * localPosition;");i.normalsBuf&&(o?c.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):c.push("vec4 localNormal = vec4(normal, 0.0); "),c.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),c.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));c.push("mat4 viewMatrix2 = viewMatrix;"),c.push("mat4 modelMatrix2 = modelMatrix;"),r&&c.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===a||"cylindrical"===a?(c.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),c.push("billboard(modelMatrix2);"),c.push("billboard(viewMatrix2);"),c.push("billboard(modelViewMatrix);"),i.normalsBuf&&(c.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),c.push("billboard(modelNormalMatrix2);"),c.push("billboard(viewNormalMatrix2);"),c.push("billboard(modelViewNormalMatrix);")),c.push("worldPosition = modelMatrix2 * localPosition;"),c.push("worldPosition.xyz = worldPosition.xyz + offset;"),c.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(c.push("worldPosition = modelMatrix2 * localPosition;"),c.push("worldPosition.xyz = worldPosition.xyz + offset;"),c.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i.normalsBuf&&c.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(c.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),c.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),c.push("float lambertian = 1.0;"),i.normalsBuf)for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?c.push("viewLightDir = normalize(lightDir"+e+");"):c.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?c.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):c.push("viewLightDir = -normalize((viewMatrix2 * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?c.push("viewLightDir = normalize(lightDir"+e+");"):c.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);")}c.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),c.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}c.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * materialColor.rgb) + materialEmissive.rgb + (reflectedColor * materialColor.rgb), materialColor.a) * colorize;"),l&&c.push("vWorldPosition = worldPosition;");"points"===i.primitiveName&&c.push("gl_PointSize = pointSize;");c.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(c.push("vFragDepth = 1.0 + clipPos.w;"),c.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return c.push("gl_Position = clipPos;"),c.push("}"),c}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState;e._material._state;const n=e._geometry._state,i=s.sectionPlanes.length>0,a=t.gammaOutput,r=[];r.push("#version 300 es"),r.push("// Lambertian drawing fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(i){r.push("in vec4 vWorldPosition;"),r.push("uniform bool clippable;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}r.push("in vec4 vColor;"),a&&(r.push("uniform float gammaFactor;"),r.push(" vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),r.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),r.push("}"));if(r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push("if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}"points"===n.primitiveName&&(r.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),r.push("float r = dot(cxy, cxy);"),r.push("if (r > 1.0) {"),r.push(" discard;"),r.push("}"));t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");a?r.push("outColor = linearToGamma(vColor, gammaFactor);"):r.push("outColor = vColor;");return r.push("}"),r}(e)):(this.vertex=function(e){const t=e.scene;e._material;const s=e._state,n=t._sectionPlanesState,i=e._geometry._state,a=t._lightsState;let r;const l=s.billboard,o=s.background,c=s.stationary,u=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),h=As(e),p=n.sectionPlanes.length>0,A=ps(e),d=!!i.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),d&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),p&&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;"));a.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(h){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(let e=0,t=a.lights.length;e<t;e++)r=a.lights[e],"ambient"!==r.type&&("dir"===r.type&&f.push("uniform vec3 lightDir"+e+";"),"point"===r.type&&f.push("uniform vec3 lightPos"+e+";"),"spot"===r.type&&(f.push("uniform vec3 lightPos"+e+";"),f.push("uniform vec3 lightDir"+e+";")),"dir"===r.type&&"view"===r.space||f.push("out vec4 vViewLightReverseDirAndDist"+e+";"));d&&(f.push("vec3 octDecode(vec2 oct) {"),f.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),f.push(" if (v.z < 0.0) {"),f.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}u&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),d&&f.push("uniform mat3 uvDecodeMatrix;"));i.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===i.primitiveName&&f.push("uniform float pointSize;");"spherical"!==l&&"cylindrical"!==l||(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"===l&&(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(A){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=a.lights.length;e<t;e++)a.lights[e].castsShadow&&(f.push("uniform mat4 shadowViewMatrix"+e+";"),f.push("uniform mat4 shadowProjMatrix"+e+";"),f.push("out vec4 vShadowPosFromLight"+e+";"))}f.push("void main(void) {"),f.push("vec4 localPosition = vec4(position, 1.0); "),f.push("vec4 worldPosition;"),d&&f.push("localPosition = positionsDecodeMatrix * localPosition;");h&&(d?f.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):f.push("vec4 localNormal = vec4(normal, 0.0); "),f.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),f.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));f.push("mat4 viewMatrix2 = viewMatrix;"),f.push("mat4 modelMatrix2 = modelMatrix;"),c?f.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"):o&&f.push("viewMatrix2[3] = vec4(0.0, 0.0, 0.0 ,1.0);");"spherical"===l||"cylindrical"===l?(f.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),f.push("billboard(modelMatrix2);"),f.push("billboard(viewMatrix2);"),f.push("billboard(modelViewMatrix);"),h&&(f.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),f.push("billboard(modelNormalMatrix2);"),f.push("billboard(viewNormalMatrix2);"),f.push("billboard(modelViewNormalMatrix);")),f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));if(h){f.push("vec3 worldNormal = (modelNormalMatrix2 * localNormal).xyz; "),a.lightMaps.length>0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(let e=0,t=a.lights.length;e<t;e++)r=a.lights[e],"ambient"!==r.type&&("dir"===r.type&&"world"===r.space&&(f.push("tmpVec3 = vec3(viewMatrix2 * vec4(lightDir"+e+", 0.0) ).xyz;"),f.push("vViewLightReverseDirAndDist"+e+" = vec4(-tmpVec3, 0.0);")),"point"===r.type&&("world"===r.space?(f.push("tmpVec3 = (viewMatrix2 * vec4(lightPos"+e+", 1.0)).xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")):(f.push("tmpVec3 = lightPos"+e+".xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")),f.push("vViewLightReverseDirAndDist"+e+" = vec4(tmpVec3, lightDist);")))}u&&(d?f.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"):f.push("vUV = uv;"));i.colors&&f.push("vColor = color;");"points"===i.primitiveName&&f.push("gl_PointSize = pointSize;");p&&f.push("vWorldPosition = worldPosition;");f.push(" vViewPosition = viewPosition.xyz;"),f.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(f.push("vFragDepth = 1.0 + clipPos.w;"),f.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));o&&f.push("clipPos.z = clipPos.w;");if(f.push("gl_Position = clipPos;"),A){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);"),f.push("vec4 tempx; ");for(let e=0,t=a.lights.length;e<t;e++)a.lights[e].castsShadow&&f.push("vShadowPosFromLight"+e+" = texUnitConverter * shadowProjMatrix"+e+" * (shadowViewMatrix"+e+" * worldPosition); ")}return f.push("}"),f}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const s=e._material,n=e._geometry._state,i=e.scene._sectionPlanesState,a=e.scene._lightsState,r=e._material._state,l=i.sectionPlanes.length>0,o=As(e),c=n.uvBuf,u="PhongMaterial"===r.type,h="MetallicMaterial"===r.type,p="SpecularMaterial"===r.type,A=ps(e);t.gammaInput;const d=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));A&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),d&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(l){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var I=0;I<i.sectionPlanes.length;I++)f.push("uniform bool sectionPlaneActive"+I+";"),f.push("uniform vec3 sectionPlanePos"+I+";"),f.push("uniform vec3 sectionPlaneDir"+I+";")}o&&(a.lightMaps.length>0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),a.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(a.lightMaps.length>0||a.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("};"),u&&((a.lightMaps.length>0||a.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.lightMaps.length>0&&(f.push(" vec3 irradiance = "+hs[a.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;")),a.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(h||p)&&(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("}"),a.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 = "+hs[a.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("}"),(a.lightMaps.length>0||a.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.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;")),a.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;"),n.colors&&f.push("in vec4 vColor;");c&&(o&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._occlusionMap||s._alphaMap)&&f.push("in vec2 vUV;");o&&(a.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));r.ambient&&f.push("uniform vec3 materialAmbient;");r.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==r.alpha&&null!==r.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");r.emissive&&f.push("uniform vec3 materialEmissive;");r.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==r.glossiness&&null!==r.glossiness&&f.push("uniform float materialGlossiness;");void 0!==r.shininess&&null!==r.shininess&&f.push("uniform float materialShininess;");r.specular&&f.push("uniform vec3 materialSpecular;");void 0!==r.metallic&&null!==r.metallic&&f.push("uniform float materialMetallic;");void 0!==r.roughness&&null!==r.roughness&&f.push("uniform float materialRoughness;");void 0!==r.specularF0&&null!==r.specularF0&&f.push("uniform float materialSpecularF0;");c&&s._ambientMap&&(f.push("uniform sampler2D ambientMap;"),s._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));c&&s._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),s._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));c&&s._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),s._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));c&&s._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),s._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));o&&c&&s._metallicMap&&(f.push("uniform sampler2D metallicMap;"),s._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));o&&c&&s._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),s._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));o&&c&&s._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),s._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));o&&s._normalMap&&(f.push("uniform sampler2D normalMap;"),s._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));c&&s._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),s._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));c&&s._alphaMap&&(f.push("uniform sampler2D alphaMap;"),s._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));o&&c&&s._specularMap&&(f.push("uniform sampler2D specularMap;"),s._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));o&&c&&s._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),s._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));o&&c&&s._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),s._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));o&&(s._diffuseFresnel||s._specularFresnel||s._alphaFresnel||s._emissiveFresnel||s._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),s._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),s._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),s._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),s._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),s._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),o)for(let e=0,t=a.lights.length;e<t;e++){const t=a.lights[e];"ambient"!==t.type&&(f.push("uniform vec4 lightColor"+e+";"),"point"===t.type&&f.push("uniform vec3 lightAttenuation"+e+";"),"dir"===t.type&&"view"===t.space&&f.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&"view"===t.space?f.push("uniform vec3 lightPos"+e+";"):f.push("in vec4 vViewLightReverseDirAndDist"+e+";"))}if(A)for(let e=0,t=a.lights.length;e<t;e++)a.lights[e].castsShadow&&(f.push("in vec4 vShadowPosFromLight"+e+";"),f.push("uniform sampler2D shadowMap"+e+";"));if(f.push("uniform vec4 colorize;"),f.push("out vec4 outColor;"),f.push("void main(void) {"),l){f.push("if (clippable) {"),f.push(" float dist = 0.0;");for(I=0;I<i.sectionPlanes.length;I++)f.push("if (sectionPlaneActive"+I+") {"),f.push(" dist += clamp(dot(-sectionPlaneDir"+I+".xyz, vWorldPosition.xyz - sectionPlanePos"+I+".xyz), 0.0, 1000.0);"),f.push("}");f.push(" if (dist > 0.0) { discard; }"),f.push("}")}"points"===n.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;"),r.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");r.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):r.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");n.colors&&f.push("diffuseColor *= vColor.rgb;");r.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");r.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==r.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");n.colors&&f.push("alpha *= vColor.a;");void 0!==r.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==r.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==r.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==r.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");c&&(o&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._occlusionMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));c&&s._ambientMap&&(s._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+hs[s._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));c&&s._diffuseMap&&(s._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+hs[s._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));c&&s._baseColorMap&&(s._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+hs[s._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));c&&s._emissiveMap&&(s._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+hs[s._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));c&&s._alphaMap&&(s._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));c&&s._occlusionMap&&(s._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(o&&(a.lights.length>0||a.lightMaps.length>0||a.reflectionMaps.length>0)){c&&s._normalMap?(s._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),c&&s._specularMap&&(s._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),c&&s._glossinessMap&&(s._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),c&&s._specularGlossinessMap&&(s._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),c&&s._metallicMap&&(s._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),c&&s._roughnessMap&&(s._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),c&&s._metallicRoughnessMap&&(s._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),s._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),s._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),s._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),s._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),u&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),p&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),h&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),a.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),u&&(a.lightMaps.length>0||a.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(p||h)&&(a.lightMaps.length>0||a.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=a.lights.length;e<t;e++){const t=a.lights[e];"ambient"!==t.type&&("dir"===t.type&&"view"===t.space?f.push("viewLightDir = -normalize(lightDir"+e+");"):"point"===t.type&&"view"===t.space?f.push("viewLightDir = normalize(lightPos"+e+" - vViewPosition);"):f.push("viewLightDir = normalize(vViewLightReverseDirAndDist"+e+".xyz);"),A&&t.castsShadow?(f.push("shadow = 0.0;"),f.push("fragmentDepth = vShadowPosFromLight"+e+".xyz;"),f.push("fragmentDepth.z -= shadowAcneRemover;"),f.push("for (int x = -3; x <= 3; x++) {"),f.push(" for (int y = -3; y <= 3; y++) {"),f.push(" float texelDepth = unpackDepth(texture(shadowMap"+e+", fragmentDepth.xy + vec2(x, y) * texelSize));"),f.push(" if (fragmentDepth.z < texelDepth) {"),f.push(" shadow += 1.0;"),f.push(" }"),f.push(" }"),f.push("}"),f.push("shadow = shadow / 9.0;"),f.push("light.color = lightColor"+e+".rgb * (lightColor"+e+".a * shadow);")):f.push("light.color = lightColor"+e+".rgb * (lightColor"+e+".a );"),f.push("light.direction = viewLightDir;"),u&&f.push("computePhongLighting(light, geometry, material, reflectedLight);"),(p||h)&&f.push("computePBRLighting(light, geometry, material, reflectedLight);"))}u?f.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * diffuseColor) + ((occlusion * (( reflectedLight.diffuse + reflectedLight.specular)))) + emissiveColor;"):f.push("vec3 outgoingLight = (occlusion * (reflectedLight.diffuse)) + (occlusion * reflectedLight.specular) + emissiveColor;")}else f.push("ambientColor *= (lightAmbient.rgb * lightAmbient.a);"),f.push("vec3 outgoingLight = emissiveColor + ambientColor;");f.push("vec4 fragColor = vec4(outgoingLight, alpha) * colorize;"),d&&f.push("fragColor = linearToGamma(fragColor, gammaFactor);");f.push("outColor = fragColor;"),t.logarithmicDepthBufferEnabled&&f.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return f.push("}"),f}(e))},hs={};function ps(e){if(!e.receivesShadow)return!1;const t=e.scene._lightsState.lights;if(!t||0===t.length)return!1;for(let e=0,s=t.length;e<s;e++)if(t[e].castsShadow)return!0;return!1}function As(e){const t=e._geometry._state.primitiveName;return!(!e._geometry._state.autoVertexNormals&&!e._geometry._state.normalsBuf||"triangles"!==t&&"triangle-strip"!==t&&"triangle-fan"!==t)}hs[3e3]="linearToLinear",hs[3001]="sRGBToLinear";const ds=h.vec3(),fs=new e({}),Is=function(e,t){this.id=fs.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new us(t),this._allocate(t)},ys={};Is.get=function(e){const t=e.scene,s=[t.canvas.canvas.id,(t.gammaInput?"gi;":";")+(t.gammaOutput?"go":""),t._lightsState.getHash(),t._sectionPlanesState.getHash(),e._geometry._state.hash,e._material._state.hash,e._state.drawHash].join(";");let n=ys[s];if(!n){if(n=new Is(s,e),n.errors)return console.log(n.errors.join("\n")),null;ys[s]=n,A.memory.programs++}return n._useCount++,n},Is.prototype.put=function(){0==--this._useCount&&(fs.removeItem(this.id),this._program&&this._program.destroy(),delete ys[this._hash],A.memory.programs--)},Is.prototype.webglContextRestored=function(){this._program=null},Is.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=oe.MAX_TEXTURE_UNITS,n=t.scene,i=t._material,a=n.canvas.gl,r=this._program,l=t._state,o=t._material._state,c=t._geometry._state,u=n.camera,h=t.origin,p=l.background;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,p&&a.depthFunc(a.LEQUAL),this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(l.originHash,h):u.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,u.viewNormalMatrix),l.clippable){const e=n._sectionPlanesState.sectionPlanes.length;if(e>0){const s=n._sectionPlanesState.sectionPlanes,i=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const n=i.sectionPlanesActivePerLayer[t];if(a.uniform1i(e.active,n?1:0),n){const n=s[t];a.uniform3fv(e.pos,h?N(n.dist,n.dir,h,ds):n.pos),a.uniform3fv(e.dir,n.dir)}}}}}if(o.id!==this._lastMaterialId){e.textureUnit=this._baseTextureUnit;const t=o.backfaces;e.backfaces!==t&&(t?a.disable(a.CULL_FACE):a.enable(a.CULL_FACE),e.backfaces=t);const n=o.frontface;switch(e.frontface!==n&&(n?a.frontFace(a.CCW):a.frontFace(a.CW),e.frontface=n),e.lineWidth!==o.lineWidth&&(a.lineWidth(o.lineWidth),e.lineWidth=o.lineWidth),this._uPointSize&&a.uniform1f(this._uPointSize,o.pointSize),o.type){case"LambertMaterial":this._uMaterialAmbient&&a.uniform3fv(this._uMaterialAmbient,o.ambient),this._uMaterialColor&&a.uniform4f(this._uMaterialColor,o.color[0],o.color[1],o.color[2],o.alpha),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive);break;case"PhongMaterial":this._uMaterialShininess&&a.uniform1f(this._uMaterialShininess,o.shininess),this._uMaterialAmbient&&a.uniform3fv(this._uMaterialAmbient,o.ambient),this._uMaterialDiffuse&&a.uniform3fv(this._uMaterialDiffuse,o.diffuse),this._uMaterialSpecular&&a.uniform3fv(this._uMaterialSpecular,o.specular),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive),this._uAlphaModeCutoff&&a.uniform4f(this._uAlphaModeCutoff,1*o.alpha,1===o.alphaMode?1:0,o.alphaCutoff,0),i._ambientMap&&i._ambientMap._state.texture&&this._uMaterialAmbientMap&&(r.bindTexture(this._uMaterialAmbientMap,i._ambientMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uMaterialAmbientMapMatrix&&a.uniformMatrix4fv(this._uMaterialAmbientMapMatrix,!1,i._ambientMap._state.matrix)),i._diffuseMap&&i._diffuseMap._state.texture&&this._uDiffuseMap&&(r.bindTexture(this._uDiffuseMap,i._diffuseMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uDiffuseMapMatrix&&a.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,i._diffuseMap._state.matrix)),i._specularMap&&i._specularMap._state.texture&&this._uSpecularMap&&(r.bindTexture(this._uSpecularMap,i._specularMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uSpecularMapMatrix&&a.uniformMatrix4fv(this._uSpecularMapMatrix,!1,i._specularMap._state.matrix)),i._emissiveMap&&i._emissiveMap._state.texture&&this._uEmissiveMap&&(r.bindTexture(this._uEmissiveMap,i._emissiveMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uEmissiveMapMatrix&&a.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,i._emissiveMap._state.matrix)),i._alphaMap&&i._alphaMap._state.texture&&this._uAlphaMap&&(r.bindTexture(this._uAlphaMap,i._alphaMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uAlphaMapMatrix&&a.uniformMatrix4fv(this._uAlphaMapMatrix,!1,i._alphaMap._state.matrix)),i._reflectivityMap&&i._reflectivityMap._state.texture&&this._uReflectivityMap&&(r.bindTexture(this._uReflectivityMap,i._reflectivityMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,this._uReflectivityMapMatrix&&a.uniformMatrix4fv(this._uReflectivityMapMatrix,!1,i._reflectivityMap._state.matrix)),i._normalMap&&i._normalMap._state.texture&&this._uNormalMap&&(r.bindTexture(this._uNormalMap,i._normalMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uNormalMapMatrix&&a.uniformMatrix4fv(this._uNormalMapMatrix,!1,i._normalMap._state.matrix)),i._occlusionMap&&i._occlusionMap._state.texture&&this._uOcclusionMap&&(r.bindTexture(this._uOcclusionMap,i._occlusionMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uOcclusionMapMatrix&&a.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,i._occlusionMap._state.matrix)),i._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias&&a.uniform1f(this._uDiffuseFresnelEdgeBias,i._diffuseFresnel.edgeBias),this._uDiffuseFresnelCenterBias&&a.uniform1f(this._uDiffuseFresnelCenterBias,i._diffuseFresnel.centerBias),this._uDiffuseFresnelEdgeColor&&a.uniform3fv(this._uDiffuseFresnelEdgeColor,i._diffuseFresnel.edgeColor),this._uDiffuseFresnelCenterColor&&a.uniform3fv(this._uDiffuseFresnelCenterColor,i._diffuseFresnel.centerColor),this._uDiffuseFresnelPower&&a.uniform1f(this._uDiffuseFresnelPower,i._diffuseFresnel.power)),i._specularFresnel&&(this._uSpecularFresnelEdgeBias&&a.uniform1f(this._uSpecularFresnelEdgeBias,i._specularFresnel.edgeBias),this._uSpecularFresnelCenterBias&&a.uniform1f(this._uSpecularFresnelCenterBias,i._specularFresnel.centerBias),this._uSpecularFresnelEdgeColor&&a.uniform3fv(this._uSpecularFresnelEdgeColor,i._specularFresnel.edgeColor),this._uSpecularFresnelCenterColor&&a.uniform3fv(this._uSpecularFresnelCenterColor,i._specularFresnel.centerColor),this._uSpecularFresnelPower&&a.uniform1f(this._uSpecularFresnelPower,i._specularFresnel.power)),i._alphaFresnel&&(this._uAlphaFresnelEdgeBias&&a.uniform1f(this._uAlphaFresnelEdgeBias,i._alphaFresnel.edgeBias),this._uAlphaFresnelCenterBias&&a.uniform1f(this._uAlphaFresnelCenterBias,i._alphaFresnel.centerBias),this._uAlphaFresnelEdgeColor&&a.uniform3fv(this._uAlphaFresnelEdgeColor,i._alphaFresnel.edgeColor),this._uAlphaFresnelCenterColor&&a.uniform3fv(this._uAlphaFresnelCenterColor,i._alphaFresnel.centerColor),this._uAlphaFresnelPower&&a.uniform1f(this._uAlphaFresnelPower,i._alphaFresnel.power)),i._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias&&a.uniform1f(this._uReflectivityFresnelEdgeBias,i._reflectivityFresnel.edgeBias),this._uReflectivityFresnelCenterBias&&a.uniform1f(this._uReflectivityFresnelCenterBias,i._reflectivityFresnel.centerBias),this._uReflectivityFresnelEdgeColor&&a.uniform3fv(this._uReflectivityFresnelEdgeColor,i._reflectivityFresnel.edgeColor),this._uReflectivityFresnelCenterColor&&a.uniform3fv(this._uReflectivityFresnelCenterColor,i._reflectivityFresnel.centerColor),this._uReflectivityFresnelPower&&a.uniform1f(this._uReflectivityFresnelPower,i._reflectivityFresnel.power)),i._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias&&a.uniform1f(this._uEmissiveFresnelEdgeBias,i._emissiveFresnel.edgeBias),this._uEmissiveFresnelCenterBias&&a.uniform1f(this._uEmissiveFresnelCenterBias,i._emissiveFresnel.centerBias),this._uEmissiveFresnelEdgeColor&&a.uniform3fv(this._uEmissiveFresnelEdgeColor,i._emissiveFresnel.edgeColor),this._uEmissiveFresnelCenterColor&&a.uniform3fv(this._uEmissiveFresnelCenterColor,i._emissiveFresnel.centerColor),this._uEmissiveFresnelPower&&a.uniform1f(this._uEmissiveFresnelPower,i._emissiveFresnel.power));break;case"MetallicMaterial":this._uBaseColor&&a.uniform3fv(this._uBaseColor,o.baseColor),this._uMaterialMetallic&&a.uniform1f(this._uMaterialMetallic,o.metallic),this._uMaterialRoughness&&a.uniform1f(this._uMaterialRoughness,o.roughness),this._uMaterialSpecularF0&&a.uniform1f(this._uMaterialSpecularF0,o.specularF0),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive),this._uAlphaModeCutoff&&a.uniform4f(this._uAlphaModeCutoff,1*o.alpha,1===o.alphaMode?1:0,o.alphaCutoff,0);const t=i._baseColorMap;t&&t._state.texture&&this._uBaseColorMap&&(r.bindTexture(this._uBaseColorMap,t._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uBaseColorMapMatrix&&a.uniformMatrix4fv(this._uBaseColorMapMatrix,!1,t._state.matrix));const n=i._metallicMap;n&&n._state.texture&&this._uMetallicMap&&(r.bindTexture(this._uMetallicMap,n._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uMetallicMapMatrix&&a.uniformMatrix4fv(this._uMetallicMapMatrix,!1,n._state.matrix));const l=i._roughnessMap;l&&l._state.texture&&this._uRoughnessMap&&(r.bindTexture(this._uRoughnessMap,l._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uRoughnessMapMatrix&&a.uniformMatrix4fv(this._uRoughnessMapMatrix,!1,l._state.matrix));const c=i._metallicRoughnessMap;c&&c._state.texture&&this._uMetallicRoughnessMap&&(r.bindTexture(this._uMetallicRoughnessMap,c._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uMetallicRoughnessMapMatrix&&a.uniformMatrix4fv(this._uMetallicRoughnessMapMatrix,!1,c._state.matrix)),(A=i._emissiveMap)&&A._state.texture&&this._uEmissiveMap&&(r.bindTexture(this._uEmissiveMap,A._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uEmissiveMapMatrix&&a.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,A._state.matrix)),(d=i._occlusionMap)&&i._occlusionMap._state.texture&&this._uOcclusionMap&&(r.bindTexture(this._uOcclusionMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uOcclusionMapMatrix&&a.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,d._state.matrix)),(f=i._alphaMap)&&f._state.texture&&this._uAlphaMap&&(r.bindTexture(this._uAlphaMap,f._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uAlphaMapMatrix&&a.uniformMatrix4fv(this._uAlphaMapMatrix,!1,f._state.matrix)),(I=i._normalMap)&&I._state.texture&&this._uNormalMap&&(r.bindTexture(this._uNormalMap,I._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uNormalMapMatrix&&a.uniformMatrix4fv(this._uNormalMapMatrix,!1,I._state.matrix));break;case"SpecularMaterial":this._uMaterialDiffuse&&a.uniform3fv(this._uMaterialDiffuse,o.diffuse),this._uMaterialSpecular&&a.uniform3fv(this._uMaterialSpecular,o.specular),this._uMaterialGlossiness&&a.uniform1f(this._uMaterialGlossiness,o.glossiness),this._uMaterialReflectivity&&a.uniform1f(this._uMaterialReflectivity,o.reflectivity),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive),this._uAlphaModeCutoff&&a.uniform4f(this._uAlphaModeCutoff,1*o.alpha,1===o.alphaMode?1:0,o.alphaCutoff,0);const u=i._diffuseMap;u&&u._state.texture&&this._uDiffuseMap&&(r.bindTexture(this._uDiffuseMap,u._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uDiffuseMapMatrix&&a.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,u._state.matrix));const h=i._specularMap;h&&h._state.texture&&this._uSpecularMap&&(r.bindTexture(this._uSpecularMap,h._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uSpecularMapMatrix&&a.uniformMatrix4fv(this._uSpecularMapMatrix,!1,h._state.matrix));const p=i._glossinessMap;p&&p._state.texture&&this._uGlossinessMap&&(r.bindTexture(this._uGlossinessMap,p._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uGlossinessMapMatrix&&a.uniformMatrix4fv(this._uGlossinessMapMatrix,!1,p._state.matrix));const y=i._specularGlossinessMap;var A,d,f,I;y&&y._state.texture&&this._uSpecularGlossinessMap&&(r.bindTexture(this._uSpecularGlossinessMap,y._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uSpecularGlossinessMapMatrix&&a.uniformMatrix4fv(this._uSpecularGlossinessMapMatrix,!1,y._state.matrix)),(A=i._emissiveMap)&&A._state.texture&&this._uEmissiveMap&&(r.bindTexture(this._uEmissiveMap,A._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uEmissiveMapMatrix&&a.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,A._state.matrix)),(d=i._occlusionMap)&&d._state.texture&&this._uOcclusionMap&&(r.bindTexture(this._uOcclusionMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uOcclusionMapMatrix&&a.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,d._state.matrix)),(f=i._alphaMap)&&f._state.texture&&this._uAlphaMap&&(r.bindTexture(this._uAlphaMap,f._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uAlphaMapMatrix&&a.uniformMatrix4fv(this._uAlphaMapMatrix,!1,f._state.matrix)),(I=i._normalMap)&&I._state.texture&&this._uNormalMap&&(r.bindTexture(this._uNormalMap,I._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uNormalMapMatrix&&a.uniformMatrix4fv(this._uNormalMapMatrix,!1,I._state.matrix))}this._lastMaterialId=o.id}if(a.uniformMatrix4fv(this._uModelMatrix,a.FALSE,t.worldMatrix),this._uModelNormalMatrix&&a.uniformMatrix4fv(this._uModelNormalMatrix,a.FALSE,t.worldNormalMatrix),this._uClippable&&a.uniform1i(this._uClippable,l.clippable),this._uColorize){const e=l.colorize,t=this._lastColorize;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(a.uniform4fv(this._uColorize,e),t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3])}a.uniform3fv(this._uOffset,l.offset),c.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,c.positionsDecodeMatrix),this._uUVDecodeMatrix&&a.uniformMatrix3fv(this._uUVDecodeMatrix,!1,c.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(c.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(c.normalsBuf),e.bindArray++),this._aUV&&(this._aUV.bindArrayBuffer(c.uvBuf),e.bindArray++),this._aColor&&(this._aColor.bindArrayBuffer(c.colorsBuf),e.bindArray++),this._aFlags&&(this._aFlags.bindArrayBuffer(c.flagsBuf),e.bindArray++),c.indicesBuf&&(c.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=c.id),c.indicesBuf?(a.drawElements(c.primitive,c.indicesBuf.numItems,c.indicesBuf.itemType,0),e.drawElements++):c.positions&&(a.drawArrays(a.TRIANGLES,0,c.positions.numItems),e.drawArrays++),p&&a.depthFunc(a.LESS)},Is.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl,n=e._material,i=t._lightsState,a=t._sectionPlanesState,r=e._material._state;if(this._program=new we(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const l=this._program;this._uPositionsDecodeMatrix=l.getLocation("positionsDecodeMatrix"),this._uUVDecodeMatrix=l.getLocation("uvDecodeMatrix"),this._uModelMatrix=l.getLocation("modelMatrix"),this._uModelNormalMatrix=l.getLocation("modelNormalMatrix"),this._uViewMatrix=l.getLocation("viewMatrix"),this._uViewNormalMatrix=l.getLocation("viewNormalMatrix"),this._uProjMatrix=l.getLocation("projMatrix"),this._uGammaFactor=l.getLocation("gammaFactor"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[],this._uShadowViewMatrix=[],this._uShadowProjMatrix=[],t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=l.getLocation("logDepthBufFC"));const o=i.lights;let c;for(var u=0,h=o.length;u<h;u++){switch(c=o[u],c.type){case"ambient":this._uLightAmbient[u]=l.getLocation("lightAmbient");break;case"dir":this._uLightColor[u]=l.getLocation("lightColor"+u),this._uLightPos[u]=null,this._uLightDir[u]=l.getLocation("lightDir"+u);break;case"point":this._uLightColor[u]=l.getLocation("lightColor"+u),this._uLightPos[u]=l.getLocation("lightPos"+u),this._uLightDir[u]=null,this._uLightAttenuation[u]=l.getLocation("lightAttenuation"+u);break;case"spot":this._uLightColor[u]=l.getLocation("lightColor"+u),this._uLightPos[u]=l.getLocation("lightPos"+u),this._uLightDir[u]=l.getLocation("lightDir"+u),this._uLightAttenuation[u]=l.getLocation("lightAttenuation"+u)}c.castsShadow&&(this._uShadowViewMatrix[u]=l.getLocation("shadowViewMatrix"+u),this._uShadowProjMatrix[u]=l.getLocation("shadowProjMatrix"+u))}i.lightMaps.length>0&&(this._uLightMap="lightMap"),i.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(u=0,h=a.sectionPlanes.length;u<h;u++)this._uSectionPlanes.push({active:l.getLocation("sectionPlaneActive"+u),pos:l.getLocation("sectionPlanePos"+u),dir:l.getLocation("sectionPlaneDir"+u)});switch(this._uPointSize=l.getLocation("pointSize"),r.type){case"LambertMaterial":this._uMaterialColor=l.getLocation("materialColor"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff");break;case"PhongMaterial":this._uMaterialAmbient=l.getLocation("materialAmbient"),this._uMaterialDiffuse=l.getLocation("materialDiffuse"),this._uMaterialSpecular=l.getLocation("materialSpecular"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff"),this._uMaterialShininess=l.getLocation("materialShininess"),n._ambientMap&&(this._uMaterialAmbientMap="ambientMap",this._uMaterialAmbientMapMatrix=l.getLocation("ambientMapMatrix")),n._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=l.getLocation("diffuseMapMatrix")),n._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=l.getLocation("specularMapMatrix")),n._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=l.getLocation("emissiveMapMatrix")),n._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=l.getLocation("alphaMapMatrix")),n._reflectivityMap&&(this._uReflectivityMap="reflectivityMap",this._uReflectivityMapMatrix=l.getLocation("reflectivityMapMatrix")),n._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=l.getLocation("normalMapMatrix")),n._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=l.getLocation("occlusionMapMatrix")),n._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias=l.getLocation("diffuseFresnelEdgeBias"),this._uDiffuseFresnelCenterBias=l.getLocation("diffuseFresnelCenterBias"),this._uDiffuseFresnelEdgeColor=l.getLocation("diffuseFresnelEdgeColor"),this._uDiffuseFresnelCenterColor=l.getLocation("diffuseFresnelCenterColor"),this._uDiffuseFresnelPower=l.getLocation("diffuseFresnelPower")),n._specularFresnel&&(this._uSpecularFresnelEdgeBias=l.getLocation("specularFresnelEdgeBias"),this._uSpecularFresnelCenterBias=l.getLocation("specularFresnelCenterBias"),this._uSpecularFresnelEdgeColor=l.getLocation("specularFresnelEdgeColor"),this._uSpecularFresnelCenterColor=l.getLocation("specularFresnelCenterColor"),this._uSpecularFresnelPower=l.getLocation("specularFresnelPower")),n._alphaFresnel&&(this._uAlphaFresnelEdgeBias=l.getLocation("alphaFresnelEdgeBias"),this._uAlphaFresnelCenterBias=l.getLocation("alphaFresnelCenterBias"),this._uAlphaFresnelEdgeColor=l.getLocation("alphaFresnelEdgeColor"),this._uAlphaFresnelCenterColor=l.getLocation("alphaFresnelCenterColor"),this._uAlphaFresnelPower=l.getLocation("alphaFresnelPower")),n._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias=l.getLocation("reflectivityFresnelEdgeBias"),this._uReflectivityFresnelCenterBias=l.getLocation("reflectivityFresnelCenterBias"),this._uReflectivityFresnelEdgeColor=l.getLocation("reflectivityFresnelEdgeColor"),this._uReflectivityFresnelCenterColor=l.getLocation("reflectivityFresnelCenterColor"),this._uReflectivityFresnelPower=l.getLocation("reflectivityFresnelPower")),n._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias=l.getLocation("emissiveFresnelEdgeBias"),this._uEmissiveFresnelCenterBias=l.getLocation("emissiveFresnelCenterBias"),this._uEmissiveFresnelEdgeColor=l.getLocation("emissiveFresnelEdgeColor"),this._uEmissiveFresnelCenterColor=l.getLocation("emissiveFresnelCenterColor"),this._uEmissiveFresnelPower=l.getLocation("emissiveFresnelPower"));break;case"MetallicMaterial":this._uBaseColor=l.getLocation("materialBaseColor"),this._uMaterialMetallic=l.getLocation("materialMetallic"),this._uMaterialRoughness=l.getLocation("materialRoughness"),this._uMaterialSpecularF0=l.getLocation("materialSpecularF0"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff"),n._baseColorMap&&(this._uBaseColorMap="baseColorMap",this._uBaseColorMapMatrix=l.getLocation("baseColorMapMatrix")),n._metallicMap&&(this._uMetallicMap="metallicMap",this._uMetallicMapMatrix=l.getLocation("metallicMapMatrix")),n._roughnessMap&&(this._uRoughnessMap="roughnessMap",this._uRoughnessMapMatrix=l.getLocation("roughnessMapMatrix")),n._metallicRoughnessMap&&(this._uMetallicRoughnessMap="metallicRoughnessMap",this._uMetallicRoughnessMapMatrix=l.getLocation("metallicRoughnessMapMatrix")),n._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=l.getLocation("emissiveMapMatrix")),n._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=l.getLocation("occlusionMapMatrix")),n._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=l.getLocation("alphaMapMatrix")),n._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=l.getLocation("normalMapMatrix"));break;case"SpecularMaterial":this._uMaterialDiffuse=l.getLocation("materialDiffuse"),this._uMaterialSpecular=l.getLocation("materialSpecular"),this._uMaterialGlossiness=l.getLocation("materialGlossiness"),this._uMaterialReflectivity=l.getLocation("reflectivityFresnel"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff"),n._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=l.getLocation("diffuseMapMatrix")),n._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=l.getLocation("specularMapMatrix")),n._glossinessMap&&(this._uGlossinessMap="glossinessMap",this._uGlossinessMapMatrix=l.getLocation("glossinessMapMatrix")),n._specularGlossinessMap&&(this._uSpecularGlossinessMap="materialSpecularGlossinessMap",this._uSpecularGlossinessMapMatrix=l.getLocation("materialSpecularGlossinessMapMatrix")),n._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=l.getLocation("emissiveMapMatrix")),n._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=l.getLocation("occlusionMapMatrix")),n._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=l.getLocation("alphaMapMatrix")),n._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=l.getLocation("normalMapMatrix"))}this._aPosition=l.getAttribute("position"),this._aNormal=l.getAttribute("normal"),this._aUV=l.getAttribute("uv"),this._aColor=l.getAttribute("color"),this._aFlags=l.getAttribute("flags"),this._uClippable=l.getLocation("clippable"),this._uColorize=l.getLocation("colorize"),this._uOffset=l.getLocation("offset"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize=new Float32Array(4),this._baseTextureUnit=0},Is.prototype._bindProgram=function(e){const t=oe.MAX_TEXTURE_UNITS,s=this._scene,n=s.canvas.gl,i=s._lightsState,a=s.camera.project;let r;const l=this._program;if(l.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize[0]=-1,this._lastColorize[1]=-1,this._lastColorize[2]=-1,this._lastColorize[3]=-1,n.uniformMatrix4fv(this._uProjMatrix,!1,a.matrix),s.logarithmicDepthBufferEnabled){const e=2/(Math.log(a.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}for(var o=0,c=i.lights.length;o<c;o++)if(r=i.lights[o],this._uLightAmbient[o])n.uniform4f(this._uLightAmbient[o],r.color[0],r.color[1],r.color[2],r.intensity);else if(this._uLightColor[o]&&n.uniform4f(this._uLightColor[o],r.color[0],r.color[1],r.color[2],r.intensity),this._uLightPos[o]&&(n.uniform3fv(this._uLightPos[o],r.pos),this._uLightAttenuation[o]&&n.uniform1f(this._uLightAttenuation[o],r.attenuation)),this._uLightDir[o]&&n.uniform3fv(this._uLightDir[o],r.dir),r.castsShadow){this._uShadowViewMatrix[o]&&n.uniformMatrix4fv(this._uShadowViewMatrix[o],!1,r.getShadowViewMatrix()),this._uShadowProjMatrix[o]&&n.uniformMatrix4fv(this._uShadowProjMatrix[o],!1,r.getShadowProjMatrix());const s=r.getShadowRenderBuf();s&&(l.bindTexture("shadowMap"+o,s.getTexture(),e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++)}i.lightMaps.length>0&&i.lightMaps[0].texture&&this._uLightMap&&(l.bindTexture(this._uLightMap,i.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),i.reflectionMaps.length>0&&i.reflectionMaps[0].texture&&this._uReflectionMap&&(l.bindTexture(this._uReflectionMap,i.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&n.uniform1f(this._uGammaFactor,s.gammaFactor),this._baseTextureUnit=e.textureUnit};class ms{constructor(e){this.vertex=function(e){const t=e.scene,s=t._lightsState,n=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),i=t._sectionPlanesState.sectionPlanes.length>0,a=!!e._geometry._state.compressGeometry,r=e._state.billboard,l=e._state.stationary,o=[];o.push("#version 300 es"),o.push("// EmphasisFillShaderSource vertex shader"),o.push("in vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform vec4 colorize;"),o.push("uniform vec3 offset;"),a&&o.push("uniform mat4 positionsDecodeMatrix;");t.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;"));i&&o.push("out vec4 vWorldPosition;");if(o.push("uniform vec4 lightAmbient;"),o.push("uniform vec4 fillColor;"),n){o.push("in vec3 normal;"),o.push("uniform mat4 modelNormalMatrix;"),o.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(o.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&o.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&o.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&o.push("uniform vec3 lightPos"+e+";"))}a&&(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 vColor;"),("spherical"===r||"cylindrical"===r)&&(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = 1.0;"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===r&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}"));o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),o.push("vec4 worldPosition;"),a&&o.push("localPosition = positionsDecodeMatrix * localPosition;");n&&(a?o.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):o.push("vec4 localNormal = vec4(normal, 0.0); "),o.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),o.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),l&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"),o.push("billboard(modelViewMatrix);"),n&&(o.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),o.push("billboard(modelNormalMatrix2);"),o.push("billboard(viewNormalMatrix2);"),o.push("billboard(modelViewNormalMatrix);")),o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n&&o.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(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;"),n)for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);");else{if("point"!==t.type)continue;"view"===t.space?o.push("viewLightDir = normalize(lightPos"+e+" - viewPosition.xyz);"):o.push("viewLightDir = normalize((viewMatrix2 * vec4(lightPos"+e+", 0.0)).xyz);")}o.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),o.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}o.push("vColor = vec4(reflectedColor * fillColor.rgb, fillColor.a);"),i&&o.push("vWorldPosition = worldPosition;");"points"===e._geometry._state.primitiveName&&o.push("gl_PointSize = pointSize;");o.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return o.push("gl_Position = clipPos;"),o.push("}"),o}(e),this.fragment=function(e){const t=e.scene,s=e.scene._sectionPlanesState,n=e.scene.gammaOutput,i=s.sectionPlanes.length>0,a=[];a.push("#version 300 es"),a.push("// Lambertian drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),t.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;"));n&&(a.push("uniform float gammaFactor;"),a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}"));if(i){a.push("in vec4 vWorldPosition;"),a.push("uniform bool clippable;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){a.push("if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}"points"===e._geometry._state.primitiveName&&(a.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push("float r = dot(cxy, cxy);"),a.push("if (r > 1.0) {"),a.push(" discard;"),a.push("}"));t.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");n?a.push("outColor = linearToGamma(vColor, gammaFactor);"):a.push("outColor = vColor;");return a.push("}"),a}(e)}}const vs=new e({}),ws=h.vec3(),gs=function(e,t){this.id=vs.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new ms(t),this._allocate(t)},Ts={};gs.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=Ts[t];return s||(s=new gs(t,e),Ts[t]=s,A.memory.programs++),s._useCount++,s},gs.prototype.put=function(){0==--this._useCount&&(vs.removeItem(this.id),this._program&&this._program.destroy(),delete Ts[this._hash],A.memory.programs--)},gs.prototype.webglContextRestored=function(){this._program=null},gs.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const n=this._scene,i=n.camera,a=n.canvas.gl,r=0===s?t._xrayMaterial._state:1===s?t._highlightMaterial._state:t._selectedMaterial._state,l=t._state,o=t._geometry._state,c=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,c?e.getRTCViewMatrix(l.originHash,c):i.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,i.viewNormalMatrix),l.clippable){const e=n._sectionPlanesState.sectionPlanes.length;if(e>0){const s=n._sectionPlanesState.sectionPlanes,i=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const n=i.sectionPlanesActivePerLayer[t];if(a.uniform1i(e.active,n?1:0),n){const n=s[t];a.uniform3fv(e.pos,c?N(n.dist,n.dir,c,ws):n.pos),a.uniform3fv(e.dir,n.dir)}}}}}if(r.id!==this._lastMaterialId){const t=r.fillColor,s=r.backfaces;e.backfaces!==s&&(s?a.disable(a.CULL_FACE):a.enable(a.CULL_FACE),e.backfaces=s),a.uniform4f(this._uFillColor,t[0],t[1],t[2],r.fillAlpha),this._lastMaterialId=r.id}a.uniformMatrix4fv(this._uModelMatrix,a.FALSE,t.worldMatrix),this._uModelNormalMatrix&&a.uniformMatrix4fv(this._uModelNormalMatrix,a.FALSE,t.worldNormalMatrix),this._uClippable&&a.uniform1i(this._uClippable,l.clippable),a.uniform3fv(this._uOffset,l.offset),o.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,o.positionsDecodeMatrix),this._uUVDecodeMatrix&&a.uniformMatrix3fv(this._uUVDecodeMatrix,!1,o.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(o.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(o.normalsBuf),e.bindArray++),o.indicesBuf?(o.indicesBuf.bind(),e.bindArray++):o.positionsBuf,this._lastGeometryId=o.id),o.indicesBuf?(a.drawElements(o.primitive,o.indicesBuf.numItems,o.indicesBuf.itemType,0),e.drawElements++):o.positionsBuf&&(a.drawArrays(a.TRIANGLES,0,o.positionsBuf.numItems),e.drawArrays++)},gs.prototype._allocate=function(e){const t=e.scene,s=t._lightsState,n=t._sectionPlanesState,i=t.canvas.gl;if(this._program=new we(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const a=this._program;this._uPositionsDecodeMatrix=a.getLocation("positionsDecodeMatrix"),this._uModelMatrix=a.getLocation("modelMatrix"),this._uModelNormalMatrix=a.getLocation("modelNormalMatrix"),this._uViewMatrix=a.getLocation("viewMatrix"),this._uViewNormalMatrix=a.getLocation("viewNormalMatrix"),this._uProjMatrix=a.getLocation("projMatrix"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(let e=0,t=s.lights.length;e<t;e++){switch(s.lights[e].type){case"ambient":this._uLightAmbient[e]=a.getLocation("lightAmbient");break;case"dir":this._uLightColor[e]=a.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=a.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=a.getLocation("lightColor"+e),this._uLightPos[e]=a.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=a.getLocation("lightAttenuation"+e)}}this._uSectionPlanes=[];for(let e=0,t=n.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:a.getLocation("sectionPlaneActive"+e),pos:a.getLocation("sectionPlanePos"+e),dir:a.getLocation("sectionPlaneDir"+e)});this._uFillColor=a.getLocation("fillColor"),this._aPosition=a.getAttribute("position"),this._aNormal=a.getAttribute("normal"),this._uClippable=a.getLocation("clippable"),this._uGammaFactor=a.getLocation("gammaFactor"),this._uOffset=a.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=a.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},gs.prototype._bindProgram=function(e){const t=this._scene,s=t.canvas.gl,n=t._lightsState,i=t.camera,a=i.project;if(this._program.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastIndicesBufId=null,s.uniformMatrix4fv(this._uViewNormalMatrix,!1,i.normalMatrix),s.uniformMatrix4fv(this._uProjMatrix,!1,a.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(a.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];this._uLightAmbient[e]?s.uniform4f(this._uLightAmbient[e],t.color[0],t.color[1],t.color[2],t.intensity):(this._uLightColor[e]&&s.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(s.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&s.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&s.uniform3fv(this._uLightDir[e],t.dir))}this._uGammaFactor&&s.uniform1f(this._uGammaFactor,t.gammaFactor)};class Es{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry,i=e._state.billboard,a=e._state.stationary,r=[];r.push("#version 300 es"),r.push("// Edges drawing vertex shader"),r.push("in vec3 position;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec4 edgeColor;"),r.push("uniform vec3 offset;"),n&&r.push("uniform mat4 positionsDecodeMatrix;");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;"));s&&r.push("out vec4 vWorldPosition;");r.push("out vec4 vColor;"),("spherical"===i||"cylindrical"===i)&&(r.push("void billboard(inout mat4 mat) {"),r.push(" mat[0][0] = 1.0;"),r.push(" mat[0][1] = 0.0;"),r.push(" mat[0][2] = 0.0;"),"spherical"===i&&(r.push(" mat[1][0] = 0.0;"),r.push(" mat[1][1] = 1.0;"),r.push(" mat[1][2] = 0.0;")),r.push(" mat[2][0] = 0.0;"),r.push(" mat[2][1] = 0.0;"),r.push(" mat[2][2] =1.0;"),r.push("}"));r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),r.push("vec4 worldPosition;"),n&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push("mat4 viewMatrix2 = viewMatrix;"),r.push("mat4 modelMatrix2 = modelMatrix;"),a&&r.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===i||"cylindrical"===i?(r.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),r.push("billboard(modelMatrix2);"),r.push("billboard(viewMatrix2);"),r.push("billboard(modelViewMatrix);"),r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.push("vColor = edgeColor;"),s&&r.push("vWorldPosition = worldPosition;");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 = clipPos;"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,s=e.scene._sectionPlanesState,n=e.scene.gammaOutput,i=s.sectionPlanes.length>0,a=[];a.push("#version 300 es"),a.push("// Edges drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),t.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;"));n&&(a.push("uniform float gammaFactor;"),a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}"));if(i){a.push("in vec4 vWorldPosition;"),a.push("uniform bool clippable;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){a.push("if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}t.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");n?a.push("outColor = linearToGamma(vColor, gammaFactor);"):a.push("outColor = vColor;");return a.push("}"),a}(e)}}const bs=new e({}),Ds=h.vec3(),Ps=function(e,t){this.id=bs.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Es(t),this._allocate(t)},Rs={};Ps.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=Rs[t];return s||(s=new Ps(t,e),Rs[t]=s,A.memory.programs++),s._useCount++,s},Ps.prototype.put=function(){0==--this._useCount&&(bs.removeItem(this.id),this._program&&this._program.destroy(),delete Rs[this._hash],A.memory.programs--)},Ps.prototype.webglContextRestored=function(){this._program=null},Ps.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const n=this._scene,i=n.camera,a=n.canvas.gl;let r;const l=t._state,o=t._geometry,c=o._state,u=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,u?e.getRTCViewMatrix(l.originHash,u):i.viewMatrix),l.clippable){const e=n._sectionPlanesState.sectionPlanes.length;if(e>0){const s=n._sectionPlanesState.sectionPlanes,i=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const n=i.sectionPlanesActivePerLayer[t];if(a.uniform1i(e.active,n?1:0),n){const n=s[t];a.uniform3fv(e.pos,u?N(n.dist,n.dir,u,Ds):n.pos),a.uniform3fv(e.dir,n.dir)}}}}}switch(s){case 0:r=t._xrayMaterial._state;break;case 1:r=t._highlightMaterial._state;break;case 2:r=t._selectedMaterial._state;break;default:r=t._edgeMaterial._state}if(r.id!==this._lastMaterialId){const t=r.backfaces;if(e.backfaces!==t&&(t?a.disable(a.CULL_FACE):a.enable(a.CULL_FACE),e.backfaces=t),e.lineWidth!==r.edgeWidth&&(a.lineWidth(r.edgeWidth),e.lineWidth=r.edgeWidth),this._uEdgeColor){const e=r.edgeColor,t=r.edgeAlpha;a.uniform4f(this._uEdgeColor,e[0],e[1],e[2],t)}this._lastMaterialId=r.id}let h;a.uniformMatrix4fv(this._uModelMatrix,a.FALSE,t.worldMatrix),this._uClippable&&a.uniform1i(this._uClippable,l.clippable),a.uniform3fv(this._uOffset,l.offset),c.primitive===a.TRIANGLES?h=o._getEdgeIndices():c.primitive===a.LINES&&(h=c.indicesBuf),h&&(c.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,c.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(c.positionsBuf,c.compressGeometry?a.UNSIGNED_SHORT:a.FLOAT),e.bindArray++),h.bind(),e.bindArray++,this._lastGeometryId=c.id),a.drawElements(a.LINES,h.numItems,h.itemType,0),e.drawElements++)},Ps.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl,n=t._sectionPlanesState;if(this._program=new we(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=n.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+e),pos:i.getLocation("sectionPlanePos"+e),dir:i.getLocation("sectionPlaneDir"+e)});this._uEdgeColor=i.getLocation("edgeColor"),this._aPosition=i.getAttribute("position"),this._uClippable=i.getLocation("clippable"),this._uGammaFactor=i.getLocation("gammaFactor"),this._uOffset=i.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Ps.prototype._bindProgram=function(e){const t=this._program,s=this._scene,n=s.canvas.gl,i=s.camera.project;if(t.bind(),e.useProgram++,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,n.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),s.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}this._uGammaFactor&&n.uniform1f(this._uGammaFactor,s.gammaFactor)};class Cs{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry,i=e._state.billboard,a=e._state.stationary,r=[];r.push("#version 300 es"),r.push("// Mesh picking vertex shader"),r.push("in vec3 position;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("out vec4 vViewPosition;"),r.push("uniform vec3 offset;"),n&&r.push("uniform mat4 positionsDecodeMatrix;");s&&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;"));"spherical"!==i&&"cylindrical"!==i||(r.push("void billboard(inout mat4 mat) {"),r.push(" mat[0][0] = 1.0;"),r.push(" mat[0][1] = 0.0;"),r.push(" mat[0][2] = 0.0;"),"spherical"===i&&(r.push(" mat[1][0] = 0.0;"),r.push(" mat[1][1] = 1.0;"),r.push(" mat[1][2] = 0.0;")),r.push(" mat[2][0] = 0.0;"),r.push(" mat[2][1] = 0.0;"),r.push(" mat[2][2] =1.0;"),r.push("}"));r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),n&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push("mat4 viewMatrix2 = viewMatrix;"),r.push("mat4 modelMatrix2 = modelMatrix;"),a&&r.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==i&&"cylindrical"!==i||(r.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),r.push("billboard(modelMatrix2);"),r.push("billboard(viewMatrix2);"));r.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),s&&r.push(" vWorldPosition = worldPosition;");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 = clipPos;"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];i.push("#version 300 es"),i.push("// Mesh 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"),t.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"));if(i.push("uniform vec4 pickColor;"),n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(var a=0;a<s.sectionPlanes.length;a++)i.push("uniform bool sectionPlaneActive"+a+";"),i.push("uniform vec3 sectionPlanePos"+a+";"),i.push("uniform vec3 sectionPlaneDir"+a+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(a=0;a<s.sectionPlanes.length;a++)i.push("if (sectionPlaneActive"+a+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}t.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return i.push(" outColor = pickColor; "),i.push("}"),i}(e)}}const _s=h.vec3(),Bs=function(e,t){this._hash=e,this._shaderSource=new Cs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Os={};Bs.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=Os[t];if(!s){if(s=new Bs(t,e),s.errors)return console.log(s.errors.join("\n")),null;Os[t]=s,A.memory.programs++}return s._useCount++,s},Bs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Os[this._hash],A.memory.programs--)},Bs.prototype.webglContextRestored=function(){this._program=null},Bs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,n=s.canvas.gl,i=t._state,a=t._material._state,r=t._geometry._state,l=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),n.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(i.originHash,l):e.pickViewMatrix),i.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,a=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const s=a.sectionPlanesActivePerLayer[t];if(n.uniform1i(e.active,s?1:0),s){const s=i[t];n.uniform3fv(e.pos,l?N(s.dist,s.dir,l,_s):s.pos),n.uniform3fv(e.dir,s.dir)}}}}}if(a.id!==this._lastMaterialId){const t=a.backfaces;e.backfaces!==t&&(t?n.disable(n.CULL_FACE):n.enable(n.CULL_FACE),e.backfaces=t);const s=a.frontface;e.frontface!==s&&(s?n.frontFace(n.CCW):n.frontFace(n.CW),e.frontface=s),this._lastMaterialId=a.id}n.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),n.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&n.uniform1i(this._uClippable,t._state.clippable),n.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&n.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?n.UNSIGNED_SHORT:n.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=r.id);var o=t._state.pickID;const c=o>>24&255,u=o>>16&255,h=o>>8&255,p=255&o;n.uniform4f(this._uPickColor,p/255,h/255,u/255,c/255),r.indicesBuf?(n.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&n.drawArrays(n.TRIANGLES,0,r.positions.numItems)},Bs.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new we(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._uClippable=n.getLocation("clippable"),this._uPickColor=n.getLocation("pickColor"),this._uOffset=n.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastGeometryId=null},Bs.prototype._bindProgram=function(e){const t=this._scene,s=t.canvas.gl,n=t.camera.project;if(this._program.bind(),e.useProgram++,t.logarithmicDepthBufferEnabled){const e=2/(Math.log(n.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}this._lastMaterialId=null,this._lastGeometryId=null};class Ss{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry;e._state.billboard,e._state.stationary;const i=[];i.push("#version 300 es"),i.push("// Surface picking vertex shader"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform vec3 offset;"),s&&(i.push("uniform bool clippable;"),i.push("out vec4 vWorldPosition;"));t.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 vColor;"),n&&i.push("uniform mat4 positionsDecodeMatrix;");i.push("void main(void) {"),i.push("vec4 localPosition = vec4(position, 1.0); "),n&&i.push("localPosition = positionsDecodeMatrix * localPosition;");i.push(" vec4 worldPosition = modelMatrix * localPosition; "),i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),s&&i.push(" vWorldPosition = worldPosition;");i.push(" vColor = color;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return i.push("gl_Position = clipPos;"),i.push("}"),i}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];i.push("#version 300 es"),i.push("// Surface 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"),i.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"));if(n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(let e=0;e<s.sectionPlanes.length;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e<s.sectionPlanes.length;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}t.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return i.push(" outColor = vColor;"),i.push("}"),i}(e)}}const Ns=h.vec3(),xs=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Ss(t),this._allocate(t)},Ls={};xs.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=Ls[t];if(!s){if(s=new xs(t,e),s.errors)return console.log(s.errors.join("\n")),null;Ls[t]=s,A.memory.programs++}return s._useCount++,s},xs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ls[this._hash],A.memory.programs--)},xs.prototype.webglContextRestored=function(){this._program=null},xs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,n=s.canvas.gl,i=t._state,a=t._material._state,r=t._geometry,l=t._geometry._state,o=t.origin,c=a.backfaces,u=a.frontface,h=s.camera.project,p=r._getPickTrianglePositions(),A=r._getPickTriangleColors();if(this._program.bind(),e.useProgram++,s.logarithmicDepthBufferEnabled){const e=2/(Math.log(h.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}if(n.uniformMatrix4fv(this._uViewMatrix,!1,o?e.getRTCPickViewMatrix(i.originHash,o):e.pickViewMatrix),i.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,a=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const s=a.sectionPlanesActivePerLayer[t];if(n.uniform1i(e.active,s?1:0),s){const s=i[t];n.uniform3fv(e.pos,o?N(s.dist,s.dir,o,Ns):s.pos),n.uniform3fv(e.dir,s.dir)}}}}}n.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),s.logarithmicDepthBufferEnabled&&n.uniform1f(this._uZFar,s.camera.project.far),e.backfaces!==c&&(c?n.disable(n.CULL_FACE):n.enable(n.CULL_FACE),e.backfaces=c),e.frontface!==u&&(u?n.frontFace(n.CCW):n.frontFace(n.CW),e.frontface=u),n.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&n.uniform1i(this._uClippable,t._state.clippable),n.uniform3fv(this._uOffset,t._state.offset),this._uPositionsDecodeMatrix?(n.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,l.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(p,l.compressGeometry?n.UNSIGNED_SHORT:n.FLOAT)):this._aPosition.bindArrayBuffer(p),A.bind(),n.enableVertexAttribArray(this._aColor.location),n.vertexAttribPointer(this._aColor.location,A.itemSize,A.itemType,!0,0,0),n.drawArrays(l.primitive,0,p.numItems/3)},xs.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new we(s,this._shaderSource),this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._aColor=n.getAttribute("color"),this._uClippable=n.getLocation("clippable"),this._uOffset=n.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC"))};class Ms{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry,i=e._state.billboard,a=e._state.stationary,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion vertex shader"),r.push("in vec3 position;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),n&&r.push("uniform mat4 positionsDecodeMatrix;");s&&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;"));"spherical"!==i&&"cylindrical"!==i||(r.push("void billboard(inout mat4 mat) {"),r.push(" mat[0][0] = 1.0;"),r.push(" mat[0][1] = 0.0;"),r.push(" mat[0][2] = 0.0;"),"spherical"===i&&(r.push(" mat[1][0] = 0.0;"),r.push(" mat[1][1] = 1.0;"),r.push(" mat[1][2] = 0.0;")),r.push(" mat[2][0] = 0.0;"),r.push(" mat[2][1] = 0.0;"),r.push(" mat[2][2] =1.0;"),r.push("}"));r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),r.push("vec4 worldPosition;"),n&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push("mat4 viewMatrix2 = viewMatrix;"),r.push("mat4 modelMatrix2 = modelMatrix;"),a&&r.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===i||"cylindrical"===i?(r.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),r.push("billboard(modelMatrix2);"),r.push("billboard(viewMatrix2);"),r.push("billboard(modelViewMatrix);"),r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&r.push(" vWorldPosition = worldPosition;");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 = clipPos;"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];i.push("#version 300 es"),i.push("// Mesh 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.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"));if(n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(var a=0;a<s.sectionPlanes.length;a++)i.push("uniform bool sectionPlaneActive"+a+";"),i.push("uniform vec3 sectionPlanePos"+a+";"),i.push("uniform vec3 sectionPlaneDir"+a+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(a=0;a<s.sectionPlanes.length;a++)i.push("if (sectionPlaneActive"+a+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return i.push("}"),i}(e)}}const Fs=h.vec3(),Hs=function(e,t){this._hash=e,this._shaderSource=new Ms(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Us={};Hs.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let s=Us[t];if(!s){if(s=new Hs(t,e),s.errors)return console.log(s.errors.join("\n")),null;Us[t]=s,A.memory.programs++}return s._useCount++,s},Hs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Us[this._hash],A.memory.programs--)},Hs.prototype.webglContextRestored=function(){this._program=null},Hs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,n=s.canvas.gl,i=t._material._state,a=t._state,r=t._geometry._state,l=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),i.id!==this._lastMaterialId){const t=i.backfaces;e.backfaces!==t&&(t?n.disable(n.CULL_FACE):n.enable(n.CULL_FACE),e.backfaces=t);const s=i.frontface;e.frontface!==s&&(s?n.frontFace(n.CCW):n.frontFace(n.CW),e.frontface=s),this._lastMaterialId=i.id}const o=s.camera;if(n.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCViewMatrix(a.originHash,l):o.viewMatrix),a.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,a=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const s=a.sectionPlanesActivePerLayer[t];if(n.uniform1i(e.active,s?1:0),s){const s=i[t];n.uniform3fv(e.pos,l?N(s.dist,s.dir,l,Fs):s.pos),n.uniform3fv(e.dir,s.dir)}}}}}n.uniformMatrix4fv(this._uProjMatrix,!1,o._project._state.matrix),n.uniformMatrix4fv(this._uModelMatrix,n.FALSE,t.worldMatrix),this._uClippable&&n.uniform1i(this._uClippable,t._state.clippable),n.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&n.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?n.UNSIGNED_SHORT:n.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=r.id),r.indicesBuf?(n.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&n.drawArrays(n.TRIANGLES,0,r.positions.numItems)},Hs.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new we(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._uClippable=n.getLocation("clippable"),this._uOffset=n.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Hs.prototype._bindProgram=function(e){const t=this._scene,s=t.camera.project,n=t.canvas.gl;if(this._program.bind(),e.useProgram++,n.uniformMatrix4fv(this._uProjMatrix,!1,s.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null};class Gs{constructor(e){this.vertex=function(e){const t=e.scene._sectionPlanesState.sectionPlanes.length>0,s=!!e._geometry._state.compressGeometry,n=[];n.push("// Mesh shadow vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 shadowViewMatrix;"),n.push("uniform mat4 shadowProjMatrix;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");t&&n.push("out vec4 vWorldPosition;");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("worldPosition = modelMatrix * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&n.push("vWorldPosition = worldPosition;");return n.push(" gl_Position = shadowProjMatrix * viewPosition;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];if(i.push("// Mesh 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"),n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(var a=0;a<s.sectionPlanes.length;a++)i.push("uniform bool sectionPlaneActive"+a+";"),i.push("uniform vec3 sectionPlanePos"+a+";"),i.push("uniform vec3 sectionPlaneDir"+a+";")}if(i.push("vec4 encodeFloat( const in float depth ) {"),i.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),i.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),i.push(" vec4 comp = fract(depth * bitShift);"),i.push(" comp -= comp.xxyz * bitMask;"),i.push(" return comp;"),i.push("}"),i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(a=0;a<s.sectionPlanes.length;a++)i.push("if (sectionPlaneActive"+a+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}return i.push("outColor = encodeFloat(gl_FragCoord.z);"),i.push("}"),i}(e)}}const Vs=function(e,t){this._hash=e,this._shaderSource=new Gs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},js={};Vs.get=function(e){const t=e.scene,s=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let n=js[s];if(!n){if(n=new Vs(s,e),n.errors)return console.log(n.errors.join("\n")),null;js[s]=n,A.memory.programs++}return n._useCount++,n},Vs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete js[this._hash],A.memory.programs--)},Vs.prototype.webglContextRestored=function(){this._program=null},Vs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene.canvas.gl,n=t._material._state,i=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),n.id!==this._lastMaterialId){const t=n.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=n.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),e.lineWidth!==n.lineWidth&&(s.lineWidth(n.lineWidth),e.lineWidth=n.lineWidth),this._uPointSize&&s.uniform1i(this._uPointSize,n.pointSize),this._lastMaterialId=n.id}if(s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),i.combineGeometry){const n=t.vertexBufs;n.id!==this._lastVertexBufsId&&(n.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(n.positionsBuf,n.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),this._lastVertexBufsId=n.id)}this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),i.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,i.positionsDecodeMatrix),i.combineGeometry?i.indicesBufCombined&&(i.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(i.positionsBuf,i.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),i.indicesBuf&&(i.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=i.id),i.combineGeometry?i.indicesBufCombined&&(s.drawElements(i.primitive,i.indicesBufCombined.numItems,i.indicesBufCombined.itemType,0),e.drawElements++):i.indicesBuf?(s.drawElements(i.primitive,i.indicesBuf.numItems,i.indicesBuf.itemType,0),e.drawElements++):i.positions&&(s.drawArrays(s.TRIANGLES,0,i.positions.numItems),e.drawArrays++)},Vs.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new we(s,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uShadowViewMatrix=n.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=n.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._uClippable=n.getLocation("clippable"),this._uOffset=n.getLocation("offset"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Vs.prototype._bindProgram=function(e){this._program||this._allocate(mesh);const t=this._scene,s=t.canvas.gl,n=t._sectionPlanesState;if(this._program.bind(),e.useProgram++,s.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),s.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,n.sectionPlanes.length>0){let e,t,i,a,r;for(let l=0,o=this._uSectionPlanes.length;l<o;l++)e=this._uSectionPlanes[l],t=e.active,i=n.sectionPlanes[l],t&&s.uniform1i(t,i.active),a=e.pos,a&&s.uniform3fv(e.pos,i.pos),r=e.dir,r&&s.uniform3fv(e.dir,i.dir)}};class ks{constructor(){this.visibleLayers=[],this.sectionPlanesActivePerLayer=[],this.reset()}reset(){this.culled=!1,this.sectioned=!1,this.numLayers=0,this.numVisibleLayers=0,this.colorOpaque=!1,this.colorTransparent=!1,this.edgesOpaque=!1,this.edgesTransparent=!1,this.xrayedSilhouetteOpaque=!1,this.xrayedEdgesOpaque=!1,this.xrayedSilhouetteTransparent=!1,this.xrayedEdgesTransparent=!1,this.highlightedSilhouetteOpaque=!1,this.highlightedEdgesOpaque=!1,this.highlightedSilhouetteTransparent=!1,this.highlightedEdgesTransparent=!1,this.selectedSilhouetteOpaque=!1,this.selectedEdgesOpaque=!1,this.selectedSilhouetteTransparent=!1,this.selectedEdgesTransparent=!1}}const Qs=h.OBB3(),Ws=h.vec4(),zs=h.vec4(),Ks=h.vec4(),Ys=h.vec3([1,0,0]),Xs=h.vec3([0,1,0]),qs=h.vec3([0,0,1]),Js=h.vec3(3),Zs=h.vec3(3),$s=h.identityMat4();class en extends C{constructor(e,t={}){super(e,t),this.originalSystemId=t.originalSystemId||this.id,this.renderFlags=new ks,this._state=new Ve({visible:!0,culled:!1,pickable:null,clippable:null,collidable:null,occluder:!1!==t.occluder,castsShadow:null,receivesShadow:null,xrayed:!1,highlighted:!1,selected:!1,edges:!1,stationary:!!t.stationary,background:!!t.background,billboard:this._checkBillboard(t.billboard),layer:null,colorize:null,pickID:this.scene._renderer.getPickID(this),drawHash:"",pickHash:"",offset:h.vec3(),origin:null,originHash:null}),this._drawRenderer=null,this._shadowRenderer=null,this._emphasisFillRenderer=null,this._emphasisEdgesRenderer=null,this._pickMeshRenderer=null,this._pickTriangleRenderer=null,this._occlusionRenderer=null,this._geometry=t.geometry?this._checkComponent2(["ReadableGeometry","VBOGeometry"],t.geometry):this.scene.geometry,this._material=t.material?this._checkComponent2(["PhongMaterial","MetallicMaterial","SpecularMaterial","LambertMaterial"],t.material):this.scene.material,this._xrayMaterial=t.xrayMaterial?this._checkComponent("EmphasisMaterial",t.xrayMaterial):this.scene.xrayMaterial,this._highlightMaterial=t.highlightMaterial?this._checkComponent("EmphasisMaterial",t.highlightMaterial):this.scene.highlightMaterial,this._selectedMaterial=t.selectedMaterial?this._checkComponent("EmphasisMaterial",t.selectedMaterial):this.scene.selectedMaterial,this._edgeMaterial=t.edgeMaterial?this._checkComponent("EdgeMaterial",t.edgeMaterial):this.scene.edgeMaterial,this._parentNode=null,this._aabb=null,this._aabbDirty=!0,this._numTriangles=this._geometry?this._geometry.numTriangles:0,this.scene._aabbDirty=!0,this._scale=h.vec3(),this._quaternion=h.identityQuaternion(),this._rotation=h.vec3(),this._position=h.vec3(),this._worldMatrix=h.identityMat4(),this._worldNormalMatrix=h.identityMat4(),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0;const s=t.origin||t.rtcCenter;if(s&&(this._state.origin=h.vec3(s),this._state.originHash=s.join()),t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),this._isObject=t.isObject,this._isObject&&this.scene._registerObject(this),this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.layer=t.layer,this.colorize=t.colorize,this.opacity=t.opacity,this.offset=t.offset,t.parentId){const e=this.scene.components[t.parentId];e?e.isNode?e.addChild(this):this.error("Parent is not a Node: '"+t.parentId+"'"):this.error("Parent not found: '"+t.parentId+"'"),this._parentNode=e}else t.parent&&(t.parent.isNode||this.error("Parent is not a Node"),t.parent.addChild(this),this._parentNode=t.parent);this.compile()}get type(){return"Mesh"}get isMesh(){return!0}get parent(){return this._parentNode}get geometry(){return this._geometry}get material(){return this._material}get position(){return this._position}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set rotation(e){this._rotation.set(e||[0,0,0]),h.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),h.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get scale(){return this._scale}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get matrix(){return this._localMatrixDirty&&(this.__localMatrix||(this.__localMatrix=h.identityMat4()),h.composeMat4(this._position,this._quaternion,this._scale,this.__localMatrix),this._localMatrixDirty=!1),this.__localMatrix}set matrix(e){this.__localMatrix||(this.__localMatrix=h.identityMat4()),this.__localMatrix.set(e||$s),h.decomposeMat4(this.__localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}get worldNormalMatrix(){return this._worldNormalMatrixDirty&&this._buildWorldNormalMatrix(),this._worldNormalMatrix}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return this._isObject}get aabb(){return this._aabbDirty&&this._updateAABB(),this._aabb}get origin(){return this._state.origin}set origin(e){e?(this._state.origin||(this._state.origin=h.vec3()),this._state.origin.set(e),this._state.originHash=e.join(),this._setAABBDirty(),this.scene._aabbDirty=!0):this._state.origin&&(this._state.origin=null,this._state.originHash=null,this._setAABBDirty(),this.scene._aabbDirty=!0)}get rtcCenter(){return this.origin}set rtcCenter(e){this.origin=e}get numTriangles(){return this._numTriangles}get visible(){return this._state.visible}set visible(e){e=!1!==e,this._state.visible=e,this._isObject&&this.scene._objectVisibilityUpdated(this,e),this.glRedraw()}get xrayed(){return this._state.xrayed}set xrayed(e){e=!!e,this._state.xrayed!==e&&(this._state.xrayed=e,this._isObject&&this.scene._objectXRayedUpdated(this,e),this.glRedraw())}get highlighted(){return this._state.highlighted}set highlighted(e){(e=!!e)!==this._state.highlighted&&(this._state.highlighted=e,this._isObject&&this.scene._objectHighlightedUpdated(this,e),this.glRedraw())}get selected(){return this._state.selected}set selected(e){(e=!!e)!==this._state.selected&&(this._state.selected=e,this._isObject&&this.scene._objectSelectedUpdated(this,e),this.glRedraw())}get edges(){return this._state.edges}set edges(e){(e=!!e)!==this._state.edges&&(this._state.edges=e,this.glRedraw())}get culled(){return this._state.culled}set culled(e){this._state.culled=!!e,this.glRedraw()}get clippable(){return this._state.clippable}set clippable(e){e=!1!==e,this._state.clippable!==e&&(this._state.clippable=e,this.glRedraw())}get collidable(){return this._state.collidable}set collidable(e){(e=!1!==e)!==this._state.collidable&&(this._state.collidable=e,this._setAABBDirty(),this.scene._aabbDirty=!0)}get pickable(){return this._state.pickable}set pickable(e){e=!1!==e,this._state.pickable!==e&&(this._state.pickable=e)}get castsShadow(){return this._state.castsShadow}set castsShadow(e){(e=!1!==e)!==this._state.castsShadow&&(this._state.castsShadow=e,this.glRedraw())}get receivesShadow(){return this._state.receivesShadow}set receivesShadow(e){(e=!1!==e)!==this._state.receivesShadow&&(this._state.receivesShadow=e,this._state.hash=e?"/mod/rs;":"/mod;",this.fire("dirty",this))}get saoEnabled(){return!1}get colorize(){return this._state.colorize}set colorize(e){let t=this._state.colorize;t||(t=this._state.colorize=new Float32Array(4),t[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);const s=!!e;this.scene._objectColorizeUpdated(this,s),this.glRedraw()}get opacity(){return this._state.colorize[3]}set opacity(e){let t=this._state.colorize;t||(t=this._state.colorize=new Float32Array(4),t[0]=1,t[1]=1,t[2]=1);const s=null!=e;t[3]=s?e:1,this.scene._objectOpacityUpdated(this,s),this.glRedraw()}get transparent(){return 2===this._material.alphaMode||this._state.colorize[3]<1}get layer(){return this._state.layer}set layer(e){e=e||0,(e=Math.round(e))!==this._state.layer&&(this._state.layer=e,this._renderer.needStateSort())}get stationary(){return this._state.stationary}get billboard(){return this._state.billboard}get offset(){return this._state.offset}set offset(e){this._state.offset.set(e||[0,0,0]),this._setAABBDirty(),this.glRedraw()}get isDrawable(){return!0}get isStateSortable(){return!0}get xrayMaterial(){return this._xrayMaterial}get highlightMaterial(){return this._highlightMaterial}get selectedMaterial(){return this._selectedMaterial}get edgeMaterial(){return this._edgeMaterial}_checkBillboard(e){return"spherical"!==(e=e||"none")&&"cylindrical"!==e&&"none"!==e&&(this.error("Unsupported value for 'billboard': "+e+" - accepted values are 'spherical', 'cylindrical' and 'none' - defaulting to 'none'."),e="none"),e}compile(){const e=this._makeDrawHash();this._state.drawHash!==e&&(this._state.drawHash=e,this._putDrawRenderers(),this._drawRenderer=Is.get(this),this._emphasisFillRenderer=gs.get(this),this._emphasisEdgesRenderer=Ps.get(this));const t=this._makePickHash();if(this._state.pickHash!==t&&(this._state.pickHash=t,this._putPickRenderers(),this._pickMeshRenderer=Bs.get(this)),this._state.occluder){const e=this._makeOcclusionHash();this._state.occlusionHash!==e&&(this._state.occlusionHash=e,this._putOcclusionRenderer(),this._occlusionRenderer=Hs.get(this))}}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}_setWorldMatrixDirty(){this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0}_buildWorldMatrix(){const e=this.matrix;if(this._parentNode)h.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(let t=0,s=e.length;t<s;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_buildWorldNormalMatrix(){this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldNormalMatrix||(this._worldNormalMatrix=h.mat4()),h.transposeMat4(this._worldMatrix,this._worldNormalMatrix),h.inverseMat4(this._worldNormalMatrix),this._worldNormalMatrixDirty=!1}_setAABBDirty(){if(this.collidable)for(let e=this;e;e=e._parentNode)e._aabbDirty=!0}_updateAABB(){this.scene._aabbDirty=!0,this._aabb||(this._aabb=h.AABB3()),this._buildAABB(this.worldMatrix,this._aabb),this._aabbDirty=!1}_webglContextRestored(){this._drawRenderer&&this._drawRenderer.webglContextRestored(),this._shadowRenderer&&this._shadowRenderer.webglContextRestored(),this._emphasisFillRenderer&&this._emphasisFillRenderer.webglContextRestored(),this._emphasisEdgesRenderer&&this._emphasisEdgesRenderer.webglContextRestored(),this._pickMeshRenderer&&this._pickMeshRenderer.webglContextRestored(),this._pickTriangleRenderer&&this._pickMeshRenderer.webglContextRestored(),this._occlusionRenderer&&this._occlusionRenderer.webglContextRestored()}_makeDrawHash(){const e=this.scene,t=[e.canvas.canvas.id,(e.gammaInput?"gi;":";")+(e.gammaOutput?"go":""),e._lightsState.getHash(),e._sectionPlanesState.getHash()],s=this._state;return s.stationary&&t.push("/s"),"none"===s.billboard?t.push("/n"):"spherical"===s.billboard?t.push("/s"):"cylindrical"===s.billboard&&t.push("/c"),s.receivesShadow&&t.push("/rs"),t.push(";"),t.join("")}_makePickHash(){const e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],s=this._state;return s.stationary&&t.push("/s"),"none"===s.billboard?t.push("/n"):"spherical"===s.billboard?t.push("/s"):"cylindrical"===s.billboard&&t.push("/c"),t.push(";"),t.join("")}_makeOcclusionHash(){const e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],s=this._state;return s.stationary&&t.push("/s"),"none"===s.billboard?t.push("/n"):"spherical"===s.billboard?t.push("/s"):"cylindrical"===s.billboard&&t.push("/c"),t.push(";"),t.join("")}_buildAABB(e,t){h.transformOBB3(e,this._geometry.obb,Qs),h.OBB3ToAABB3(Qs,t);const s=this._state.offset;if(t[0]+=s[0],t[1]+=s[1],t[2]+=s[2],t[3]+=s[0],t[4]+=s[1],t[5]+=s[2],this._state.origin){const e=this._state.origin;t[0]+=e[0],t[1]+=e[1],t[2]+=e[2],t[3]+=e[0],t[4]+=e[1],t[5]+=e[2]}}rotate(e,t){return Ws[0]=e[0],Ws[1]=e[1],Ws[2]=e[2],Ws[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Ws,zs),h.mulQuaternions(this.quaternion,zs,Ks),this.quaternion=Ks,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return Ws[0]=e[0],Ws[1]=e[1],Ws[2]=e[2],Ws[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Ws,zs),h.mulQuaternions(zs,this.quaternion,zs),this}rotateX(e){return this.rotate(Ys,e)}rotateY(e){return this.rotate(Xs,e)}rotateZ(e){return this.rotate(qs,e)}translate(e,t){return h.vec3ApplyQuaternion(this.quaternion,e,Js),h.mulVec3Scalar(Js,t,Zs),h.addVec3(this.position,Zs,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(Ys,e)}translateY(e){return this.translate(Xs,e)}translateZ(e){return this.translate(qs,e)}_putDrawRenderers(){this._drawRenderer&&(this._drawRenderer.put(),this._drawRenderer=null),this._shadowRenderer&&(this._shadowRenderer.put(),this._shadowRenderer=null),this._emphasisFillRenderer&&(this._emphasisFillRenderer.put(),this._emphasisFillRenderer=null),this._emphasisEdgesRenderer&&(this._emphasisEdgesRenderer.put(),this._emphasisEdgesRenderer=null)}_putPickRenderers(){this._pickMeshRenderer&&(this._pickMeshRenderer.put(),this._pickMeshRenderer=null),this._pickTriangleRenderer&&(this._pickTriangleRenderer.put(),this._pickTriangleRenderer=null)}_putOcclusionRenderer(){this._occlusionRenderer&&(this._occlusionRenderer.put(),this._occlusionRenderer=null)}stateSortCompare(e,t){return e._state.layer-t._state.layer||e._drawRenderer.id-t._drawRenderer.id||e._material._state.id-t._material._state.id||e._geometry._state.id-t._geometry._state.id}rebuildRenderFlags(){this.renderFlags.reset(),this._getActiveSectionPlanes()?(this.renderFlags.numLayers=1,this.renderFlags.numVisibleLayers=1,this.renderFlags.visibleLayers[0]=0,this._updateRenderFlags()):this.renderFlags.culled=!0}_updateRenderFlags(){const e=this.renderFlags,t=this._state;if(t.xrayed){const t=this._xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}else{if(this._material._state.alpha<1||t.colorize[3]<1?e.colorTransparent=!0:e.colorOpaque=!0,t.edges){this._edgeMaterial._state.alpha<1?e.edgesTransparent=!0:e.edgesOpaque=!0}if(t.selected){const t=this._selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}else if(t.highlighted){const t=this._highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}}_getActiveSectionPlanes(){if(this._state.clippable){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let s=0;s<t;s++){const t=e[s],n=this.renderFlags;if(t.active)if(this._state.origin){const e=h.planeAABB3Intersect(t.dir,t.dist,this.aabb);if(-1===e)return!1;const i=0===e;n.sectionPlanesActivePerLayer[s]=i}else n.sectionPlanesActivePerLayer[s]=!0;else n.sectionPlanesActivePerLayer[s]=!1}}return!0}drawColorOpaque(e){(this._drawRenderer||(this._drawRenderer=Is.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawColorTransparent(e){(this._drawRenderer||(this._drawRenderer=Is.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawSilhouetteXRayed(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=gs.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,0)}drawSilhouetteHighlighted(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=gs.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,1)}drawSilhouetteSelected(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=gs.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,2)}drawEdgesColorOpaque(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Ps.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawEdgesColorTransparent(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Ps.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawEdgesXRayed(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Ps.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,0)}drawEdgesHighlighted(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Ps.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,1)}drawEdgesSelected(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Ps.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,2)}drawOcclusion(e){(this._state.occluder&&this._occlusionRenderer||(this._occlusionRenderer=Hs.get(this)))&&this._occlusionRenderer.drawMesh(e,this)}drawShadow(e){(this._shadowRenderer||(this._shadowRenderer=Vs.get(this)))&&this._shadowRenderer.drawMesh(e,this)}drawPickMesh(e){(this._pickMeshRenderer||(this._pickMeshRenderer=Bs.get(this)))&&this._pickMeshRenderer.drawMesh(e,this)}canPickTriangle(){return this._geometry.isReadableGeometry}drawPickTriangles(e){(this._pickTriangleRenderer||(this._pickTriangleRenderer=xs.get(this)))&&this._pickTriangleRenderer.drawMesh(e,this)}pickTriangleSurface(e,t,s){tn(this,e,t,s)}drawPickVertices(e){}delegatePickedEntity(){return this}destroy(){super.destroy(),this._putDrawRenderers(),this._putPickRenderers(),this._putOcclusionRenderer(),this.scene._renderer.putPickID(this._state.pickID),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const tn=function(){const e=h.vec3(),t=h.vec3(),s=h.vec3(),n=h.vec3(),i=h.vec3(),a=h.vec3(),r=h.vec4(),l=h.vec3(),o=h.vec3(),c=h.vec3(),u=h.vec3(),p=h.vec3(),A=h.vec3(),d=h.vec3(),f=h.vec3(),I=h.vec3(),y=h.vec4(),m=h.vec4(),v=h.vec4(),w=h.vec3(),g=h.vec3(),T=h.vec3(),E=h.vec3(),b=h.vec3(),D=h.vec3(),P=h.vec3(),R=h.vec3(),C=h.vec3(),_=h.vec3(),O=h.vec3();return function(S,N,x,L){var M=L.primIndex;if(null!=M&&M>-1){const G=S.geometry._state,V=S.scene,j=V.camera,k=V.canvas;if("triangles"===G.primitiveName){L.primitive="triangle";const V=M,Q=G.indices,W=G.positions;let z,K,Y;if(Q){var F=Q[V+0],H=Q[V+1],U=Q[V+2];a[0]=F,a[1]=H,a[2]=U,L.indices=a,z=3*F,K=3*H,Y=3*U}else z=3*V,K=z+3,Y=K+3;if(s[0]=W[z+0],s[1]=W[z+1],s[2]=W[z+2],n[0]=W[K+0],n[1]=W[K+1],n[2]=W[K+2],i[0]=W[Y+0],i[1]=W[Y+1],i[2]=W[Y+2],G.compressGeometry){const e=G.positionsDecodeMatrix;e&&(wt.decompressPosition(s,e,s),wt.decompressPosition(n,e,n),wt.decompressPosition(i,e,i))}L.canvasPos?h.canvasPosToLocalRay(k.canvas,S.origin?B(N,S.origin):N,x,S.worldMatrix,L.canvasPos,e,t):L.origin&&L.direction&&h.worldRayToLocalRay(S.worldMatrix,L.origin,L.direction,e,t),h.normalizeVec3(t),h.rayPlaneIntersect(e,t,s,n,i,r),L.localPos=r,L.position=r,y[0]=r[0],y[1]=r[1],y[2]=r[2],y[3]=1,h.transformVec4(S.worldMatrix,y,m),l[0]=m[0],l[1]=m[1],l[2]=m[2],L.canvasPos&&S.origin&&(l[0]+=S.origin[0],l[1]+=S.origin[1],l[2]+=S.origin[2]),L.worldPos=l,h.transformVec4(j.matrix,m,v),o[0]=v[0],o[1]=v[1],o[2]=v[2],L.viewPos=o,h.cartesianToBarycentric(r,s,n,i,c),L.bary=c;const X=G.normals;if(X){if(G.compressGeometry){const e=3*F,t=3*H,s=3*U;wt.decompressNormal(X.subarray(e,e+2),u),wt.decompressNormal(X.subarray(t,t+2),p),wt.decompressNormal(X.subarray(s,s+2),A)}else u[0]=X[z],u[1]=X[z+1],u[2]=X[z+2],p[0]=X[K],p[1]=X[K+1],p[2]=X[K+2],A[0]=X[Y],A[1]=X[Y+1],A[2]=X[Y+2];const e=h.addVec3(h.addVec3(h.mulVec3Scalar(u,c[0],w),h.mulVec3Scalar(p,c[1],g),T),h.mulVec3Scalar(A,c[2],E),b);L.worldNormal=h.normalizeVec3(h.transformVec3(S.worldNormalMatrix,e,D))}const q=G.uv;if(q){if(d[0]=q[2*F],d[1]=q[2*F+1],f[0]=q[2*H],f[1]=q[2*H+1],I[0]=q[2*U],I[1]=q[2*U+1],G.compressGeometry){const e=G.uvDecodeMatrix;e&&(wt.decompressUV(d,e,d),wt.decompressUV(f,e,f),wt.decompressUV(I,e,I))}L.uv=h.addVec3(h.addVec3(h.mulVec2Scalar(d,c[0],P),h.mulVec2Scalar(f,c[1],R),C),h.mulVec2Scalar(I,c[2],_),O)}}}}}();function sn(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let s=e.radiusBottom||1;s<0&&(console.error("negative radiusBottom not allowed - will invert"),s*=-1);let n=e.height||1;n<0&&(console.error("negative height not allowed - will invert"),n*=-1);let i=e.radialSegments||32;i<0&&(console.error("negative radialSegments not allowed - will invert"),i*=-1),i<3&&(i=3);let a=e.heightSegments||1;a<0&&(console.error("negative heightSegments not allowed - will invert"),a*=-1),a<1&&(a=1);const r=!!e.openEnded;let l=e.center;const o=l?l[0]:0,c=l?l[1]:0,u=l?l[2]:0,h=n/2,p=n/a,A=2*Math.PI/i,d=1/i,f=(t-s)/a,I=[],m=[],v=[],w=[];let g,T,E,b,D,P,R,C,_,B,O;const S=(90-180*Math.atan(n/(s-t))/Math.PI)/90;for(g=0;g<=a;g++)for(D=t-g*f,P=h-g*p,T=0;T<=i;T++)E=Math.sin(T*A),b=Math.cos(T*A),m.push(D*E),m.push(S),m.push(D*b),v.push(T*d),v.push(1*g/a),I.push(D*E+o),I.push(P+c),I.push(D*b+u);for(g=0;g<a;g++)for(T=0;T<=i;T++)R=g*(i+1)+T,C=R+i,w.push(R),w.push(C),w.push(C+1),w.push(R),w.push(C+1),w.push(R+1);if(!r&&t>0){for(_=I.length/3,m.push(0),m.push(1),m.push(0),v.push(.5),v.push(.5),I.push(0+o),I.push(h+c),I.push(0+u),T=0;T<=i;T++)E=Math.sin(T*A),b=Math.cos(T*A),B=.5*Math.sin(T*A)+.5,O=.5*Math.cos(T*A)+.5,m.push(t*E),m.push(1),m.push(t*b),v.push(B),v.push(O),I.push(t*E+o),I.push(h+c),I.push(t*b+u);for(T=0;T<i;T++)l=_,R=_+1+T,w.push(R),w.push(R+1),w.push(l)}if(!r&&s>0){for(_=I.length/3,m.push(0),m.push(-1),m.push(0),v.push(.5),v.push(.5),I.push(0+o),I.push(0-h+c),I.push(0+u),T=0;T<=i;T++)E=Math.sin(T*A),b=Math.cos(T*A),B=.5*Math.sin(T*A)+.5,O=.5*Math.cos(T*A)+.5,m.push(s*E),m.push(-1),m.push(s*b),v.push(B),v.push(O),I.push(s*E+o),I.push(0-h+c),I.push(s*b+u);for(T=0;T<i;T++)l=_,R=_+1+T,w.push(l),w.push(R+1),w.push(R)}return y.apply(e,{positions:I,normals:m,uv:v,indices:w})}function nn(e={}){const t=e.lod||1,s=e.center?e.center[0]:0,n=e.center?e.center[1]:0,i=e.center?e.center[2]:0;let a=e.radius||1;a<0&&(console.error("negative radius not allowed - will invert"),a*=-1);let r=e.heightSegments||18;r<0&&(console.error("negative heightSegments not allowed - will invert"),r*=-1),r=Math.floor(t*r),r<18&&(r=18);let l=e.widthSegments||18;l<0&&(console.error("negative widthSegments not allowed - will invert"),l*=-1),l=Math.floor(t*l),l<18&&(l=18);const o=[],c=[],u=[],h=[];let p,A,d,f,I,m,v,w,g,T,E,b,D,P,R;for(p=0;p<=r;p++)for(d=p*Math.PI/r,f=Math.sin(d),I=Math.cos(d),A=0;A<=l;A++)m=2*A*Math.PI/l,v=Math.sin(m),w=Math.cos(m),g=w*f,T=I,E=v*f,b=1-A/l,D=p/r,c.push(g),c.push(T),c.push(E),u.push(b),u.push(D),o.push(s+a*g),o.push(n+a*T),o.push(i+a*E);for(p=0;p<r;p++)for(A=0;A<l;A++)P=p*(l+1)+A,R=P+l+1,h.push(P+1),h.push(R+1),h.push(R),h.push(P+1),h.push(R),h.push(P);return y.apply(e,{positions:o,normals:c,uv:u,indices:h})}const an={" ":{width:16,points:[]},"!":{width:10,points:[[5,21],[5,7],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]]},'"':{width:16,points:[[4,21],[4,14],[-1,-1],[12,21],[12,14]]},"#":{width:21,points:[[11,25],[4,-7],[-1,-1],[17,25],[10,-7],[-1,-1],[4,12],[18,12],[-1,-1],[3,6],[17,6]]},$:{width:20,points:[[8,25],[8,-4],[-1,-1],[12,25],[12,-4],[-1,-1],[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},"%":{width:24,points:[[21,21],[3,0],[-1,-1],[8,21],[10,19],[10,17],[9,15],[7,14],[5,14],[3,16],[3,18],[4,20],[6,21],[8,21],[10,20],[13,19],[16,19],[19,20],[21,21],[-1,-1],[17,7],[15,6],[14,4],[14,2],[16,0],[18,0],[20,1],[21,3],[21,5],[19,7],[17,7]]},"&":{width:26,points:[[23,12],[23,13],[22,14],[21,14],[20,13],[19,11],[17,6],[15,3],[13,1],[11,0],[7,0],[5,1],[4,2],[3,4],[3,6],[4,8],[5,9],[12,13],[13,14],[14,16],[14,18],[13,20],[11,21],[9,20],[8,18],[8,16],[9,13],[11,10],[16,3],[18,1],[20,0],[22,0],[23,1],[23,2]]},"'":{width:10,points:[[5,19],[4,20],[5,21],[6,20],[6,18],[5,16],[4,15]]},"(":{width:14,points:[[11,25],[9,23],[7,20],[5,16],[4,11],[4,7],[5,2],[7,-2],[9,-5],[11,-7]]},")":{width:14,points:[[3,25],[5,23],[7,20],[9,16],[10,11],[10,7],[9,2],[7,-2],[5,-5],[3,-7]]},"*":{width:16,points:[[8,21],[8,9],[-1,-1],[3,18],[13,12],[-1,-1],[13,18],[3,12]]},"+":{width:26,points:[[13,18],[13,0],[-1,-1],[4,9],[22,9]]},",":{width:10,points:[[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"-":{width:26,points:[[4,9],[22,9]]},".":{width:10,points:[[5,2],[4,1],[5,0],[6,1],[5,2]]},"/":{width:22,points:[[20,25],[2,-7]]},0:{width:20,points:[[9,21],[6,20],[4,17],[3,12],[3,9],[4,4],[6,1],[9,0],[11,0],[14,1],[16,4],[17,9],[17,12],[16,17],[14,20],[11,21],[9,21]]},1:{width:20,points:[[6,17],[8,18],[11,21],[11,0]]},2:{width:20,points:[[4,16],[4,17],[5,19],[6,20],[8,21],[12,21],[14,20],[15,19],[16,17],[16,15],[15,13],[13,10],[3,0],[17,0]]},3:{width:20,points:[[5,21],[16,21],[10,13],[13,13],[15,12],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},4:{width:20,points:[[13,21],[3,7],[18,7],[-1,-1],[13,21],[13,0]]},5:{width:20,points:[[15,21],[5,21],[4,12],[5,13],[8,14],[11,14],[14,13],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},6:{width:20,points:[[16,18],[15,20],[12,21],[10,21],[7,20],[5,17],[4,12],[4,7],[5,3],[7,1],[10,0],[11,0],[14,1],[16,3],[17,6],[17,7],[16,10],[14,12],[11,13],[10,13],[7,12],[5,10],[4,7]]},7:{width:20,points:[[17,21],[7,0],[-1,-1],[3,21],[17,21]]},8:{width:20,points:[[8,21],[5,20],[4,18],[4,16],[5,14],[7,13],[11,12],[14,11],[16,9],[17,7],[17,4],[16,2],[15,1],[12,0],[8,0],[5,1],[4,2],[3,4],[3,7],[4,9],[6,11],[9,12],[13,13],[15,14],[16,16],[16,18],[15,20],[12,21],[8,21]]},9:{width:20,points:[[16,14],[15,11],[13,9],[10,8],[9,8],[6,9],[4,11],[3,14],[3,15],[4,18],[6,20],[9,21],[10,21],[13,20],[15,18],[16,14],[16,9],[15,4],[13,1],[10,0],[8,0],[5,1],[4,3]]},":":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]]},";":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"<":{width:24,points:[[20,18],[4,9],[20,0]]},"=":{width:26,points:[[4,12],[22,12],[-1,-1],[4,6],[22,6]]},">":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function rn(e={}){var t=e.origin||[0,0,0],s=t[0],n=t[1],i=t[2],a=e.size||1,r=[],l=[],o=e.text;y.isNumeric(o)&&(o=""+o);for(var c,u,h,p,A,d,f,I,m,v=(o||"").split("\n"),w=0,g=0,T=.04,E=0;E<v.length;E++){c=0,h=(u=v[E]).length;for(var b=0;b<h;b++)if(p=an[u.charAt(b)]){A=1,d=-1,f=-1,I=p.points.length;for(var D=0;D<I;D++)-1!==(m=p.points[D])[0]||-1!==m[1]?(r.push(c+m[0]*a*T+s),r.push(g+m[1]*a*T+n),r.push(0+i),-1===d?d=w:(-1===f||(d=f),f=w),w++,A?A=!1:(l.push(d),l.push(f))):A=1;c+=p.width*T*a}g-=35*T*a}return y.apply(e,{primitive:"lines",positions:r,indices:l})}class ln extends C{get type(){return"SectionPlane"}constructor(e,t={}){super(e,t),this._state=new Ve({active:!0,pos:h.vec3(),dir:h.vec3(),dist:0}),this.active=t.active,this.pos=t.pos,this.dir=t.dir,this.scene._sectionPlaneCreated(this)}set active(e){this._state.active=!1!==e,this.glRedraw(),this.fire("active",this._state.active)}get active(){return this._state.active}set pos(e){this._state.pos.set(e||[0,0,0]),this._state.dist=-h.dotVec3(this._state.pos,this._state.dir),this.fire("pos",this._state.pos)}get pos(){return this._state.pos}set dir(e){this._state.dir.set(e||[0,0,-1]),this._state.dist=-h.dotVec3(this._state.pos,this._state.dir),this.glRedraw(),this.fire("dir",this._state.dir)}get dir(){return this._state.dir}get dist(){return this._state.dist}flipDir(){const e=this._state.dir;e[0]*=-1,e[1]*=-1,e[2]*=-1,this._state.dist=-h.dotVec3(this._state.pos,this._state.dir),this.fire("dir",this._state.dir),this.glRedraw()}destroy(){this._state.destroy(),this.scene._sectionPlaneDestroyed(this),super.destroy()}}const on=h.vec4(4),cn=h.vec4(),un=h.vec4(),hn=h.vec3([1,0,0]),pn=h.vec3([0,1,0]),An=h.vec3([0,0,1]),dn=h.vec3(3),fn=h.vec3(3),In=h.identityMat4();class yn extends C{constructor(e,t={}){if(super(e,t),this._parentNode=null,this._children=[],this._aabb=null,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._numTriangles=0,this._scale=h.vec3(),this._quaternion=h.identityQuaternion(),this._rotation=h.vec3(),this._position=h.vec3(),this._offset=h.vec3(),this._localMatrix=h.identityMat4(),this._worldMatrix=h.identityMat4(),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._isObject=t.isObject,this._isObject&&this.scene._registerObject(this),this.origin=t.origin,this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.offset=t.offset,t.children){const e=t.children;for(let s=0,n=e.length;s<n;s++)this.addChild(e[s],t.inheritStates)}if(t.parentId){const e=this.scene.components[t.parentId];e?e.isNode?e.addChild(this):this.error("Parent is not a Node: '"+t.parentId+"'"):this.error("Parent not found: '"+t.parentId+"'")}else t.parent&&(t.parent.isNode||this.error("Parent is not a Node"),t.parent.addChild(this))}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return this._isObject}get aabb(){return this._aabbDirty&&this._updateAABB(),this._aabb}set origin(e){e?(this._origin||(this._origin=h.vec3()),this._origin.set(e)):this._origin&&(this._origin=null);for(let t=0,s=this._children.length;t<s;t++)this._children[t].origin=e;this.glRedraw()}get origin(){return this._origin}set rtcCenter(e){this.origin=e}get rtcCenter(){return this.origin}get numTriangles(){return this._numTriangles}set visible(e){e=!1!==e,this._visible=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].visible=e;this._isObject&&this.scene._objectVisibilityUpdated(this,e)}get visible(){return this._visible}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].xrayed=e;this._isObject&&this.scene._objectXRayedUpdated(this,e)}get xrayed(){return this._xrayed}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].highlighted=e;this._isObject&&this.scene._objectHighlightedUpdated(this,e)}get highlighted(){return this._highlighted}set selected(e){e=!!e,this._selected=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].selected=e;this._isObject&&this.scene._objectSelectedUpdated(this,e)}get selected(){return this._selected}set edges(e){e=!!e,this._edges=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].edges=e}get edges(){return this._edges}set culled(e){e=!!e,this._culled=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].culled=e}get culled(){return this._culled}set clippable(e){e=!1!==e,this._clippable=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].clippable=e}get clippable(){return this._clippable}set collidable(e){e=!1!==e,this._collidable=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].collidable=e}get collidable(){return this._collidable}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].pickable=e}get pickable(){return this._pickable}set colorize(e){let t=this._colorize;t||(t=this._colorize=new Float32Array(4),t[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);for(let e=0,s=this._children.length;e<s;e++)this._children[e].colorize=t;if(this._isObject){const t=!!e;this.scene._objectColorizeUpdated(this,t)}}get colorize(){return this._colorize.slice(0,3)}set opacity(e){let t=this._colorize;t||(t=this._colorize=new Float32Array(4),t[0]=1,t[1]=1,t[2]=1),t[3]=null!=e?e:1;for(let t=0,s=this._children.length;t<s;t++)this._children[t].opacity=e;if(this._isObject){const t=null!=e;this.scene._objectOpacityUpdated(this,t)}}get opacity(){return this._colorize[3]}set castsShadow(e){e=!!e,this._castsShadow=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].castsShadow=e}get castsShadow(){return this._castsShadow}set receivesShadow(e){e=!!e,this._receivesShadow=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].receivesShadow=e}get receivesShadow(){return this._receivesShadow}get saoEnabled(){return!1}set offset(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(let e=0,t=this._children.length;e<t;e++)this._children[e].offset=this._offset;this._isObject&&this.scene._objectOffsetUpdated(this,e)}get offset(){return this._offset}get isNode(){return!0}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}_setWorldMatrixDirty(){this._worldMatrixDirty=!0;for(let e=0,t=this._children.length;e<t;e++)this._children[e]._setWorldMatrixDirty()}_buildWorldMatrix(){const e=this.matrix;if(this._parentNode)h.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(let t=0,s=e.length;t<s;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_setSubtreeAABBsDirty(e){if(e._aabbDirty=!0,e._children)for(let t=0,s=e._children.length;t<s;t++)this._setSubtreeAABBsDirty(e._children[t])}_setAABBDirty(){if(this._setSubtreeAABBsDirty(this),this.collidable)for(let e=this;e;e=e._parentNode)e._aabbDirty=!0}_updateAABB(){if(this.scene._aabbDirty=!0,this._aabb||(this._aabb=h.AABB3()),this._buildAABB)this._buildAABB(this.worldMatrix,this._aabb);else{let e;h.collapseAABB3(this._aabb);for(let t=0,s=this._children.length;t<s;t++)e=this._children[t],e.collidable&&h.expandAABB3(this._aabb,e.aabb)}this._aabbDirty=!1}addChild(e,t){if(y.isNumeric(e)||y.isString(e)){const t=e;if(!(e=this.scene.component[t]))return void this.warn("Component not found: "+y.inQuotes(t));if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+t)}else{if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+e.id);if(e._parentNode){if(e._parentNode.id===this.id)return void this.warn("Already a child: "+e.id);e._parentNode.removeChild(e)}}if(e.id,e.scene.id===this.scene.id)return this._children.push(e),e._parentNode=this,t&&(e.visible=this.visible,e.culled=this.culled,e.xrayed=this.xrayed,e.highlited=this.highlighted,e.selected=this.selected,e.edges=this.edges,e.clippable=this.clippable,e.pickable=this.pickable,e.collidable=this.collidable,e.castsShadow=this.castsShadow,e.receivesShadow=this.receivesShadow,e.colorize=this.colorize,e.opacity=this.opacity,e.offset=this.offset),e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles+=e.numTriangles,e;this.error("Child not in same Scene: "+e.id)}removeChild(e){for(let t=0,s=this._children.length;t<s;t++)if(this._children[t].id===e.id)return e._parentNode=null,this._children=this._children.splice(t,1),e._setWorldMatrixDirty(),e._setAABBDirty(),this._setAABBDirty(),void(this._numTriangles-=e.numTriangles)}removeChildren(){let e;for(let t=0,s=this._children.length;t<s;t++)e=this._children[t],e._parentNode=null,e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles-=e.numTriangles;this._children=[],this._setAABBDirty()}get numChildren(){return this._children.length}get children(){return this._children}set parent(e){if(y.isNumeric(e)||y.isString(e)){const t=e;if(!(e=this.scene.components[t]))return void this.warn("Node not found: "+y.inQuotes(t));if(!e.isNode)return void this.error("Not a Node: "+e.id)}e.scene.id===this.scene.id?this._parentNode&&this._parentNode.id===e.id?this.warn("Already a child of Node: "+e.id):e.addChild(this):this.error("Node not in same Scene: "+e.id)}get parent(){return this._parentNode}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),h.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),h.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get scale(){return this._scale}set matrix(e){this._localMatrix||(this._localMatrix=h.identityMat4()),this._localMatrix.set(e||In),h.decomposeMat4(this._localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get matrix(){return this._localMatrixDirty&&(this._localMatrix||(this._localMatrix=h.identityMat4()),h.composeMat4(this._position,this._quaternion,this._scale,this._localMatrix),this._localMatrixDirty=!1),this._localMatrix}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}rotate(e,t){return on[0]=e[0],on[1]=e[1],on[2]=e[2],on[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(on,cn),h.mulQuaternions(this.quaternion,cn,un),this.quaternion=un,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return on[0]=e[0],on[1]=e[1],on[2]=e[2],on[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(on,cn),h.mulQuaternions(cn,this.quaternion,cn),this}rotateX(e){return this.rotate(hn,e)}rotateY(e){return this.rotate(pn,e)}rotateZ(e){return this.rotate(An,e)}translate(e,t){return h.vec3ApplyQuaternion(this.quaternion,e,dn),h.mulVec3Scalar(dn,t,fn),h.addVec3(this.position,fn,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(hn,e)}translateY(e){return this.translate(pn,e)}translateZ(e){return this.translate(An,e)}get type(){return"Node"}destroy(){if(super.destroy(),this._parentNode&&this._parentNode.removeChild(this),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let s=0,n=e.length;s<n;s++)t=e[s],t.destroy()}this._children=[],this._setAABBDirty(),this.scene._aabbDirty=!0}}class mn extends Dt{get type(){return"LambertMaterial"}constructor(e,t={}){super(e,t),this._state=new Ve({type:"LambertMaterial",ambient:h.vec3([1,1,1]),color:h.vec3([1,1,1]),emissive:h.vec3([0,0,0]),alpha:null,alphaMode:0,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:"/lam;"}),this.ambient=t.ambient,this.color=t.color,this.emissive=t.emissive,this.alpha=t.alpha,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this.backfaces=t.backfaces,this.frontface=t.frontface}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set color(e){let t=this._state.color;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.color=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get color(){return this._state.color}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this._state.alphaMode=e<1?2:0,this.glRedraw())}get alpha(){return this._state.alpha}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}const vn={opaque:0,mask:1,blend:2},wn=["opaque","mask","blend"];class gn extends Dt{get type(){return"MetallicMaterial"}constructor(e,t={}){super(e,t),this._state=new Ve({type:"MetallicMaterial",baseColor:h.vec4([1,1,1]),emissive:h.vec4([0,0,0]),metallic:null,roughness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.baseColor=t.baseColor,this.metallic=t.metallic,this.roughness=t.roughness,this.specularF0=t.specularF0,this.emissive=t.emissive,this.alpha=t.alpha,t.baseColorMap&&(this._baseColorMap=this._checkComponent("Texture",t.baseColorMap)),t.metallicMap&&(this._metallicMap=this._checkComponent("Texture",t.metallicMap)),t.roughnessMap&&(this._roughnessMap=this._checkComponent("Texture",t.roughnessMap)),t.metallicRoughnessMap&&(this._metallicRoughnessMap=this._checkComponent("Texture",t.metallicRoughnessMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this._makeHash()}_makeHash(){const e=this._state,t=["/met"];this._baseColorMap&&(t.push("/bm"),this._baseColorMap._state.hasMatrix&&t.push("/mat"),t.push("/"+this._baseColorMap._state.encoding)),this._metallicMap&&(t.push("/mm"),this._metallicMap._state.hasMatrix&&t.push("/mat")),this._roughnessMap&&(t.push("/rm"),this._roughnessMap._state.hasMatrix&&t.push("/mat")),this._metallicRoughnessMap&&(t.push("/mrm"),this._metallicRoughnessMap._state.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap._state.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap._state.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/am"),this._alphaMap._state.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap._state.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}set baseColor(e){let t=this._state.baseColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.baseColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get baseColor(){return this._state.baseColor}get baseColorMap(){return this._baseColorMap}set metallic(e){e=null!=e?e:1,this._state.metallic!==e&&(this._state.metallic=e,this.glRedraw())}get metallic(){return this._state.metallic}get metallicMap(){return this._attached.metallicMap}set roughness(e){e=null!=e?e:1,this._state.roughness!==e&&(this._state.roughness=e,this.glRedraw())}get roughness(){return this._state.roughness}get roughnessMap(){return this._attached.roughnessMap}get metallicRoughnessMap(){return this._attached.metallicRoughnessMap}set specularF0(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}get specularF0(){return this._state.specularF0}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}get emissiveMap(){return this._attached.emissiveMap}get occlusionMap(){return this._attached.occlusionMap}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}get alphaMap(){return this._attached.alphaMap}get normalMap(){return this._attached.normalMap}set alphaMode(e){let t=vn[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 wn[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}destroy(){super.destroy(),this._state.destroy()}}const Tn={opaque:0,mask:1,blend:2},En=["opaque","mask","blend"];class bn extends Dt{get type(){return"SpecularMaterial"}constructor(e,t={}){super(e,t),this._state=new Ve({type:"SpecularMaterial",diffuse:h.vec3([1,1,1]),emissive:h.vec3([0,0,0]),specular:h.vec3([1,1,1]),glossiness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.diffuse=t.diffuse,this.specular=t.specular,this.glossiness=t.glossiness,this.specularF0=t.specularF0,this.emissive=t.emissive,this.alpha=t.alpha,t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.glossinessMap&&(this._glossinessMap=this._checkComponent("Texture",t.glossinessMap)),t.specularGlossinessMap&&(this._specularGlossinessMap=this._checkComponent("Texture",t.specularGlossinessMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this._makeHash()}_makeHash(){const e=this._state,t=["/spe"];this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat")),this._glossinessMap&&(t.push("/gm"),this._glossinessMap.hasMatrix&&t.push("/mat")),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._specularGlossinessMap&&(t.push("/sgm"),this._specularGlossinessMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}get diffuseMap(){return this._diffuseMap}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}get specularMap(){return this._specularMap}get specularGlossinessMap(){return this._specularGlossinessMap}set glossiness(e){e=null!=e?e:1,this._state.glossiness!==e&&(this._state.glossiness=e,this.glRedraw())}get glossiness(){return this._state.glossiness}get glossinessMap(){return this._glossinessMap}set specularF0(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}get specularF0(){return this._state.specularF0}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}get emissiveMap(){return this._emissiveMap}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}get alphaMap(){return this._alphaMap}get normalMap(){return this._normalMap}get occlusionMap(){return this._occlusionMap}set alphaMode(e){let t=Tn[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 En[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}destroy(){super.destroy(),this._state.destroy()}}function Dn(e,t,s=null){let n;const i=t;if(1009===i)return e.UNSIGNED_BYTE;if(1017===i)return e.UNSIGNED_SHORT_4_4_4_4;if(1018===i)return e.UNSIGNED_SHORT_5_5_5_1;if(1010===i)return e.BYTE;if(1011===i)return e.SHORT;if(1012===i)return e.UNSIGNED_SHORT;if(1013===i)return e.INT;if(1014===i)return e.UNSIGNED_INT;if(1015===i)return e.FLOAT;if(1016===i)return e.HALF_FLOAT;if(1021===i)return e.ALPHA;if(1023===i)return e.RGBA;if(1024===i)return e.LUMINANCE;if(1025===i)return e.LUMINANCE_ALPHA;if(1026===i)return e.DEPTH_COMPONENT;if(1027===i)return e.DEPTH_STENCIL;if(1028===i)return e.RED;if(1022===i)return e.RGBA;if(1029===i)return e.RED_INTEGER;if(1030===i)return e.RG;if(1031===i)return e.RG_INTEGER;if(1033===i)return e.RGBA_INTEGER;if(33776===i||33777===i||33778===i||33779===i)if(3001===s){const t=Fe(e,"WEBGL_compressed_texture_s3tc_srgb");if(null===t)return null;if(33776===i)return t.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(33777===i)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(33778===i)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(33779===i)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(n=Fe(e,"WEBGL_compressed_texture_s3tc"),null===n)return null;if(33776===i)return n.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===i)return n.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===i)return n.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===i)return n.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===i||35841===i||35842===i||35843===i){const t=Fe(e,"WEBGL_compressed_texture_pvrtc");if(null===t)return null;if(35840===i)return t.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===i)return t.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===i)return t.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===i)return t.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===i){const t=Fe(e,"WEBGL_compressed_texture_etc1");return null!==t?t.COMPRESSED_RGB_ETC1_WEBGL:null}if(37492===i||37496===i){const t=Fe(e,"WEBGL_compressed_texture_etc");if(null===t)return null;if(37492===i)return 3001===s?t.COMPRESSED_SRGB8_ETC2:t.COMPRESSED_RGB8_ETC2;if(37496===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:t.COMPRESSED_RGBA8_ETC2_EAC}if(37808===i||37809===i||37810===i||37811===i||37812===i||37813===i||37814===i||37815===i||37816===i||37817===i||37818===i||37819===i||37820===i||37821===i){const t=Fe(e,"WEBGL_compressed_texture_astc");if(null===t)return null;if(37808===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:t.COMPRESSED_RGBA_ASTC_4x4_KHR;if(37809===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:t.COMPRESSED_RGBA_ASTC_5x4_KHR;if(37810===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:t.COMPRESSED_RGBA_ASTC_5x5_KHR;if(37811===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:t.COMPRESSED_RGBA_ASTC_6x5_KHR;if(37812===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:t.COMPRESSED_RGBA_ASTC_6x6_KHR;if(37813===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:t.COMPRESSED_RGBA_ASTC_8x5_KHR;if(37814===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:t.COMPRESSED_RGBA_ASTC_8x6_KHR;if(37815===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:t.COMPRESSED_RGBA_ASTC_8x8_KHR;if(37816===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:t.COMPRESSED_RGBA_ASTC_10x5_KHR;if(37817===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:t.COMPRESSED_RGBA_ASTC_10x6_KHR;if(37818===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:t.COMPRESSED_RGBA_ASTC_10x8_KHR;if(37819===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:t.COMPRESSED_RGBA_ASTC_10x10_KHR;if(37820===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:t.COMPRESSED_RGBA_ASTC_12x10_KHR;if(37821===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:t.COMPRESSED_RGBA_ASTC_12x12_KHR}if(36492===i){const t=Fe(e,"EXT_texture_compression_bptc");if(null===t)return null;if(36492===i)return 3001===s?t.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:t.COMPRESSED_RGBA_BPTC_UNORM_EXT}return 1020===i?e.UNSIGNED_INT_24_8:1e3===i?e.REPEAT:1001===i?e.CLAMP_TO_EDGE:1004===i||1005===i?e.NEAREST_MIPMAP_LINEAR:1007===i?e.LINEAR_MIPMAP_NEAREST:1008===i?e.LINEAR_MIPMAP_LINEAR:1003===i?e.NEAREST:1006===i?e.LINEAR:null}const Pn=new Uint8Array([0,0,0,1]);class Rn{constructor({gl:e,target:t,format:s,type:n,wrapS:i,wrapT:a,wrapR:r,encoding:l,preloadColor:o,premultiplyAlpha:c,flipY:u}){this.gl=e,this.target=t||e.TEXTURE_2D,this.format=s||1023,this.type=n||1009,this.internalFormat=null,this.premultiplyAlpha=!!c,this.flipY=!!u,this.unpackAlignment=4,this.wrapS=i||1e3,this.wrapT=a||1e3,this.wrapR=r||1e3,this.encoding=l||3001,this.texture=e.createTexture(),o&&this.setPreloadColor(o),this.allocated=!0}setPreloadColor(e){e?(Pn[0]=Math.floor(255*e[0]),Pn[1]=Math.floor(255*e[1]),Pn[2]=Math.floor(255*e[2]),Pn[3]=Math.floor(255*(void 0!==e[3]?e[3]:1))):(Pn[0]=0,Pn[1]=0,Pn[2]=0,Pn[3]=255);const t=this.gl;if(t.bindTexture(this.target,this.texture),this.target===t.TEXTURE_CUBE_MAP){const e=[t.TEXTURE_CUBE_MAP_POSITIVE_X,t.TEXTURE_CUBE_MAP_NEGATIVE_X,t.TEXTURE_CUBE_MAP_POSITIVE_Y,t.TEXTURE_CUBE_MAP_NEGATIVE_Y,t.TEXTURE_CUBE_MAP_POSITIVE_Z,t.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(let s=0,n=e.length;s<n;s++)t.texImage2D(e[s],0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Pn)}else t.texImage2D(this.target,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Pn);t.bindTexture(this.target,null)}setTarget(e){this.target=e||this.gl.TEXTURE_2D}setImage(e,t={}){const s=this.gl;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR);let n=!1;s.bindTexture(this.target,this.texture);const i=s.getParameter(s.UNPACK_FLIP_Y_WEBGL);s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,this.flipY);const a=s.getParameter(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL);s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);const r=s.getParameter(s.UNPACK_ALIGNMENT);s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment);const l=s.getParameter(s.UNPACK_COLORSPACE_CONVERSION_WEBGL);s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE);const o=Dn(s,this.minFilter);s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,o),o!==s.NEAREST_MIPMAP_NEAREST&&o!==s.LINEAR_MIPMAP_NEAREST&&o!==s.NEAREST_MIPMAP_LINEAR&&o!==s.LINEAR_MIPMAP_LINEAR||(n=!0);const c=Dn(s,this.magFilter);c&&s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,c);const u=Dn(s,this.wrapS);u&&s.texParameteri(this.target,s.TEXTURE_WRAP_S,u);const h=Dn(s,this.wrapT);h&&s.texParameteri(this.target,s.TEXTURE_WRAP_T,h);const p=Dn(s,this.format,this.encoding),A=Dn(s,this.type),d=Cn(s,this.internalFormat,p,A,this.encoding,!1);if(this.target===s.TEXTURE_CUBE_MAP){if(y.isArray(e)){const t=e,n=[s.TEXTURE_CUBE_MAP_POSITIVE_X,s.TEXTURE_CUBE_MAP_NEGATIVE_X,s.TEXTURE_CUBE_MAP_POSITIVE_Y,s.TEXTURE_CUBE_MAP_NEGATIVE_Y,s.TEXTURE_CUBE_MAP_POSITIVE_Z,s.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(let e=0,i=n.length;e<i;e++)s.texImage2D(n[e],0,d,p,A,t[e])}}else s.texImage2D(s.TEXTURE_2D,0,d,p,A,e);n&&s.generateMipmap(this.target),s.bindTexture(this.target,null),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,i),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a),s.pixelStorei(s.UNPACK_ALIGNMENT,r),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,l)}setCompressedData({mipmaps:e,props:t={}}){const s=this.gl,n=e.length;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR),s.activeTexture(s.TEXTURE0+0),s.bindTexture(this.target,this.texture);let i=e.length>1;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,this.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE);const a=Dn(s,this.wrapS);a&&s.texParameteri(this.target,s.TEXTURE_WRAP_S,a);const r=Dn(s,this.wrapT);if(r&&s.texParameteri(this.target,s.TEXTURE_WRAP_T,r),this.type===s.TEXTURE_3D||this.type===s.TEXTURE_2D_ARRAY){const e=Dn(s,this.wrapR);e&&s.texParameteri(this.target,s.TEXTURE_WRAP_R,e),s.texParameteri(this.type,s.TEXTURE_WRAP_R,e)}i?(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,_n(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,_n(s,this.magFilter))):(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,Dn(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,Dn(s,this.magFilter)));const l=Dn(s,this.format,this.encoding),o=Dn(s,this.type),c=Cn(s,this.internalFormat,l,o,this.encoding,!1);s.texStorage2D(s.TEXTURE_2D,n,c,e[0].width,e[0].height);for(let t=0,n=e.length;t<n;t++){const n=e[t];1023!==this.format?null!==l?s.compressedTexSubImage2D(s.TEXTURE_2D,t,0,0,n.width,n.height,l,n.data):console.warn("Attempt to load unsupported compressed texture format in .setCompressedData()"):s.texSubImage2D(s.TEXTURE_2D,t,0,0,n.width,n.height,l,o,n.data)}s.bindTexture(this.target,null)}setProps(e){const t=this.gl;t.bindTexture(this.target,this.texture),this._uploadProps(e),t.bindTexture(this.target,null)}_uploadProps(e){const t=this.gl;if(void 0!==e.format&&(this.format=e.format),void 0!==e.internalFormat&&(this.internalFormat=e.internalFormat),void 0!==e.encoding&&(this.encoding=e.encoding),void 0!==e.type&&(this.type=e.type),void 0!==e.minFilter){const s=Dn(t,e.minFilter);s&&(this.minFilter=e.minFilter,t.texParameteri(this.target,t.TEXTURE_MIN_FILTER,s),s!==t.NEAREST_MIPMAP_NEAREST&&s!==t.LINEAR_MIPMAP_NEAREST&&s!==t.NEAREST_MIPMAP_LINEAR&&s!==t.LINEAR_MIPMAP_LINEAR||t.generateMipmap(this.target))}if(void 0!==e.magFilter){const s=Dn(t,e.magFilter);s&&(this.magFilter=e.magFilter,t.texParameteri(this.target,t.TEXTURE_MAG_FILTER,s))}if(void 0!==e.wrapS){const s=Dn(t,e.wrapS);s&&(this.wrapS=e.wrapS,t.texParameteri(this.target,t.TEXTURE_WRAP_S,s))}if(void 0!==e.wrapT){const s=Dn(t,e.wrapT);s&&(this.wrapT=e.wrapT,t.texParameteri(this.target,t.TEXTURE_WRAP_T,s))}}bind(e){if(this.allocated){if(this.texture){const t=this.gl;return t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,this.texture),!0}return!1}}unbind(e){if(this.allocated&&this.texture){const t=this.gl;t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,null)}}destroy(){this.allocated&&this.texture&&(this.gl.deleteTexture(this.texture),this.texture=null)}}function Cn(e,t,s,n,i,a=!1){if(null!==t){if(void 0!==e[t])return e[t];console.warn("Attempt to use non-existing WebGL internal format '"+t+"'")}let r=s;return s===e.RED&&(n===e.FLOAT&&(r=e.R32F),n===e.HALF_FLOAT&&(r=e.R16F),n===e.UNSIGNED_BYTE&&(r=e.R8)),s===e.RG&&(n===e.FLOAT&&(r=e.RG32F),n===e.HALF_FLOAT&&(r=e.RG16F),n===e.UNSIGNED_BYTE&&(r=e.RG8)),s===e.RGBA&&(n===e.FLOAT&&(r=e.RGBA32F),n===e.HALF_FLOAT&&(r=e.RGBA16F),n===e.UNSIGNED_BYTE&&(r=3001===i&&!1===a?e.SRGB8_ALPHA8:e.RGBA8),n===e.UNSIGNED_SHORT_4_4_4_4&&(r=e.RGBA4),n===e.UNSIGNED_SHORT_5_5_5_1&&(r=e.RGB5_A1)),r!==e.R16F&&r!==e.R32F&&r!==e.RG16F&&r!==e.RG32F&&r!==e.RGBA16F&&r!==e.RGBA32F||Fe(e,"EXT_color_buffer_float"),r}function _n(e,t){return 1003===t||1004===t||1005===t?e.NEAREST:e.LINEAR}function Bn(e){if(!On(e.width)||!On(e.height)){const t=document.createElement("canvas");t.width=Sn(e.width),t.height=Sn(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function On(e){return 0==(e&e-1)}function Sn(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class Nn extends C{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new Ve({texture:new Rn({gl:this.scene.canvas.gl}),matrix:h.identityMat4(),hasMatrix:t.translate&&(0!==t.translate[0]||0!==t.translate[1])||!!t.rotate||t.scale&&(0!==t.scale[0]||0!==t.scale[1]),minFilter:this._checkMinFilter(t.minFilter),magFilter:this._checkMagFilter(t.magFilter),wrapS:this._checkWrapS(t.wrapS),wrapT:this._checkWrapT(t.wrapT),flipY:this._checkFlipY(t.flipY),encoding:this._checkEncoding(t.encoding)}),this._src=null,this._image=null,this._translate=h.vec2([0,0]),this._scale=h.vec2([1,1]),this._rotate=h.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),A.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 Rn({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,s;0===this._translate[0]&&0===this._translate[1]||(t=h.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(s=h.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?h.mulMat4(t,s):s),0!==this._rotate&&(s=h.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?h.mulMat4(t,s):s),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=Bn(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let s=new Image;s.onload=function(){s=Bn(s),t._state.texture.setImage(s,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},s.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),A.memory.textures--}}const xn=A.memory,Ln=h.AABB3();class Mn extends pt{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new Ve({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._aabb=null,this._obb=h.OBB3();const s=this._state,n=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=n.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=n.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=n.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=n.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=n.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=n.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=n.TRIANGLE_FAN,s.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),s.primitive=n.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(t.indices){var i;if(t.positionsDecodeMatrix);else{const e=wt.getPositionsBounds(t.positions),a=wt.compressPositions(t.positions,e.min,e.max);i=a.quantized,s.positionsDecodeMatrix=a.decodeMatrix,s.positionsBuf=new ge(n,n.ARRAY_BUFFER,i,i.length,3,n.STATIC_DRAW),xn.positions+=s.positionsBuf.numItems,h.positions3ToAABB3(t.positions,this._aabb),h.positions3ToAABB3(i,Ln,s.positionsDecodeMatrix),h.AABB3ToOBB3(Ln,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);s.colorsBuf=new ge(n,n.ARRAY_BUFFER,e,e.length,4,n.STATIC_DRAW),xn.colors+=s.colorsBuf.numItems}if(t.uv){const e=wt.getUVBounds(t.uv),i=wt.compressUVs(t.uv,e.min,e.max),a=i.quantized;s.uvDecodeMatrix=i.decodeMatrix,s.uvBuf=new ge(n,n.ARRAY_BUFFER,a,a.length,2,n.STATIC_DRAW),xn.uvs+=s.uvBuf.numItems}if(t.normals){const e=wt.compressNormals(t.normals);let i=s.compressGeometry;s.normalsBuf=new ge(n,n.ARRAY_BUFFER,e,e.length,3,n.STATIC_DRAW,i),xn.normals+=s.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);s.indicesBuf=new ge(n,n.ELEMENT_ARRAY_BUFFER,e,e.length,1,n.STATIC_DRAW),xn.indices+=s.indicesBuf.numItems;const a=At(i,e,s.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new ge(n,n.ELEMENT_ARRAY_BUFFER,a,a.length,1,n.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),xn.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(),xn.meshes--}}var Fn={};function Hn(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let s=e.divisions||1;s<0&&(console.error("negative divisions not allowed - will invert"),s*=-1),s<1&&(s=1),t=t||10,s=s||10;const n=t/s,i=t/2,a=[],r=[];let l=0;for(let e=0,t=-i;e<=s;e++,t+=n)a.push(-i),a.push(0),a.push(t),a.push(i),a.push(0),a.push(t),a.push(t),a.push(0),a.push(-i),a.push(t),a.push(0),a.push(i),r.push(l++),r.push(l++),r.push(l++),r.push(l++);return y.apply(e,{primitive:"lines",positions:a,indices:r})}function Un(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);let n=e.xSegments||1;n<0&&(console.error("negative xSegments not allowed - will invert"),n*=-1),n<1&&(n=1);let i=e.xSegments||1;i<0&&(console.error("negative zSegments not allowed - will invert"),i*=-1),i<1&&(i=1);const a=e.center,r=a?a[0]:0,l=a?a[1]:0,o=a?a[2]:0,c=t/2,u=s/2,h=Math.floor(n)||1,p=Math.floor(i)||1,A=h+1,d=p+1,f=t/h,I=s/p,m=new Float32Array(A*d*3),v=new Float32Array(A*d*3),w=new Float32Array(A*d*2);let g,T,E,b,D,P,R,C=0,_=0;for(g=0;g<d;g++){const e=g*I-u;for(T=0;T<A;T++)E=T*f-c,m[C]=E+r,m[C+1]=l,m[C+2]=-e+o,v[C+2]=-1,w[_]=T/h,w[_+1]=(p-g)/p,C+=3,_+=2}C=0;const B=new(m.length/3>65535?Uint32Array:Uint16Array)(h*p*6);for(g=0;g<p;g++)for(T=0;T<h;T++)b=T+A*g,D=T+A*(g+1),P=T+1+A*(g+1),R=T+1+A*g,B[C]=R,B[C+1]=D,B[C+2]=b,B[C+3]=R,B[C+4]=P,B[C+5]=D,C+=6;return y.apply(e,{positions:m,normals:v,uv:w,indices:B})}function Gn(e={}){let t=e.radius||1;t<0&&(console.error("negative radius not allowed - will invert"),t*=-1),t*=.5;let s=e.tube||.3;s<0&&(console.error("negative tube not allowed - will invert"),s*=-1);let n=e.radialSegments||32;n<0&&(console.error("negative radialSegments not allowed - will invert"),n*=-1),n<4&&(n=4);let i=e.tubeSegments||24;i<0&&(console.error("negative tubeSegments not allowed - will invert"),i*=-1),i<4&&(i=4);let a=e.arc||2*Math.PI;a<0&&(console.warn("negative arc not allowed - will invert"),a*=-1),a>360&&(a=360);const r=e.center;let l=r?r[0]:0,o=r?r[1]:0;const c=r?r[2]:0,u=[],p=[],A=[],d=[];let f,I,m,v,w,g,T,E,b,D,P,R;for(E=0;E<=i;E++)for(T=0;T<=n;T++)f=T/n*a,I=.785398+E/i*Math.PI*2,l=t*Math.cos(f),o=t*Math.sin(f),m=(t+s*Math.cos(I))*Math.cos(f),v=(t+s*Math.cos(I))*Math.sin(f),w=s*Math.sin(I),u.push(m+l),u.push(v+o),u.push(w+c),A.push(1-T/n),A.push(E/i),g=h.normalizeVec3(h.subVec3([m,v,w],[l,o,c],[]),[]),p.push(g[0]),p.push(g[1]),p.push(g[2]);for(E=1;E<=i;E++)for(T=1;T<=n;T++)b=(n+1)*E+T-1,D=(n+1)*(E-1)+T-1,P=(n+1)*(E-1)+T,R=(n+1)*E+T,d.push(b),d.push(D),d.push(P),d.push(P),d.push(R),d.push(b);return y.apply(e,{positions:u,normals:p,uv:A,indices:d})}Fn.load=function(e,t){var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=function(e){t(e.target.response)},s.send()},Fn.save=function(e,t){var s="data:application/octet-stream;base64,"+btoa(Fn.parse._buffToStr(e));window.location.href=s},Fn.clone=function(e){return JSON.parse(JSON.stringify(e))},Fn.bin={},Fn.bin.f=new Float32Array(1),Fn.bin.fb=new Uint8Array(Fn.bin.f.buffer),Fn.bin.rf=function(e,t){for(var s=Fn.bin.f,n=Fn.bin.fb,i=0;i<4;i++)n[i]=e[t+i];return s[0]},Fn.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},Fn.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},Fn.bin.rASCII0=function(e,t){for(var s="";0!=e[t];)s+=String.fromCharCode(e[t++]);return s},Fn.bin.wf=function(e,t,s){new Float32Array(e.buffer,t,1)[0]=s},Fn.bin.wsl=function(e,t,s){e[t]=s,e[t+1]=s>>8},Fn.bin.wil=function(e,t,s){e[t]=s,e[t+1]=s>>8,e[t+2]=s>>16,e[t+3]},Fn.parse={},Fn.parse._buffToStr=function(e){for(var t=new Uint8Array(e),s="",n=0;n<t.length;n++)s=s.concat(String.fromCharCode(t[n]));return s},Fn.parse._strToBuff=function(e){for(var t=new ArrayBuffer(e.length),s=new Uint8Array(t),n=0;n<e.length;n++)s[n]=e.charCodeAt(n);return t},Fn.parse._readLine=function(e,t){for(var s="";10!=e[t];)s+=String.fromCharCode(e[t++]);return s},Fn.parse.fromJSON=function(e){return JSON.parse(Fn.parse._buffToStr(e))},Fn.parse.toJSON=function(e){var t=JSON.stringify(e);return Fn.parse._strToBuff(t)},Fn.parse.fromOBJ=function(e){for(var t={groups:{},c_verts:[],c_uvt:[],c_norms:[],i_verts:[],i_uvt:[],i_norms:[]},s={from:0,to:0},n=0,i=new Uint8Array(e);n<i.length;){var a=Fn.parse._readLine(i,n);n+=a.length+1;var r=(a=(a=a.replace(/ +(?= )/g,"")).replace(/(^\s+|\s+$)/g,"")).split(" ");if("g"==r[0]&&(s.to=t.i_verts.length,null==t.groups[r[1]]&&(t.groups[r[1]]={from:t.i_verts.length,to:0}),s=t.groups[r[1]]),"v"==r[0]){var l=parseFloat(r[1]),o=parseFloat(r[2]),c=parseFloat(r[3]);t.c_verts.push(l,o,c)}if("vt"==r[0]){l=parseFloat(r[1]),o=1-parseFloat(r[2]);t.c_uvt.push(l,o)}if("vn"==r[0]){l=parseFloat(r[1]),o=parseFloat(r[2]),c=parseFloat(r[3]);t.c_norms.push(l,o,c)}if("f"==r[0]){var u=r[1].split("/"),h=r[2].split("/"),p=r[3].split("/"),A=parseInt(u[0])-1,d=parseInt(h[0])-1,f=parseInt(p[0])-1,I=parseInt(u[1])-1,y=parseInt(h[1])-1,m=parseInt(p[1])-1,v=parseInt(u[2])-1,w=parseInt(h[2])-1,g=parseInt(p[2])-1,T=t.c_verts.length/3,E=t.c_uvt.length/2,b=t.c_norms.length/3;if(A<0&&(A=T+A+1),d<0&&(d=T+d+1),f<0&&(f=T+f+1),I<0&&(I=E+I+1),y<0&&(y=E+y+1),m<0&&(m=E+m+1),v<0&&(v=b+v+1),w<0&&(w=b+w+1),g<0&&(g=b+g+1),t.i_verts.push(A,d,f),t.i_uvt.push(I,y,m),t.i_norms.push(v,w,g),5==r.length){var D=r[4].split("/"),P=parseInt(D[0])-1,R=parseInt(D[1])-1,C=parseInt(D[2])-1;P<0&&(P=T+P+1),R<0&&(R=E+R+1),C<0&&(C=b+C+1),t.i_verts.push(A,f,P),t.i_uvt.push(I,m,R),t.i_norms.push(v,g,C)}}}return s.to=t.i_verts.length,t},Fn.parse.fromMD2=function(e){e=new Uint8Array(e);var t={},s={};s.ident=Fn.bin.ril(e,0),s.version=Fn.bin.ril(e,4),s.skinwidth=Fn.bin.ril(e,8),s.skinheight=Fn.bin.ril(e,12),s.framesize=Fn.bin.ril(e,16),s.num_skins=Fn.bin.ril(e,20),s.num_vertices=Fn.bin.ril(e,24),s.num_st=Fn.bin.ril(e,28),s.num_tris=Fn.bin.ril(e,32),s.num_glcmds=Fn.bin.ril(e,36),s.num_frames=Fn.bin.ril(e,40),s.offset_skins=Fn.bin.ril(e,44),s.offset_st=Fn.bin.ril(e,48),s.offset_tris=Fn.bin.ril(e,52),s.offset_frames=Fn.bin.ril(e,56),s.offset_glcmds=Fn.bin.ril(e,60),s.offset_end=Fn.bin.ril(e,64);var n=s.offset_st;t.c_uvt=[];for(var i=0;i<s.num_st;i++){var a=Fn.bin.rsl(e,n)/s.skinwidth,r=Fn.bin.rsl(e,n+2)/s.skinheight;t.c_uvt.push(a,r),n+=4}n=s.offset_tris;var l=[],o=[];t.i_verts=l,t.i_uvt=o;for(i=0;i<s.num_tris;i++)l.push(Fn.bin.rsl(e,n),Fn.bin.rsl(e,n+2),Fn.bin.rsl(e,n+4)),o.push(Fn.bin.rsl(e,n+6),Fn.bin.rsl(e,n+8),Fn.bin.rsl(e,n+10)),n+=12;n=s.offset_skins;t.skins=[];for(i=0;i<s.num_skins;i++)t.skins.push(Fn.bin.rASCII0(e,n)),n+=64;n=s.offset_frames;t.frames=[];var c=Fn.parse.fromMD2._normals;for(i=0;i<s.num_frames;i++){var u={},h=Fn.bin.rf(e,n),p=Fn.bin.rf(e,n+4),A=Fn.bin.rf(e,n+8);n+=12;var d=Fn.bin.rf(e,n),f=Fn.bin.rf(e,n+4),I=Fn.bin.rf(e,n+8);n+=12,u.name=Fn.bin.rASCII0(e,n),n+=16,u.verts=[],u.norms=[];for(var y=0;y<s.num_vertices;y++)u.verts.push(e[n]*h+d,e[n+1]*p+f,e[n+2]*A+I),u.norms.push(c[3*e[n+3]],c[3*e[n+3]+1],c[3*e[n+3]+2]),n+=4;t.frames.push(u)}return t},Fn.parse.fromMD2._normals=[-.525731,0,.850651,-.442863,.238856,.864188,-.295242,0,.955423,-.309017,.5,.809017,-.16246,.262866,.951056,0,0,1,0,.850651,.525731,-.147621,.716567,.681718,.147621,.716567,.681718,0,.525731,.850651,.309017,.5,.809017,.525731,0,.850651,.295242,0,.955423,.442863,.238856,.864188,.16246,.262866,.951056,-.681718,.147621,.716567,-.809017,.309017,.5,-.587785,.425325,.688191,-.850651,.525731,0,-.864188,.442863,.238856,-.716567,.681718,.147621,-.688191,.587785,.425325,-.5,.809017,.309017,-.238856,.864188,.442863,-.425325,.688191,.587785,-.716567,.681718,-.147621,-.5,.809017,-.309017,-.525731,.850651,0,0,.850651,-.525731,-.238856,.864188,-.442863,0,.955423,-.295242,-.262866,.951056,-.16246,0,1,0,0,.955423,.295242,-.262866,.951056,.16246,.238856,.864188,.442863,.262866,.951056,.16246,.5,.809017,.309017,.238856,.864188,-.442863,.262866,.951056,-.16246,.5,.809017,-.309017,.850651,.525731,0,.716567,.681718,.147621,.716567,.681718,-.147621,.525731,.850651,0,.425325,.688191,.587785,.864188,.442863,.238856,.688191,.587785,.425325,.809017,.309017,.5,.681718,.147621,.716567,.587785,.425325,.688191,.955423,.295242,0,1,0,0,.951056,.16246,.262866,.850651,-.525731,0,.955423,-.295242,0,.864188,-.442863,.238856,.951056,-.16246,.262866,.809017,-.309017,.5,.681718,-.147621,.716567,.850651,0,.525731,.864188,.442863,-.238856,.809017,.309017,-.5,.951056,.16246,-.262866,.525731,0,-.850651,.681718,.147621,-.716567,.681718,-.147621,-.716567,.850651,0,-.525731,.809017,-.309017,-.5,.864188,-.442863,-.238856,.951056,-.16246,-.262866,.147621,.716567,-.681718,.309017,.5,-.809017,.425325,.688191,-.587785,.442863,.238856,-.864188,.587785,.425325,-.688191,.688191,.587785,-.425325,-.147621,.716567,-.681718,-.309017,.5,-.809017,0,.525731,-.850651,-.525731,0,-.850651,-.442863,.238856,-.864188,-.295242,0,-.955423,-.16246,.262866,-.951056,0,0,-1,.295242,0,-.955423,.16246,.262866,-.951056,-.442863,-.238856,-.864188,-.309017,-.5,-.809017,-.16246,-.262866,-.951056,0,-.850651,-.525731,-.147621,-.716567,-.681718,.147621,-.716567,-.681718,0,-.525731,-.850651,.309017,-.5,-.809017,.442863,-.238856,-.864188,.16246,-.262866,-.951056,.238856,-.864188,-.442863,.5,-.809017,-.309017,.425325,-.688191,-.587785,.716567,-.681718,-.147621,.688191,-.587785,-.425325,.587785,-.425325,-.688191,0,-.955423,-.295242,0,-1,0,.262866,-.951056,-.16246,0,-.850651,.525731,0,-.955423,.295242,.238856,-.864188,.442863,.262866,-.951056,.16246,.5,-.809017,.309017,.716567,-.681718,.147621,.525731,-.850651,0,-.238856,-.864188,-.442863,-.5,-.809017,-.309017,-.262866,-.951056,-.16246,-.850651,-.525731,0,-.716567,-.681718,-.147621,-.716567,-.681718,.147621,-.525731,-.850651,0,-.5,-.809017,.309017,-.238856,-.864188,.442863,-.262866,-.951056,.16246,-.864188,-.442863,.238856,-.809017,-.309017,.5,-.688191,-.587785,.425325,-.681718,-.147621,.716567,-.442863,-.238856,.864188,-.587785,-.425325,.688191,-.309017,-.5,.809017,-.147621,-.716567,.681718,-.425325,-.688191,.587785,-.16246,-.262866,.951056,.442863,-.238856,.864188,.16246,-.262866,.951056,.309017,-.5,.809017,.147621,-.716567,.681718,0,-.525731,.850651,.425325,-.688191,.587785,.587785,-.425325,.688191,.688191,-.587785,.425325,-.955423,.295242,0,-.951056,.16246,.262866,-1,0,0,-.850651,0,.525731,-.955423,-.295242,0,-.951056,-.16246,.262866,-.864188,.442863,-.238856,-.951056,.16246,-.262866,-.809017,.309017,-.5,-.864188,-.442863,-.238856,-.951056,-.16246,-.262866,-.809017,-.309017,-.5,-.681718,.147621,-.716567,-.681718,-.147621,-.716567,-.850651,0,-.525731,-.688191,.587785,-.425325,-.587785,.425325,-.688191,-.425325,.688191,-.587785,-.425325,-.688191,-.587785,-.587785,-.425325,-.688191,-.688191,-.587785,-.425325],Fn.parse.fromCollada=function(e){var t=Fn.parse._buffToStr(e),s=(new DOMParser).parseFromString(t,"text/xml"),n={},i=(s=s.childNodes[0]).getElementsByTagName("asset")[0],a=s.getElementsByTagName("library_geometries")[0],r=s.getElementsByTagName("library_images")[0],l=s.getElementsByTagName("library_materials")[0],o=s.getElementsByTagName("library_effects")[0];return i&&(n.asset=Fn.parse.fromCollada._asset(i)),a&&(n.geometries=Fn.parse.fromCollada._libGeometries(a)),r&&(n.images=Fn.parse.fromCollada._libImages(r)),l&&(n.materials=Fn.parse.fromCollada._libMaterials(l)),o&&(n.effects=Fn.parse.fromCollada._libEffects(o)),n},Fn.parse.fromCollada._asset=function(e){return{created:e.getElementsByTagName("created")[0].textContent,modified:e.getElementsByTagName("modified")[0].textContent,up_axis:e.getElementsByTagName("up_axis")[0].textContent}},Fn.parse.fromCollada._libGeometries=function(e){e=e.getElementsByTagName("geometry");for(var t=[],s=0;s<e.length;s++){var n=e[s],i=Fn.parse.fromCollada._getMesh(n.getElementsByTagName("mesh")[0]);t.push(i)}return t},Fn.parse.fromCollada._getMesh=function(e){for(var t={},s=e.getElementsByTagName("source"),n=t.sources={},i=0;i<s.length;i++){for(var a=s[i].getElementsByTagName("float_array")[0].textContent.split(" "),r=a.length-(""==a[a.length-1]?1:0),l=new Array(r),o=0;o<r;o++)l[o]=parseFloat(a[o]);n[s[i].getAttribute("id")]=l}t.triangles=[];var c=e.getElementsByTagName("triangles");if(null==c)return t;for(i=0;i<c.length;i++){var u={},h=c[i];u.material=h.getAttribute("material");var p=h.getElementsByTagName("input"),A=[];for(o=0;o<p.length;o++){var d=p[o];l=[];A[parseInt(d.getAttribute("offset"))]=l;var f=d.getAttribute("semantic");u["s_"+f]="VERTEX"==f?e.getElementsByTagName("vertices")[0].getElementsByTagName("input")[0].getAttribute("source").substring(1):d.getAttribute("source").substring(1),u["i_"+f]=l,n[u["s_"+f]]}var I=h.getElementsByTagName("p")[0].textContent.split(" "),y=3*Math.floor(I.length/3);for(o=0;o<y;o++)A[o%p.length].push(parseInt(I[o]));t.triangles.push(u)}return t},Fn.parse.fromCollada._libImages=function(e){e=e.getElementsByTagName("image");for(var t={},s=0;s<e.length;s++)t[e[s].getAttribute("id")]=e[s].getElementsByTagName("init_from")[0].textContent;return t},Fn.parse.fromCollada._libMaterials=function(e){e=e.getElementsByTagName("material");for(var t={},s=0;s<e.length;s++)t[e[s].getAttribute("name")]=e[s].getElementsByTagName("instance_effect")[0].getAttribute("url").substring(1);return t},Fn.parse.fromCollada._libEffects=function(e){e=e.getElementsByTagName("effect");for(var t={},s=0;s<e.length;s++){for(var n={},i=e[s].getElementsByTagName("newparam"),a=0;a<i.length;a++){var r=i[a].getElementsByTagName("surface")[0];r&&(n.surface=r.getElementsByTagName("init_from")[0].textContent)}t[e[s].getAttribute("id")]=n}return t},Fn.parse.from3DS=function(e){e=new Uint8Array(e);var t={};if(19789!=Fn.bin.rsl(e,0))return null;for(var s=Fn.bin.ril(e,2),n=6;n<s;){var i=Fn.bin.rsl(e,n),a=Fn.bin.ril(e,n+2);15677==i&&(t.edit=Fn.parse.from3DS._edit3ds(e,n,a)),45056==i&&(t.keyf=Fn.parse.from3DS._keyf3ds(e,n,a)),n+=a}return t},Fn.parse.from3DS._edit3ds=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=Fn.bin.rsl(e,i),r=Fn.bin.ril(e,i+2);16384==a&&(null==n.objects&&(n.objects=[]),n.objects.push(Fn.parse.from3DS._edit_object(e,i,r))),i+=r}return n},Fn.parse.from3DS._keyf3ds=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=Fn.bin.rsl(e,i),r=Fn.bin.ril(e,i+2);45058==a&&(null==n.desc&&(n.desc=[]),n.desc.push(Fn.parse.from3DS._keyf_objdes(e,i,r))),i+=r}return n},Fn.parse.from3DS._keyf_objdes=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=Fn.bin.rsl(e,i),r=Fn.bin.ril(e,i+2);45072==a&&(n.hierarchy=Fn.parse.from3DS._keyf_objhierarch(e,i,r)),45073==a&&(n.dummy_name=Fn.bin.rASCII0(e,i+6)),i+=r}return n},Fn.parse.from3DS._keyf_objhierarch=function(e,t,s){var n={},i=t+6;return n.name=Fn.bin.rASCII0(e,i),i+=n.name.length+1,n.hierarchy=Fn.bin.rsl(e,i+4),n},Fn.parse.from3DS._edit_object=function(e,t,s){var n={},i=t+6;for(n.name=Fn.bin.rASCII0(e,i),i+=n.name.length+1;i<t+s;){var a=Fn.bin.rsl(e,i),r=Fn.bin.ril(e,i+2);16640==a&&(n.mesh=Fn.parse.from3DS._obj_trimesh(e,i,r)),i+=r}return n},Fn.parse.from3DS._obj_trimesh=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=Fn.bin.rsl(e,i),r=Fn.bin.ril(e,i+2);16656==a&&(n.vertices=Fn.parse.from3DS._tri_vertexl(e,i,r)),16672==a&&(n.indices=Fn.parse.from3DS._tri_facel1(e,i,r)),16704==a&&(n.uvt=Fn.parse.from3DS._tri_mappingcoors(e,i,r)),16736==a&&(n.local=Fn.parse.from3DS._tri_local(e,i,r)),i+=r}return n},Fn.parse.from3DS._tri_vertexl=function(e,t,s){var n=[],i=t+6,a=Fn.bin.rsl(e,i);i+=2;for(var r=0;r<a;r++)n.push(Fn.bin.rf(e,i)),n.push(Fn.bin.rf(e,i+4)),n.push(Fn.bin.rf(e,i+8)),i+=12;return n},Fn.parse.from3DS._tri_facel1=function(e,t,s){var n=[],i=t+6,a=Fn.bin.rsl(e,i);i+=2;for(var r=0;r<a;r++)n.push(Fn.bin.rsl(e,i)),n.push(Fn.bin.rsl(e,i+2)),n.push(Fn.bin.rsl(e,i+4)),i+=8;return n},Fn.parse.from3DS._tri_mappingcoors=function(e,t,s){var n=[],i=t+6,a=Fn.bin.rsl(e,i);i+=2;for(var r=0;r<a;r++)n.push(Fn.bin.rf(e,i)),n.push(1-Fn.bin.rf(e,i+4)),i+=8;return n},Fn.parse.from3DS._tri_local=function(e,t,s){var n={},i=t+6;return n.X=[Fn.bin.rf(e,i),Fn.bin.rf(e,i+4),Fn.bin.rf(e,i+8)],i+=12,n.Y=[Fn.bin.rf(e,i),Fn.bin.rf(e,i+4),Fn.bin.rf(e,i+8)],i+=12,n.Z=[Fn.bin.rf(e,i),Fn.bin.rf(e,i+4),Fn.bin.rf(e,i+8)],i+=12,n.C=[Fn.bin.rf(e,i),Fn.bin.rf(e,i+4),Fn.bin.rf(e,i+8)],i+=12,n},Fn.parse.fromBIV=function(e){e=new Uint8Array(e);var t={},s={};return s.id=Fn.bin.ril(e,0),s.verS=Fn.bin.ril(e,4),s.texS=Fn.bin.ril(e,8),s.indS=Fn.bin.ril(e,12),s.verO=Fn.bin.ril(e,16),s.verL=Fn.bin.ril(e,20),s.texO=Fn.bin.ril(e,24),s.texL=Fn.bin.ril(e,28),s.indO=Fn.bin.ril(e,32),s.indL=Fn.bin.ril(e,36),0!=s.verO&&(t.vertices=Fn.parse.fromBIV._readFloats(e,s.verO,s.verL)),0!=s.texO&&(t.uvt=Fn.parse.fromBIV._readFloats(e,s.texO,s.texL)),0!=s.indO&&(t.indices=Fn.parse.fromBIV._readInts(e,s.indO,s.indL,s.indS)),t},Fn.parse.toBIV=function(e){for(var t=0,s=0;s<e.indices.length;s++)t=Math.max(t,e.indices[s]);var n=32;t<=65535&&(n=16);var i=40;e.vertices&&(i+=4*e.vertices.length),e.uvt&&(i+=4*e.uvt.length),e.indices&&(i+=e.indices.length*n/8);var a=new Uint8Array(i);Fn.bin.wil(a,0,1769365870),Fn.bin.wil(a,4,32),Fn.bin.wil(a,8,32),Fn.bin.wil(a,12,n);var r=40;return e.vertices&&(Fn.bin.wil(a,16,r),Fn.bin.wil(a,20,4*e.vertices.length),Fn.parse.fromBIV._writeFloats(a,r,e.vertices),r+=4*e.vertices.length),e.uvt&&(Fn.bin.wil(a,24,r),Fn.bin.wil(a,28,4*e.uvt.length),Fn.parse.fromBIV._writeFloats(a,r,e.uvt),r+=4*e.uvt.length),e.indices&&(Fn.bin.wil(a,32,r),Fn.bin.wil(a,36,4*e.indices.length),Fn.parse.fromBIV._writeInts(a,r,e.indices,n)),a.buffer},Fn.parse.fromBIV._readFloats=function(e,t,s){for(var n=[],i=0;i<s/4;i++)n.push(Fn.bin.rf(e,t+4*i));return n},Fn.parse.fromBIV._writeFloats=function(e,t,s){for(var n=0;n<s.length;n++)Fn.bin.wf(e,t+4*n,s[n])},Fn.parse.fromBIV._readInts=function(e,t,s,n){for(var i=[],a=0;a<s/4;a++)16==n&&i.push(Fn.bin.rsl(e,t+2*a)),32==n&&i.push(Fn.bin.ril(e,t+4*a));return i},Fn.parse.fromBIV._writeInts=function(e,t,s,n){for(var i=0;i<s.length;i++)16==n&&Fn.bin.wsl(e,t+2*i,s[i]),32==n&&Fn.bin.wil(e,t+4*i,s[i])},Fn.gen={},Fn.gen.Plane=function(e,t,s,n){s||(s=1),n||(n=1);for(var i={verts:[],inds:[],uvt:[]},a=e+1,r=t+1,l=0;l<r;l++)for(var o=0;o<a;o++){var c=o*(2/e)-1,u=l*(2/t)-1;i.verts.push(c,u,0),i.uvt.push(s*o/e,n*l/t),l<t&&o<e&&i.inds.push(l*a+o,l*a+o+1,(l+1)*a+o,l*a+o+1,(l+1)*a+o,(l+1)*a+o+1)}return i},Fn.gen.Cube=function(){return{verts:[-1,1,-1,1,1,-1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,1,-1,1,1,-1,-1,-1,1,-1,1,1,-1,-1,1,1,1,1,1,-1,-1,-1,1,-1,-1,-1,-1,1,1,-1,1],inds:[0,1,2,1,2,3,4,5,6,5,6,7,8,9,10,9,10,11,12,13,14,13,14,15,16,17,18,17,18,19,20,21,22,21,22,23],uvt:[1/4,1/4,.5,1/4,1/4,.5,.5,.5,1,1/4,3/4,1/4,1,.5,3/4,.5,0,1/4,1/4,1/4,0,.5,1/4,.5,3/4,1/4,.5,1/4,3/4,.5,.5,.5,1/4,1/4,.5,1/4,1/4,0,.5,0,1/4,.5,.5,.5,1/4,3/4,.5,3/4]}},Fn.gen.Sphere=function(e,t){for(var s={verts:[],inds:[],uvt:[]},n=e+1,i=t+1,a=0;a<i;a++)for(var r=0;r<n;r++){var l=-Math.PI/2+a*Math.PI/t,o=2*r*Math.PI/e,c=Math.cos(l)*Math.cos(o),u=Math.sin(l),h=Math.cos(l)*Math.sin(o);s.verts.push(c,u,h),s.uvt.push(r/e,a/t),a<t&&r<e&&s.inds.push(n*a+r,n*a+r+1,n*(a+1)+r,n*a+r+1,n*(a+1)+r,n*(a+1)+r+1)}return s},Fn.mat={},Fn.mat.scale=function(e,t,s){return[e,0,0,0,0,t,0,0,0,0,s,0,0,0,0,1]},Fn.mat.translate=function(e,t,s){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,s,1]},Fn.mat.rotateDeg=function(e,t,s){var n=Math.PI/180;return Fn.mat.rotate(e*n,t*n,s*n)},Fn.mat.rotate=function(e,t,s){var n=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],i=e,a=t,r=s,l=Math.cos(i),o=Math.cos(a),c=Math.cos(r),u=Math.sin(i),h=Math.sin(a),p=Math.sin(r);return n[0]=o*c,n[1]=-o*p,n[2]=h,n[4]=l*p+u*h*c,n[5]=l*c-u*h*p,n[6]=-u*o,n[8]=u*p-l*h*c,n[9]=u*c+l*h*p,n[10]=l*o,n},Fn.edit={},Fn.edit.interpolate=function(e,t,s,n){for(var i=0;i<e.length;i++)s[i]=e[i]+n*(t[i]-e[i])},Fn.edit.transform=function(e,t){for(var s=0;s<e.length;s+=3){var n=e[s],i=e[s+1],a=e[s+2];e[s+0]=t[0]*n+t[4]*i+t[8]*a+t[12],e[s+1]=t[1]*n+t[5]*i+t[9]*a+t[13],e[s+2]=t[2]*n+t[6]*i+t[10]*a+t[14]}},Fn.edit.unwrap=function(e,t,s){for(var n=new Array(Math.floor(e.length/3)*s),i=0;i<e.length;i++)for(var a=0;a<s;a++)n[i*s+a]=t[e[i]*s+a];return n},Fn.edit.remap=function(e,t,s,n){for(var i=new Array(s.length),a=0;a<e.length;a++)for(var r=0;r<n;r++)i[t[a]*n+r]=s[e[a]*n+r];return i},Fn.utils={},Fn.utils.getAABB=function(e){var t,s,n,i,a,r;i=a=r=-(t=s=n=999999999);for(var l=0;l<e.length;l+=3){var o=e[l+0],c=e[l+1],u=e[l+2];o<t&&(t=o),o>i&&(i=o),c<s&&(s=c),c>a&&(a=c),u<n&&(n=u),c>r&&(r=u)}return{min:{x:t,y:s,z:n},max:{x:i,y:a,z:r}}};class Vn extends C{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=h.vec3(t.pos||[0,0,0]),this._up=h.vec3(t.up||[0,1,0]),this._normal=h.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=h.vec3(),this._rtcPos=h.vec3(),this._imageSize=h.vec2(),this._texture=new Nn(this),this._image=new Image,"jpg"!==this._type&&"png"!==this._type&&(this.error('Unsupported type - defaulting to "jpg"'),this._type="jpg"),this._node=new yn(this,{matrix:h.inverseMat4(h.lookAtMat4v(this._pos,h.subVec3(this._pos,this._normal,h.mat4()),this._up,h.mat4())),children:[this._bitmapMesh=new en(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new Et(this,Un({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Ct(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0})})]}),t.image?this.image=t.image:t.src?this.src=t.src:t.imageData&&(this.imageData=t.imageData),this.scene._bitmapCreated(this)}set visible(e){this._bitmapMesh.visible=e}get visible(){return this._bitmapMesh.visible}set image(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}get image(){return this._image}set src(e){if(e){this._image.onload=()=>{this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale()},this._image.src=e;switch(e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}}get src(){return this._image.src}set imageData(e){this._image.onload=()=>{this._texture.image=image,this._imageSize[0]=image.width,this._imageSize[1]=image.height,this._updateBitmapMeshScale()},this._image.src=e}get imageData(){const e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")}set type(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}get type(){return this._type}get pos(){return this._pos}get normal(){return this._normal}get up(){return this._up}set height(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}get height(){return this._height}set collidable(e){this._bitmapMesh.collidable=!1!==e}get collidable(){return this._bitmapMesh.collidable}set clippable(e){this._bitmapMesh.clippable=!1!==e}get clippable(){return this._bitmapMesh.clippable}set pickable(e){this._bitmapMesh.pickable=!1!==e}get pickable(){return this._bitmapMesh.pickable}set opacity(e){this._bitmapMesh.opacity=e}get opacity(){return this._bitmapMesh.opacity}destroy(){super.destroy(),this.scene._bitmapDestroyed(this)}_updateBitmapMeshScale(){const e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height*e,1,this._height]}}class jn extends C{constructor(e,t={}){if(super(e,t),this._positions=t.positions||[],this._origin=h.vec3(t.origin||[0,0,0]),t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;e<t;e+=2)this._indices.push(e),this._indices.push(e+1)}this._mesh=new en(this,{visible:t.visible,clippable:t.clippable,collidable:t.collidable,geometry:new Mn(this,{primitive:"lines",positions:this._positions,indices:this._indices,origin:t.origin}),material:new Ct(this,{diffuse:t.color||[0,0,0],emissive:t.color||[0,0,0]})}),this.scene._lineSetCreated(this)}set visible(e){this._mesh.visible=e}get visible(){return this._mesh.visible}get positions(){return this._positions}get indices(){return this._indices}destroy(){super.destroy(),this.scene._lineSetDestroyed(this)}}const kn=h.vec3(),Qn=h.vec3(),Wn=h.vec3(),zn=h.vec3();function Kn(e){return{x:e[0],y:e[1],z:e[2]}}function Yn(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function Xn(e){return new Float64Array([e[0],-e[2],e[1]])}function qn(e){return new Float64Array([e[0],e[2],-e[1]])}var Jn=h.vec3();const Zn=(e,t,s,n)=>{var i=e-s,a=t-n;return Math.sqrt(i*i+a*a)};class $n extends C{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var s=this.plugin.viewer.scene;this._originMarker=new Y(s,t.origin),this._targetMarker=new Y(s,t.target),this._originWorld=h.vec3(),this._targetWorld=h.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 n=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,i=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,a=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,r=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new q(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._targetDot=new q(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._lengthWire=new X(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._xAxisWire=new X(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._yAxisWire=new X(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._zAxisWire=new X(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._lengthLabel=new J(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._xAxisLabel=new J(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._yAxisLabel=new J(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._zAxisLabel=new J(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=s.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=s.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=s.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(h.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);const t=this._originMarker.viewPos[2],s=this._targetMarker.viewPos[2];if(t>-.3||s>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){h.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var n=this._pp,i=this._cp,a=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var r=a.top-t.top,l=a.left-t.left,o=e.canvas.boundary,c=o[2],u=o[3],p=0;const s=this.plugin.viewer.scene.metrics,f=s.scale,I=s.units,y=s.unitsInfo[I].abbrev;for(var A=0,d=n.length;A<d;A+=4)i[p]=l+Math.floor((1+n[A+0]/n[A+3])*c/2),i[p+1]=r+Math.floor((1-n[A+1]/n[A+3])*u/2),p+=2;if(this._originDot.setPos(i[0],i[1]),this._targetDot.setPos(i[6],i[7]),this._lengthWire.setStartAndEnd(i[0],i[1],i[6],i[7]),this._xAxisWire.setStartAndEnd(i[0],i[1],i[2],i[3]),this._yAxisWire.setStartAndEnd(i[2],i[3],i[4],i[5]),this._zAxisWire.setStartAndEnd(i[4],i[5],i[6],i[7]),this.labelsVisible){this._lengthLabel.setPosOnWire(i[0],i[1],i[6],i[7]),this._xAxisLabel.setPosOnWire(i[0],i[1],i[2],i[3]),this._yAxisLabel.setPosOnWire(i[2],i[3],i[4],i[5]),this._zAxisLabel.setPosOnWire(i[4],i[5],i[6],i[7]);const e=this._approximate?" ~ ":" = ";this._length=Math.abs(h.lenVec3(h.subVec3(this._targetWorld,this._originWorld,Jn))),this._lengthLabel.setText(e+(this._length*f).toFixed(2)+y);const t=Math.abs(Zn(i[0],i[1],i[2],i[3])),s=Math.abs(Zn(i[2],i[3],i[4],i[5])),n=Math.abs(Zn(i[4],i[5],i[6],i[7])),a=this.plugin.labelMinAxisLength;this._xAxisLabelCulled=t<a,this._yAxisLabelCulled=s<a,this._zAxisLabelCulled=n<a,this._xAxisLabelCulled?this._xAxisLabel.setCulled(!0):(this._xAxisLabel.setText(e+Math.abs((this._targetWorld[0]-this._originWorld[0])*f).toFixed(2)+y),this._xAxisLabel.setCulled(!this.axisVisible)),this._yAxisLabelCulled?this._yAxisLabel.setCulled(!0):(this._yAxisLabel.setText(e+Math.abs((this._targetWorld[1]-this._originWorld[1])*f).toFixed(2)+y),this._yAxisLabel.setCulled(!this.axisVisible)),this._zAxisLabelCulled?this._zAxisLabel.setCulled(!0):(this._zAxisLabel.setText(e+Math.abs((this._targetWorld[2]-this._originWorld[2])*f).toFixed(2)+y),this._zAxisLabel.setCulled(!this.axisVisible))}else this._lengthLabel.setCulled(!0),this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0);this._originDot.setVisible(this._visible&&this._originVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._xAxisWire.setVisible(this.axisVisible&&this.xAxisVisible),this._yAxisWire.setVisible(this.axisVisible&&this.yAxisVisible),this._zAxisWire.setVisible(this.axisVisible&&this.zAxisVisible),this._lengthWire.setVisible(this.wireVisible),this._lengthLabel.setCulled(!this.wireVisible),this._cpDirty=!1}}set approximate(e){e=!1!==e,this._approximate!==e&&(this._approximate=e,this._cpDirty=!0,this._needUpdate(0))}get approximate(){return this._approximate}get origin(){return this._originMarker}get target(){return this._targetMarker}get length(){this._update();const e=this.plugin.viewer.scene.metrics.scale;return this._length*e}get color(){return this._color}set color(e){this._color=e,this._originDot.setFillColor(e),this._targetDot.setFillColor(e),this._lengthWire.setColor(e),this._lengthLabel.setFillColor(e)}set visible(e){e=void 0!==e?Boolean(e):this.plugin.defaultVisible,this._visible=e,this._originDot.setVisible(this._visible&&this._originVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._lengthWire.setVisible(this._visible&&this._wireVisible),this._lengthLabel.setVisible(this._visible&&this._wireVisible);const t=this._visible&&this._axisVisible&&this._xAxisVisible,s=this._visible&&this._axisVisible&&this._yAxisVisible,n=this._visible&&this._axisVisible&&this._zAxisVisible;this._xAxisWire.setVisible(t),this._yAxisWire.setVisible(s),this._zAxisWire.setVisible(n),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled),this._yAxisLabel.setVisible(s&&!this._yAxisLabelCulled),this._zAxisLabel.setVisible(n&&!this._zAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get visible(){return this._visible}set originVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultOriginVisible,this._originVisible=e,this._originDot.setVisible(this._visible&&this._originVisible)}get originVisible(){return this._originVisible}set targetVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultTargetVisible,this._targetVisible=e,this._targetDot.setVisible(this._visible&&this._targetVisible)}get targetVisible(){return this._targetVisible}set axisEnabled(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._axisEnabled=e;var t=this._visible&&this._axisVisible&&this._axisEnabled;this._xAxisWire.setVisible(t&&this._xAxisVisible),this._yAxisWire.setVisible(t&&this._yAxisVisible),this._zAxisWire.setVisible(t&&this._zAxisVisible),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled&&this._xAxisVisible),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled&&this._xAxisVisible),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled&&this._xAxisVisible),this._cpDirty=!0,this._needUpdate()}get axisEnabled(){return this._axisEnabled}set axisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._axisVisible=e;var t=this._visible&&this._axisVisible&&this._axisEnabled;this._xAxisWire.setVisible(t&&this._xAxisVisible),this._yAxisWire.setVisible(t&&this._yAxisVisible),this._zAxisWire.setVisible(t&&this._zAxisVisible),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled&&this._xAxisVisible),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled&&this._yAxisVisible),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled&&this._zAxisVisible),this._cpDirty=!0,this._needUpdate()}get axisVisible(){return this._axisVisible}set xAxisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._xAxisVisible=e;const t=this._visible&&this._axisVisible&&this._xAxisVisible&&this._axisEnabled;this._xAxisWire.setVisible(t),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get xAxisVisible(){return this._xAxisVisible}set yAxisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._yAxisVisible=e;const t=this._visible&&this._axisVisible&&this._yAxisVisible&&this._axisEnabled;this._yAxisWire.setVisible(t),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get yAxisVisible(){return this._yAxisVisible}set zAxisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._zAxisVisible=e;const t=this._visible&&this._axisVisible&&this._zAxisVisible&&this._axisEnabled;this._zAxisWire.setVisible(t),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get zAxisVisible(){return this._zAxisVisible}set wireVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultWireVisible,this._wireVisible=e;var t=this._visible&&this._wireVisible;this._lengthLabel.setVisible(t),this._lengthWire.setVisible(t)}get wireVisible(){return this._wireVisible}set labelsVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultLabelsVisible,this._labelsVisible=e;var t=this._visible&&this._labelsVisible;this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled&&this._clickable&&this._axisEnabled),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled&&this._clickable&&this._axisEnabled),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled&&this._clickable&&this._axisEnabled),this._lengthLabel.setVisible(t),this._cpDirty=!0,this._needUpdate()}get labelsVisible(){return this._labelsVisible}setHighlighted(e){this._originDot.setHighlighted(e),this._targetDot.setHighlighted(e),this._xAxisWire.setHighlighted(e),this._yAxisWire.setHighlighted(e),this._zAxisWire.setHighlighted(e),this._xAxisLabel.setHighlighted(e),this._yAxisLabel.setHighlighted(e),this._zAxisLabel.setHighlighted(e),this._lengthWire.setHighlighted(e),this._lengthLabel.setHighlighted(e)}set clickable(e){e=!!e,this._clickable=e,this._originDot.setClickable(this._clickable),this._targetDot.setClickable(this._clickable),this._xAxisWire.setClickable(this._clickable),this._yAxisWire.setClickable(this._clickable),this._zAxisWire.setClickable(this._clickable),this._lengthWire.setClickable(this._clickable),this._xAxisLabel.setClickable(this._clickable),this._yAxisLabel.setClickable(this._clickable),this._zAxisLabel.setClickable(this._clickable),this._lengthLabel.setClickable(this._clickable)}get clickable(){return this._clickable}destroy(){const e=this.plugin.viewer.scene,t=e.metrics;this._onViewMatrix&&e.camera.off(this._onViewMatrix),this._onProjMatrix&&e.camera.off(this._onProjMatrix),this._onCanvasBoundary&&e.canvas.off(this._onCanvasBoundary),this._onMetricsUnits&&t.off(this._onMetricsUnits),this._onMetricsScale&&t.off(this._onMetricsScale),this._onMetricsOrigin&&t.off(this._onMetricsOrigin),this._originDot.destroy(),this._targetDot.destroy(),this._xAxisWire.destroy(),this._yAxisWire.destroy(),this._zAxisWire.destroy(),this._lengthLabel.destroy(),this._xAxisLabel.destroy(),this._yAxisLabel.destroy(),this._zAxisLabel.destroy(),this._lengthWire.destroy(),super.destroy()}}class ei{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const s=this._messages[this._locale];if(!s)return null;const n=ti(e,s);return n?t?si(n,t):n:null}translatePlurals(e,t,s){const n=this._messages[this._locale];if(!n)return null;let i=ti(e,n);return i=0===(t=parseInt(""+t,10))?i.zero:t>1?i.other:i.one,i?(i=si(i,[t]),s&&(i=si(i,s)),i):null}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==s&&(this._events[e]=t||!0);const n=this._eventSubs[e];if(n)for(const e in n)if(n.hasOwnProperty(e)){n[e].callback(t)}}on(t,s){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let n=this._eventSubs[t];n||(n={},this._eventSubs[t]=n);const i=this._eventSubIDMap.addItem();n[i]={callback:s},this._eventSubEvents[i]=t;const a=this._events[t];return void 0!==a&&s(a),i}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const s=this._eventSubs[t];s&&delete s[e],this._eventSubIDMap.removeItem(e)}}}function ti(e,t){if(t[e])return t[e];const s=e.split(".");let n=t;for(let e=0,t=s.length;n&&e<t;e++){n=n[s[e]]}return n}function si(e,t=[]){return e.replace(/\{\{|\}\}|\{(\d+)\}/g,(function(e,s){return"{{"===e?"{":"}}"===e?"}":t[s]}))}class ni extends C{constructor(e,t={}){super(e,t),this.t=t.t}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get tangent(){return this.getTangent(this._t)}get length(){var e=this._getLengths();return e[e.length-1]}getTangent(e){var t=1e-4;void 0===e&&(e=this._t);var s=e-t,n=e+t;s<0&&(s=0),n>1&&(n=1);var i=this.getPoint(s),a=this.getPoint(n),r=h.subVec3(a,i,[]);return h.normalizeVec3(r,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,s=[];for(t=0;t<=e;t++)s.push(this.getPoint(t/e));return s}_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,s,n=[],i=this.getPoint(0),a=0;for(n.push(0),s=1;s<=e;s++)t=this.getPoint(s/e),a+=h.lenVec3(h.subVec3(t,i,[])),n.push(a),i=t;return this.cacheArcLengths=n,n}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var s,n=this._getLengths(),i=0,a=n.length;s=t||e*n[a-1];for(var r,l=0,o=a-1;l<=o;)if((r=n[i=Math.floor(l+(o-l)/2)]-s)<0)l=i+1;else{if(!(r>0)){o=i;break}o=i-1}if(n[i=o]===s)return i/(a-1);var c=n[i];return(i+(s-c)/(n[i+1]-c))/(a-1)}}class ii extends ni{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 s=(t.length-1)*e,n=Math.floor(s),i=s-n,a=t[0===n?n:n-1],r=t[n],l=t[n>t.length-2?t.length-1:n+1],o=t[n>t.length-3?t.length-1:n+2],c=h.vec3();return c[0]=h.catmullRomInterpolate(a[0],r[0],l[0],o[0],i),c[1]=h.catmullRomInterpolate(a[1],r[1],l[1],o[1],i),c[2]=h.catmullRomInterpolate(a[2],r[2],l[2],o[2],i),c}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 ai=h.vec3();const ri=h.vec3(),li=h.vec3(),oi=h.vec3(),ci=h.vec3(),ui=h.vec3();class hi extends C{get type(){return"CameraFlightAnimation"}constructor(e,t={}){super(e,t),this._look1=h.vec3(),this._eye1=h.vec3(),this._up1=h.vec3(),this._look2=h.vec3(),this._eye2=h.vec3(),this._up2=h.vec3(),this._orthoScale1=1,this._orthoScale2=1,this._flying=!1,this._flyEyeLookUp=!1,this._flyingEye=!1,this._flyingLook=!1,this._callback=null,this._callbackScope=null,this._time1=null,this._time2=null,this.easing=!1!==t.easing,this.duration=t.duration,this.fit=t.fit,this.fitFOV=t.fitFOV,this.trail=t.trail}flyTo(e,t,s){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=s;const n=this.scene.camera,i=!!e.projection&&e.projection!==n.projection;let a,r,l,o,c;if(this._eye1[0]=n.eye[0],this._eye1[1]=n.eye[1],this._eye1[2]=n.eye[2],this._look1[0]=n.look[0],this._look1[1]=n.look[1],this._look1[2]=n.look[2],this._up1[0]=n.up[0],this._up1[1]=n.up[1],this._up1[2]=n.up[2],this._orthoScale1=n.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)a=e.aabb;else if(6===e.length)a=e;else if(e.eye&&e.look||e.up)r=e.eye,l=e.look,o=e.up;else if(e.eye)r=e.eye;else if(e.look)l=e.look;else{let n=e;if((y.isNumeric(n)||y.isString(n))&&(c=n,n=this.scene.components[c],!n))return this.error("Component not found: "+y.inQuotes(c)),void(t&&(s?t.call(s):t()));i||(a=n.aabb||this.scene.aabb)}const u=e.poi;if(a){if(a[3]<a[0]||a[4]<a[1]||a[5]<a[2])return;if(a[3]===a[0]&&a[4]===a[1]&&a[5]===a[2])return;a=a.slice();const t=h.getAABB3Center(a);this._look2=u||t;const s=h.subVec3(this._eye1,this._look1,ri),n=h.normalizeVec3(s),i=u?h.getAABB3DiagPoint(a,u):h.getAABB3Diag(a),r=e.fitFOV||this._fitFOV,l=Math.abs(i/Math.tan(r*h.DEGTORAD));this._orthoScale2=1.1*i,this._eye2[0]=this._look2[0]+n[0]*l,this._eye2[1]=this._look2[1]+n[1]*l,this._eye2[2]=this._look2[2]+n[2]*l,this._up2[0]=this._up1[0],this._up2[1]=this._up1[1],this._up2[2]=this._up1[2],this._flyingEyeLookUp=!0}else(r||l||o)&&(this._flyingEyeLookUp=!!r&&!!l&&!!o,this._flyingEye=!!r&&!l,this._flyingLook=!!l&&!r,r&&(this._eye2[0]=r[0],this._eye2[1]=r[1],this._eye2[2]=r[2]),l&&(this._look2[0]=l[0],this._look2[1]=l[1],this._look2[2]=l[2]),o&&(this._up2[0]=o[0],this._up2[1]=o[1],this._up2[2]=o[2]));i?("ortho"===e.projection&&"ortho"!==n.projection&&(this._projection2="ortho",this._projMatrix1=n.projMatrix.slice(),this._projMatrix2=n.ortho.matrix.slice(),n.projection="customProjection"),"perspective"===e.projection&&"perspective"!==n.projection&&(this._projection2="perspective",this._projMatrix1=n.projMatrix.slice(),this._projMatrix2=n.perspective.matrix.slice(),n.projection="customProjection")):this._projection2=null,this.fire("started",e,!0),this._time1=Date.now(),this._time2=this._time1+(e.duration?1e3*e.duration:this._duration),this._flying=!0,P.scheduleTask(this._update,this)}jumpTo(e){this._jumpTo(e)}_jumpTo(e){this._flying&&this.stop();const t=this.scene.camera;var s,n,i,a,r;if(e.aabb)s=e.aabb;else if(6===e.length)s=e;else if(e.eye||e.look||e.up)i=e.eye,a=e.look,r=e.up;else{let t=e;if((y.isNumeric(t)||y.isString(t))&&(n=t,t=this.scene.components[n],!t))return void this.error("Component not found: "+y.inQuotes(n));s=t.aabb||this.scene.aabb}const l=e.poi;if(s){if(s[3]<=s[0]||s[4]<=s[1]||s[5]<=s[2])return;var o=l?h.getAABB3DiagPoint(s,l):h.getAABB3Diag(s);let n;a=l||h.getAABB3Center(s,a),this._trail?h.subVec3(t.look,a,ui):h.subVec3(t.eye,t.look,ui),h.normalizeVec3(ui);n=(void 0!==e.fit?e.fit:this._fit)?Math.abs(o/Math.tan((e.fitFOV||this._fitFOV)*h.DEGTORAD)):h.lenVec3(h.subVec3(t.eye,t.look,ri)),h.mulVec3Scalar(ui,n),t.eye=h.addVec3(a,ui,ri),t.look=a,this.scene.camera.ortho.scale=1.1*o}else(i||a||r)&&(i&&(t.eye=i),a&&(t.look=a),r&&(t.up=r));e.projection&&(t.projection=e.projection)}_update(){if(!this._flying)return;let e=(Date.now()-this._time1)/(this._time2-this._time1);const t=e>=1;e>1&&(e=1);const s=this.easing?hi._ease(e,0,1,1):e,n=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(h.subVec3(n.eye,n.look,ui),n.eye=h.lerpVec3(s,0,1,this._eye1,this._eye2,oi),n.look=h.subVec3(oi,ui,li)):this._flyingLook&&(n.look=h.lerpVec3(s,0,1,this._look1,this._look2,li),n.up=h.lerpVec3(s,0,1,this._up1,this._up2,ci)):this._flyingEyeLookUp&&(n.eye=h.lerpVec3(s,0,1,this._eye1,this._eye2,oi),n.look=h.lerpVec3(s,0,1,this._look1,this._look2,li),n.up=h.lerpVec3(s,0,1,this._up1,this._up2,ci)),this._projection2){const t="ortho"===this._projection2?hi._easeOutExpo(e,0,1,1):hi._easeInCubic(e,0,1,1);n.customProjection.matrix=h.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else n.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return n.ortho.scale=this._orthoScale2,void this.stop();P.scheduleTask(this._update,this)}static _ease(e,t,s,n){return-s*(e/=n)*(e-2)+t}static _easeInCubic(e,t,s,n){return s*(e/=n)*e*e+t}static _easeOutExpo(e,t,s,n){return s*(1-Math.pow(2,-10*e/n))+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 pi extends C{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new hi(this),this._t=0,this.state=pi.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,s;const n=performance.now(),i=this._lastTime?.001*(n-this._lastTime):0;if(this._lastTime=n,0!==i)switch(this.state){case pi.SCRUBBING:return;case pi.PLAYING:if(this._t+=this._playingRate*i,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=pi.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case pi.PLAYING_TO:s=this._t+this._playingRate*i*this._playingDir,(this._playingDir<0&&s<=this._playingToT||this._playingDir>0&&s>=this._playingToT)&&(s=this._playingToT,this.state=pi.SCRUBBING,this.fire("stopped")),this._t=s,e.loadFrame(this._t)}}_ease(e,t,s,n){return-s*(e/=n)*(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=pi.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=pi.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const s=t.frames[e];s?this.playToT(s.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const s=this._cameraPath;if(!s)return;const n=s.frames[e];n?(this.state=pi.SCRUBBING,this._cameraFlightAnimation.flyTo(n,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=pi.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=pi.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=pi.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}pi.STOPPED=0,pi.SCRUBBING=1,pi.PLAYING=2,pi.PLAYING_TO=3;const Ai=h.vec3(),di=h.vec3();h.vec3();const fi=h.vec3([0,-1,0]),Ii=h.vec4([0,0,0,1]);function yi(e){if(!mi(e.width)||!mi(e.height)){const t=document.createElement("canvas");t.width=vi(e.width),t.height=vi(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function mi(e){return 0==(e&e-1)}function vi(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class wi extends C{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const s=this.scene.canvas.gl;this._state=new Ve({texture:new Rn({gl:s,target:s.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),A.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,s=this.scene.canvas.gl;this._images=[];let n=!1,i=0;for(let a=0;a<e.length;a++){const r=new Image;r.onload=function(){let e=r;const l=a;return function(){if(!n&&(e=yi(e),t._images[l]=e,i++,6===i)){let e=t._state.texture;e||(e=new Rn({gl:s,target:s.TEXTURE_CUBE_MAP}),t._state.texture=e),e.setImage(t._images,t._state),t.fire("loaded",t._src,!1),t.glRedraw()}}}(),r.onerror=function(){n=!0},r.src=e[a]}}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),A.memory.textures--,this._state.destroy()}}const gi=h.vec3();const Ti=h.vec3();class Ei{constructor(e,t,s,n,i=null,a=0){this.model=e,this.object=null,this.parent=null,this.id=t,this.aabb=null,this.layer=i,this.portionId=a,this._color=[s[0],s[1],s[2],n],this._colorize=[s[0],s[1],s[2],n],this._colorizing=!1,this._transparent=n<255,this.numTriangles=0,this.origin=null}_finalize(e){this.layer.initFlags(this.portionId,e,this._transparent)}_finalize2(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}_setVisible(e){this.layer.setVisible(this.portionId,e,this._transparent)}_setColor(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this.layer.setColor(this.portionId,this._color,!1)}_setColorize(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this.layer.setColor(this.portionId,this._colorize,false),this._colorizing=!0):(this.layer.setColor(this.portionId,this._color,false),this._colorizing=!1)}_setOpacity(e,t){const s=e<255,n=this._transparent!==s;this._color[3]=e,this._colorize[3]=e,this._transparent=s,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),n&&this.layer.setTransparent(this.portionId,t,s)}_setOffset(e){this.layer.setOffset(this.portionId,e)}_setHighlighted(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}_setXRayed(e){this.layer.setXRayed(this.portionId,e,this._transparent)}_setSelected(e){this.layer.setSelected(this.portionId,e,this._transparent)}_setEdges(e){this.layer.setEdges(this.portionId,e,this._transparent)}_setClippable(e){this.layer.setClippable(this.portionId,e,this._transparent)}_setCollidable(e){this.layer.setCollidable(this.portionId,e)}_setPickable(e){this.layer.setPickable(this.portionId,e,this._transparent)}_setCulled(e){this.layer.setCulled(this.portionId,e,this._transparent)}canPickTriangle(){return!1}drawPickTriangles(e,t){}pickTriangleSurface(e){}precisionRayPickSurface(e,t,s,n){return!!this.layer.precisionRayPickSurface&&this.layer.precisionRayPickSurface(this.portionId,e,t,s,n)}canPickWorldPos(){return!0}drawPickDepths(e){this.model.drawPickDepths(e)}drawPickNormals(e){this.model.drawPickNormals(e)}delegatePickedEntity(){return this.parent}getEachVertex(e){this.layer.getEachVertex(this.portionId,e)}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const bi=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 Di=0;const Pi={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},Ri=new Float32Array([1,1,1,1]),Ci=new Float32Array([0,0,0,1]),_i=h.vec4(),Bi=h.vec3();class Oi{constructor(e,t=!1,{instancing:s=!1,edges:n=!1}={}){this._scene=e,this._withSAO=t,this._instancing=s,this._edges=n,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}getValid(){return this._hash===this._getHash()}setSectionPlanesStateUniforms(e){const t=this._scene,{gl:s}=t.canvas,{model:n,layerIndex:i}=e,a=t._sectionPlanesState.sectionPlanes.length;if(a>0){const r=t._sectionPlanesState.sectionPlanes,l=i*a,o=n.renderFlags;for(let t=0;t<a;t++){const n=this._uSectionPlanes[t];if(n){const i=o.sectionPlanesActivePerLayer[l+t];if(s.uniform1i(n.active,i?1:0),i){const i=r[t],a=e._state.origin;if(a){const e=N(i.dist,i.dir,a,Bi);s.uniform3fv(n.pos,e)}else s.uniform3fv(n.pos,i.pos);s.uniform3fv(n.dir,i.dir)}}}}}_allocate(){const e=this._scene,t=e.canvas.gl,s=e._lightsState;if(this._program=new we(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uColor=n.getLocation("color"),this._uColor||(this._uColor=n.getLocation("silhouetteColor")),this._uUVDecodeMatrix=n.getLocation("uvDecodeMatrix"),this._uPickInvisible=n.getLocation("pickInvisible"),this._uGammaFactor=n.getLocation("gammaFactor"),t.uniformBlockBinding(n.handle,t.getUniformBlockIndex(n.handle,"Matrices"),this._matricesUniformBlockBufferBindingPoint),this._uShadowViewMatrix=n.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=n.getLocation("shadowProjMatrix"),e.logarithmicDepthBufferEnabled&&(this._uZFar=n.getLocation("zFar")),this._uLightAmbient=n.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const i=s.lights;let a;for(let e=0,t=i.length;e<t;e++)switch(a=i[e],a.type){case"dir":this._uLightColor[e]=n.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=n.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=n.getLocation("lightColor"+e),this._uLightPos[e]=n.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=n.getLocation("lightAttenuation"+e);break;case"spot":this._uLightColor[e]=n.getLocation("lightColor"+e),this._uLightPos[e]=n.getLocation("lightPos"+e),this._uLightDir[e]=n.getLocation("lightDir"+e),this._uLightAttenuation[e]=n.getLocation("lightAttenuation"+e)}s.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),s.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+t),pos:n.getLocation("sectionPlanePos"+t),dir:n.getLocation("sectionPlaneDir"+t)});this._aPosition=n.getAttribute("position"),this._aOffset=n.getAttribute("offset"),this._aNormal=n.getAttribute("normal"),this._aUV=n.getAttribute("uv"),this._aColor=n.getAttribute("color"),this._aMetallicRoughness=n.getAttribute("metallicRoughness"),this._aFlags=n.getAttribute("flags"),this._aPickColor=n.getAttribute("pickColor"),this._uPickZNear=n.getLocation("pickZNear"),this._uPickZFar=n.getLocation("pickZFar"),this._uColorMap="uColorMap",this._uMetallicRoughMap="uMetallicRoughMap",this._uEmissiveMap="uEmissiveMap",this._uNormalMap="uNormalMap",this._uAOMap="uAOMap",this._instancing&&(this._aModelMatrixCol0=n.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=n.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=n.getAttribute("modelMatrixCol2"),this._aModelNormalMatrixCol0=n.getAttribute("modelNormalMatrixCol0"),this._aModelNormalMatrixCol1=n.getAttribute("modelNormalMatrixCol1"),this._aModelNormalMatrixCol2=n.getAttribute("modelNormalMatrixCol2")),this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=n.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),e.pointsMaterial._state.filterIntensity&&(this._uIntensityRange=n.getLocation("intensityRange")),this._uPointSize=n.getLocation("pointSize"),this._uNearPlaneHeight=n.getLocation("nearPlaneHeight")}_bindProgram(e){const t=this._scene,s=t.canvas.gl,n=this._program,i=t._lightsState,a=i.lights,r=t.camera.project;n.bind(),e.textureUnit=0,this._uLightAmbient&&s.uniform4fv(this._uLightAmbient,i.getAmbientColorAndIntensity());for(let e=0,t=a.length;e<t;e++){const t=a[e];this._uLightColor[e]&&s.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(s.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&s.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&s.uniform3fv(this._uLightDir[e],t.dir)}if(this._withSAO){const n=t.sao;if(n.possible){const t=s.drawingBufferWidth,i=s.drawingBufferHeight;_i[0]=t,_i[1]=i,_i[2]=n.blendCutoff,_i[3]=n.blendFactor,s.uniform4fv(this._uSAOParams,_i),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,0)}}if(t.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}this._uGammaFactor&&s.uniform1f(this._uGammaFactor,t.gammaFactor),this._uPickInvisible&&s.uniform1i(this._uPickInvisible,e.pickInvisible),this._uShadowViewMatrix&&s.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),this._uShadowProjMatrix&&s.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix)}_makeVAO(e){const t=this._scene.canvas.gl,s=t.createVertexArray();return t.bindVertexArray(s),this._instancing&&(this._aModelMatrixCol0.bindArrayBuffer(e.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(e.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(e.modelMatrixCol2Buf),t.vertexAttribDivisor(this._aModelMatrixCol0.location,1),t.vertexAttribDivisor(this._aModelMatrixCol1.location,1),t.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aModelNormalMatrixCol0&&(this._aModelNormalMatrixCol0.bindArrayBuffer(e.modelNormalMatrixCol0Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol0.location,1)),this._aModelNormalMatrixCol1&&(this._aModelNormalMatrixCol1.bindArrayBuffer(e.modelNormalMatrixCol1Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol1.location,1)),this._aModelNormalMatrixCol2&&(this._aModelNormalMatrixCol2.bindArrayBuffer(e.modelNormalMatrixCol2Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol2.location,1))),this._aPosition.bindArrayBuffer((this._instancing,e.positionsBuf)),this._aUV&&this._aUV.bindArrayBuffer((this._instancing,e.uvBuf)),this._aNormal&&this._aNormal.bindArrayBuffer((this._instancing,e.normalsBuf)),this._aMetallicRoughness&&(this._aMetallicRoughness.bindArrayBuffer(e.metallicRoughnessBuf),this._instancing&&t.vertexAttribDivisor(this._aMetallicRoughness.location,1)),this._aColor&&(this._aColor.bindArrayBuffer((e.colorsBuf,e.colorsBuf)),this._instancing&&e.colorsBuf&&t.vertexAttribDivisor(this._aColor.location,1)),this._aFlags&&(this._aFlags.bindArrayBuffer(e.flagsBuf),this._instancing&&t.vertexAttribDivisor(this._aFlags.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(e.offsetsBuf),this._instancing&&t.vertexAttribDivisor(this._aOffset.location,1)),this._aPickColor&&(this._aPickColor.bindArrayBuffer(e.pickColorsBuf),this._instancing&&t.vertexAttribDivisor(this._aPickColor.location,1)),this._instancing,this._edges?e.edgeIndicesBuf.bind():e.indicesBuf&&e.indicesBuf.bind(),s}drawLayer(e,t,s,{colorUniform:n=!1,incrementDrawState:i=!1}={}){const a=oe.MAX_TEXTURE_IMAGE_UNITS,r=this._scene,l=r.canvas.gl,{_state:o,model:c}=t,{textureSet:u,origin:h,positionsDecodeMatrix:p}=o,A=r._lightsState,d=r.pointsMaterial,{camera:f}=c.scene,{viewNormalMatrix:I,project:y}=f,m=e.pickViewMatrix||f.viewMatrix,{worldMatrix:v,worldNormalMatrix:w}=c;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),this._vaoCache.has(t)?l.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(o));let g=0;if(this._matricesUniformBlockBufferData.set(v,0),this._matricesUniformBlockBufferData.set(h?B(m,h):m,g+=16),this._matricesUniformBlockBufferData.set(e.pickProjMatrix||y.matrix,g+=16),this._matricesUniformBlockBufferData.set(p,g+=16),this._matricesUniformBlockBufferData.set(w,g+=16),this._matricesUniformBlockBufferData.set(I,g+=16),l.bindBuffer(l.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),l.bufferData(l.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,l.DYNAMIC_DRAW),l.bindBufferBase(l.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer),l.uniform1i(this._uRenderPass,s),this.setSectionPlanesStateUniforms(t),r.logarithmicDepthBufferEnabled){if(this._uLogDepthBufFC){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,t)}this._uZFar&&l.uniform1f(this._uZFar,r.camera.project.far)}if(this._uPickInvisible&&l.uniform1i(this._uPickInvisible,e.pickInvisible),this._uPickZNear&&l.uniform1f(this._uPickZNear,e.pickZNear),this._uPickZFar&&l.uniform1f(this._uPickZFar,e.pickZFar),this._uPositionsDecodeMatrix&&l.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,o.positionsDecodeMatrix),this._uUVDecodeMatrix&&l.uniformMatrix3fv(this._uUVDecodeMatrix,!1,(this._instancing,o.uvDecodeMatrix)),this._uIntensityRange&&d.filterIntensity&&l.uniform2f(this._uIntensityRange,d.minIntensity,d.maxIntensity),this._uPointSize&&l.uniform1f(this._uPointSize,d.pointSize),this._uNearPlaneHeight){const e="ortho"===r.camera.projection?1:l.drawingBufferHeight/(2*Math.tan(.5*r.camera.perspective.fov*Math.PI/180));l.uniform1f(this._uNearPlaneHeight,e)}if(u){const{colorTexture:t,metallicRoughnessTexture:s,emissiveTexture:n,normalsTexture:i,occlusionTexture:r}=u;this._uColorMap&&t&&(this._program.bindTexture(this._uColorMap,t.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uMetallicRoughMap&&s&&(this._program.bindTexture(this._uMetallicRoughMap,s.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uEmissiveMap&&n&&(this._program.bindTexture(this._uEmissiveMap,n.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uNormalMap&&i&&(this._program.bindTexture(this._uNormalMap,i.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uAOMap&&r&&(this._program.bindTexture(this._uAOMap,r.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a)}if(A.reflectionMaps.length>0&&A.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,A.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a,e.bindTexture++),A.lightMaps.length>0&&A.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,A.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a,e.bindTexture++),this._withSAO){const t=r.sao;if(t.possible){const s=l.drawingBufferWidth,n=l.drawingBufferHeight;_i[0]=s,_i[1]=n,_i[2]=t.blendCutoff,_i[3]=t.blendFactor,l.uniform4fv(this._uSAOParams,_i),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a,e.bindTexture++}}if(n){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(s===Pi[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const s=r.xrayMaterial._state,n=s[e],i=s[t];l.uniform4f(this._uColor,n[0],n[1],n[2],i)}else if(s===Pi[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const s=r.highlightMaterial._state,n=s[e],i=s[t];l.uniform4f(this._uColor,n[0],n[1],n[2],i)}else if(s===Pi[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const s=r.selectedMaterial._state,n=s[e],i=s[t];l.uniform4f(this._uColor,n[0],n[1],n[2],i)}else l.uniform4fv(this._uColor,this._edges?Ci:Ri)}this._draw({state:o,frameCtx:e,incrementDrawState:i}),l.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,A.memory.programs--}}class Si extends Oi{constructor(e,t,{instancing:s=!1,edges:n=!1}={}){super(e,t,{instancing:s,edges:n})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;if(this._edges)t.drawElements(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0);else{const e=n.pickElementsCount||s.indicesBuf.numItems,a=n.pickElementsOffset?n.pickElementsOffset*s.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,s.indicesBuf.itemType,a),i&&n.drawElements++}}}class Ni extends Si{constructor(e,t){super(e,t,{instancing:!1,edges:!0})}}class xi extends Oi{constructor(e,t,{edges:s=!1}={}){super(e,t,{instancing:!0,edges:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;this._edges?t.drawElementsInstanced(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0,s.numInstances):(t.drawElementsInstanced(t.TRIANGLES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),i&&n.drawElements++)}}class Li extends xi{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class Mi extends Oi{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawArrays(t.POINTS,0,s.positionsBuf.numItems),i&&n.drawArrays++}}class Fi extends Oi{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawArraysInstanced(t.POINTS,0,s.positionsBuf.numItems,s.numInstances),i&&n.drawArrays++}}class Hi extends Oi{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawElements(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0),i&&n.drawElements++}}class Ui extends Oi{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawElementsInstanced(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),i&&n.drawElements++}}class Gi extends Si{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0;let i;const a=[];a.push("#version 300 es"),a.push("// Triangles batching draw vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec3 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),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;");for(let e=0,t=s.lights.length;e<t;e++)i=s.lights[e],"ambient"!==i.type&&(a.push("uniform vec4 lightColor"+e+";"),"dir"===i.type&&a.push("uniform vec3 lightDir"+e+";"),"point"===i.type&&a.push("uniform vec3 lightPos"+e+";"),"spot"===i.type&&(a.push("uniform vec3 lightPos"+e+";"),a.push("uniform vec3 lightDir"+e+";")));a.push("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),n&&(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 = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),a.push("vec3 viewNormal = normalize((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;");for(let e=0,t=s.lights.length;e<t;e++)if(i=s.lights[e],"ambient"!==i.type){if("dir"===i.type)"view"===i.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===i.type)"view"===i.space?a.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):a.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==i.type)continue;"view"===i.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}a.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),a.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}return a.push("vec3 rgb = (vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0));"),a.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),a.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(a.push("vFragDepth = 1.0 + clipPos.w;"),a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags = flags;")),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching 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;")),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){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):n.push(" outColor = vColor;"),n.push("}"),n}}class Vi extends Si{_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.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching flat-shading draw vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._lightsState,s=e._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),n){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}this._addMatricesUniformBlockLines(i),i.push("uniform vec4 lightAmbient;");for(let e=0,s=t.lights.length;e<s;e++){const s=t.lights[e];"ambient"!==s.type&&(i.push("uniform vec4 lightColor"+e+";"),"dir"===s.type&&i.push("uniform vec3 lightDir"+e+";"),"point"===s.type&&i.push("uniform vec3 lightPos"+e+";"),"spot"===s.type&&(i.push("uniform vec3 lightPos"+e+";"),i.push("uniform vec3 lightDir"+e+";")))}if(i.push("in vec4 vViewPosition;"),i.push("in vec4 vColor;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}i.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),i.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),i.push("float lambertian = 1.0;"),i.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),i.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),i.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,s=t.lights.length;e<s;e++){const s=t.lights[e];if("ambient"!==s.type){if("dir"===s.type)"view"===s.space?i.push("viewLightDir = normalize(lightDir"+e+");"):i.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===s.type)"view"===s.space?i.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):i.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==s.type)continue;"view"===s.space?i.push("viewLightDir = normalize(lightDir"+e+");"):i.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}i.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),i.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return i.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(fragColor.rgb * ambient, 1.0);")):i.push(" outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class ji extends Si{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Triangles batching silhouette fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}return e.logarithmicDepthBufferEnabled&&a.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("outColor = vColor;"),a.push("}"),a}}class ki extends Ni{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class Qi extends Ni{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class Wi extends Si{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry picking 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("in vec4 vPickColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vPickColor; "),n.push("}"),n}}class zi extends Si{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching pick depth 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 float pickZNear;"),n.push("uniform float pickZFar;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("in vec4 vViewPosition;"),n.push("vec4 packDepth(const in float depth) {"),n.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),n.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),n.push(" vec4 res = fract(depth * bitShift);"),n.push(" res -= res.xxyz * bitMask;"),n.push(" return res;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class Ki extends Si{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec3 worldNormal = octDecode(normal.xy); "),s.push(" vWorldNormal = worldNormal;"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching pick normals 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("in vec3 vWorldNormal;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),n.push("}"),n}}class Yi extends Si{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching occlusion 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),n.push("}"),n}}class Xi extends Si{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching depth fragment shader"),n.push("precision highp float;"),n.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(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("const float shiftRight8 = 1.0 / 256.;"),n.push("vec4 packDepthToRGBA( const in float v ) {"),n.push(" vec4 r = vec4( fract( v * packFactors ), v );"),n.push(" r.yzw -= r.xyz * shiftRight8;"),n.push(" return r * packUpScale;"),n.push("}"),n.push("in vec2 vHighPrecisionZW;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),n.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),n.push("}"),n}}class qi extends Si{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry normals 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}class Ji extends Si{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry shadow vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" int colorFlag = int(flags) & 0xF;"),s.push(" bool visible = (colorFlag > 0);"),s.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push(" if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry shadow fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("in vec4 vViewPosition;"),s.push("vec4 encodeFloat( const in float v ) {"),s.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),s.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),s.push(" vec4 comp = fract(v * bitShift);"),s.push(" comp -= comp.xxyz * bitMask;"),s.push(" return comp;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),t){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n<e.sectionPlanes.length;n++)s.push(" if (sectionPlaneActive"+n+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = encodeFloat( gl_FragCoord.z); "),s.push("}"),s}}class Zi extends Si{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0,i=t.clippingCaps,a=[];return a.push("#version 300 es"),a.push("// Triangles batching quality draw vertex shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("precision highp usampler2D;"),a.push("precision highp isampler2D;"),a.push("precision highp sampler2D;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("precision mediump usampler2D;"),a.push("precision mediump isampler2D;"),a.push("precision mediump sampler2D;"),a.push("#endif"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec3 normal;"),a.push("in vec4 color;"),a.push("in vec2 uv;"),a.push("in vec2 metallicRoughness;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),this._addMatricesUniformBlockLines(a,!0),a.push("uniform mat3 uvDecodeMatrix;"),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("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),a.push("out vec4 vViewPosition;"),a.push("out vec3 vViewNormal;"),a.push("out vec4 vColor;"),a.push("out vec2 vUV;"),a.push("out vec2 vMetallicRoughness;"),s.lightMaps.length>0&&a.push("out vec3 vWorldNormal;"),n&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;"),i&&a.push("out vec4 vClipPosition;")),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 = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),a.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),a.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),a.push("vFragDepth = 1.0 + clipPos.w;")),n&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags = flags;"),i&&a.push("vClipPosition = clipPos;")),a.push("vViewPosition = viewPosition;"),a.push("vViewNormal = viewNormal;"),a.push("vColor = color;"),a.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),a.push("vMetallicRoughness = metallicRoughness;"),s.lightMaps.length>0&&a.push("vWorldNormal = worldNormal.xyz;"),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,n=e._lightsState,i=s.sectionPlanes.length>0,a=s.clippingCaps,r=[];r.push("#version 300 es"),r.push("// Triangles batching quality 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;")),r.push("uniform sampler2D uColorMap;"),r.push("uniform sampler2D uMetallicRoughMap;"),r.push("uniform sampler2D uEmissiveMap;"),r.push("uniform sampler2D uNormalMap;"),r.push("uniform sampler2D uAOMap;"),r.push("in vec4 vViewPosition;"),r.push("in vec3 vViewNormal;"),r.push("in vec4 vColor;"),r.push("in vec2 vUV;"),r.push("in vec2 vMetallicRoughness;"),n.lightMaps.length>0&&r.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(r,!0),n.reflectionMaps.length>0&&r.push("uniform samplerCube reflectionMap;"),n.lightMaps.length>0&&r.push("uniform samplerCube lightMap;"),r.push("uniform vec4 lightAmbient;");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];"ambient"!==t.type&&(r.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&r.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&r.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(r.push("uniform vec3 lightPos"+e+";"),r.push("uniform vec3 lightDir"+e+";")))}if(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("}")),r.push("uniform float gammaFactor;"),r.push("vec4 linearToLinear( in vec4 value ) {"),r.push(" return value;"),r.push("}"),r.push("vec4 sRGBToLinear( in vec4 value ) {"),r.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 );"),r.push("}"),r.push("vec4 gammaToLinear( in vec4 value) {"),r.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),r.push("}"),t&&(r.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),r.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),r.push("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;"),a&&r.push("in vec4 vClipPosition;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}if(r.push("#define PI 3.14159265359"),r.push("#define RECIPROCAL_PI 0.31830988618"),r.push("#define RECIPROCAL_PI2 0.15915494"),r.push("#define EPSILON 1e-6"),r.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),r.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),r.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),r.push(" if (texel.x == 0.0 && texel.y == 0.0 && texel.z == 0.0) {"),r.push(" return surf_norm;"),r.push(" }"),r.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),r.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),r.push(" vec2 st0 = dFdx( uv.st );"),r.push(" vec2 st1 = dFdy( uv.st );"),r.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),r.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),r.push(" vec3 N = normalize( surf_norm );"),r.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),r.push(" mat3 tsn = mat3( S, T, N );"),r.push(" return normalize( tsn * mapN );"),r.push("}"),r.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),r.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),r.push("}"),r.push("struct IncidentLight {"),r.push(" vec3 color;"),r.push(" vec3 direction;"),r.push("};"),r.push("struct ReflectedLight {"),r.push(" vec3 diffuse;"),r.push(" vec3 specular;"),r.push("};"),r.push("struct Geometry {"),r.push(" vec3 position;"),r.push(" vec3 viewNormal;"),r.push(" vec3 worldNormal;"),r.push(" vec3 viewEyeDir;"),r.push("};"),r.push("struct Material {"),r.push(" vec3 diffuseColor;"),r.push(" float specularRoughness;"),r.push(" vec3 specularColor;"),r.push(" float shine;"),r.push("};"),r.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),r.push(" float r = ggxRoughness + 0.0001;"),r.push(" return (2.0 / (r * r) - 2.0);"),r.push("}"),r.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),r.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),r.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),r.push("}"),n.reflectionMaps.length>0&&(r.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),r.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),r.push(" return envMapColor;"),r.push("}")),r.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),r.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),r.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),r.push("}"),r.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" return 1.0 / ( gl * gv );"),r.push("}"),r.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" return 0.5 / max( gv + gl, EPSILON );"),r.push("}"),r.push("float D_GGX(const in float alpha, const in float dotNH) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),r.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float alpha = ( roughness * roughness );"),r.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),r.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),r.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),r.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),r.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),r.push(" vec3 F = F_Schlick( specularColor, dotLH );"),r.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),r.push(" float D = D_GGX( alpha, dotNH );"),r.push(" return F * (G * D);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),r.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),r.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),r.push(" vec4 r = roughness * c0 + c1;"),r.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),r.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),r.push(" return specularColor * AB.x + AB.y;"),r.push("}"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&(r.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.lightMaps.length>0&&(r.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),r.push(" irradiance *= PI;"),r.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),n.reflectionMaps.length>0&&(r.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),r.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),r.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),r.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),r.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),r.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),r.push("}")),r.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),r.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),r.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),r.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");a?(r.push(" if (dist > (0.002 * vClipPosition.w)) {"),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" return;"),r.push("}")):(r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }")),r.push("}")}r.push("IncidentLight light;"),r.push("Material material;"),r.push("Geometry geometry;"),r.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),r.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),r.push("float opacity = float(vColor.a) / 255.0;"),r.push("vec3 baseColor = rgb;"),r.push("float specularF0 = 1.0;"),r.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),r.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),r.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),r.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),r.push("baseColor *= colorTexel.rgb;"),r.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),r.push("metallic *= metalRoughTexel.b;"),r.push("roughness *= metalRoughTexel.g;"),r.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),r.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),r.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),r.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),r.push("geometry.position = vViewPosition.xyz;"),r.push("geometry.viewNormal = -normalize(viewNormal);"),r.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),n.lightMaps.length>0&&r.push("geometry.worldNormal = normalize(vWorldNormal);"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&r.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?r.push("light.direction = normalize(lightPos"+e+" - vViewPosition.xyz);"):r.push("light.direction = normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}r.push("light.color = lightColor"+e+".rgb * lightColor"+e+".a;"),r.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return r.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;"),r.push("float aoFactor = texture(uAOMap, vUV).r;"),r.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;"),r.push("vec4 fragColor;"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" fragColor = vec4(outgoingLight.rgb * ambient * aoFactor, opacity);")):r.push(" fragColor = vec4(outgoingLight.rgb * aoFactor, opacity);"),t&&r.push("fragColor = linearToGamma(fragColor, gammaFactor);"),r.push("outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}class $i extends Si{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick flat normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching pick flat normals 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("in vec4 vWorldPosition;"),s){n.push("in float vFlags;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),n.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),n.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),n.push(" outColor = vec4((worldNormal * 0.5) + 0.5, 1.0);"),n.push("}"),n}}class ea extends Si{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching color texture vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._lightsState,n=e._sectionPlanesState,i=n.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Triangles batching color texture fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),i){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(let e=0,t=n.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}this._addMatricesUniformBlockLines(a),a.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(a.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&a.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&a.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(a.push("uniform vec3 lightPos"+e+";"),a.push("uniform vec3 lightDir"+e+";")))}if(a.push("in vec4 vViewPosition;"),a.push("in vec4 vColor;"),a.push("in vec2 vUV;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=n.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { "),a.push(" discard;"),a.push(" }"),a.push("}")}a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?a.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):a.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}a.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),a.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return a.push("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),t?a.push("vec4 colorTexel = color * sRGBToLinear(texture(uColorMap, vUV));"):a.push("vec4 colorTexel = color * texture(uColorMap, vUV);"),a.push("float opacity = color.a;"),this._withSAO?(a.push(" float viewportWidth = uSAOParams[0];"),a.push(" float viewportHeight = uSAOParams[1];"),a.push(" float blendCutoff = uSAOParams[2];"),a.push(" float blendFactor = uSAOParams[3];"),a.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),a.push(" outColor = vec4(colorTexel.rgb * ambient, opacity);")):a.push(" outColor = vec4(colorTexel.rgb, opacity);"),t&&a.push("outColor = linearToGamma(outColor, gammaFactor);"),e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}}class ta{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._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)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Gi(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Gi(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Vi(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Vi(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new ea(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new ea(this._scene,!0)),this._colorTextureRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new Zi(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Zi(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new ji(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Xi(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new qi(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new ki(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Qi(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Wi(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Ki(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new $i(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new zi(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Yi(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Ji(this._scene)),this._shadowRenderer}_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._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()}}const sa={};class na{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const ia=h.mat4(),aa=h.mat4();function ra(e,t,s){const n=e.length,i=new Uint16Array(n),a=t[0],r=t[1],l=t[2],o=t[3]-a,c=t[4]-r,u=t[5]-l,p=65525,A=p/o,d=p/c,f=p/u,I=e=>e>=0?e:0;for(let t=0;t<n;t+=3)i[t+0]=Math.floor(I(e[t+0]-a)*A),i[t+1]=Math.floor(I(e[t+1]-r)*d),i[t+2]=Math.floor(I(e[t+2]-l)*f);return h.identityMat4(ia),h.translationMat4v(t,ia),h.identityMat4(aa),h.scalingMat4v([o/p,c/p,u/p],aa),h.mulMat4(ia,aa,s),i}function la(e,t){const s=e[0],n=e[1],i=e[2],a=e[3]-s,r=e[4]-n,l=e[5]-i,o=65525;return h.identityMat4(ia),h.translationMat4v(e,ia),h.identityMat4(aa),h.scalingMat4v([a/o,r/o,l/o],aa),h.mulMat4(ia,aa,t),t}function oa(e,t,s){let n=e[0]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2])),i=e[1]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2]));if(e[2]<0){let e=n,t=i;e=(1-Math.abs(i))*(n>=0?1:-1),t=(1-Math.abs(n))*(i>=0?1:-1),n=e,i=t}return new Int8Array([Math[t](127.5*n+(n<0?-1:0)),Math[s](127.5*i+(i<0?-1:0))])}function ca(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const n=1-Math.abs(t)-Math.abs(s);n<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const i=Math.sqrt(t*t+s*s+n*n);return[t/i,s/i,n/i]}const ua=h.vec3();class ha{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,s){const n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=t._state.origin;let c=a.eye;e.snapPickOrigin[0]=o[0],e.snapPickOrigin[1]=o[1],e.snapPickOrigin[2]=o[2];const u=t.aabb,p=[h.safeInv(u[3]-u[0])*h.MAX_INT,h.safeInv(u[4]-u[1])*h.MAX_INT,h.safeInv(u[5]-u[2])*h.MAX_INT];if(e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),e.pickViewMatrix&&(c=e.pickOrigin||c);const A=[c[0]-o[0],c[1]-o[1],c[2]-o[2]];r.uniform3fv(this._uCameraEyeRtc,A),r.uniform2fv(this.uVectorA,e.snapVectorA),r.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),r.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),r.uniform3fv(this._uCoordinateScaler,p),r.uniform1i(this._uRenderPass,s),r.uniform1i(this._uPickInvisible,e.pickInvisible),r.uniform1i(this._uSolid,t.solid);const d=e.pickViewMatrix||a.viewMatrix,f=o?B(d,o):d;if(r.uniformMatrix4fv(this._uWorldMatrix,!1,n.worldMatrix),r.uniformMatrix4fv(this._uViewMatrix,!1,f),r.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}const I=i._sectionPlanesState.sectionPlanes.length;if(I>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,a=n.renderFlags;for(let t=0;t<I;t++){const n=this._uSectionPlanes[t];if(n){const i=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,i?1:0),i){const s=e[t];if(o){const e=N(s.dist,s.dir,o,ua);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}r.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(l.positionsBuf),this._aOffset&&this._aOffset.bindArrayBuffer(l.offsetsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(l.flagsBuf),l.indicesBuf.bind(),r.drawElements(r.TRIANGLES,l.indicesBuf.numItems,l.indicesBuf.itemType,0),l.indicesBuf.unbind()}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new we(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uSolid=s.getLocation("solid"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aFlags=s.getAttribute("flags"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this.uVectorA=s.getLocation("snapVectorA"),this.uInverseVectorAB=s.getLocation("snapInvVectorAB"),this._uLayerNumber=s.getLocation("layerNumber"),this._uCoordinateScaler=s.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),s.push("uniform bool solid;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.z += 0.0001;"),s.push("clipPos.xyzw *= tmp;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// VBO SnapBatchingDepthBufInitRenderer 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 int layerNumber;"),n.push("uniform vec3 coordinateScaler;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in highp vec3 relativeToOriginPosition;"),n.push("out highp ivec4 outCoords;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const pa=h.vec3();class Aa{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){const n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=t._state.origin;e.snapPickOrigin[0]=o[0],e.snapPickOrigin[1]=o[1],e.snapPickOrigin[2]=o[2];const c=t.aabb,u=[h.safeInv(c[3]-c[0])*h.MAX_INT,h.safeInv(c[4]-c[1])*h.MAX_INT,h.safeInv(c[5]-c[2])*h.MAX_INT];if(e.snapPickCoordinateScale[0]=h.safeInv(u[0]),e.snapPickCoordinateScale[1]=h.safeInv(u[1]),e.snapPickCoordinateScale[2]=h.safeInv(u[2]),!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());let p=a.eye;e.pickViewMatrix&&(p=e.pickOrigin||p);const A=[p[0]-o[0],p[1]-o[1],p[2]-o[2]];r.uniform3fv(this._uCameraEyeRtc,A),r.uniform2fv(this.uVectorA,e.snapVectorA),r.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),r.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),r.uniform3fv(this._uCoordinateScaler,u),r.uniform1i(this._uRenderPass,s),r.uniform1i(this._uPickInvisible,e.pickInvisible);const d=e.pickViewMatrix||a.viewMatrix,f=o?B(d,o):d;if(r.uniformMatrix4fv(this._uWorldMatrix,!1,n.worldMatrix),r.uniformMatrix4fv(this._uViewMatrix,!1,f),r.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}const I=i._sectionPlanesState.sectionPlanes.length;if(I>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,a=n.renderFlags;for(let t=0;t<I;t++){const n=this._uSectionPlanes[t];if(n){const i=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,i?1:0),i){const s=e[t];if(o){const e=N(s.dist,s.dir,o,pa);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}r.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(l.positionsBuf),this._aOffset&&this._aOffset.bindArrayBuffer(l.offsetsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(l.flagsBuf),"edge"===e.snapMode?(l.edgeIndicesBuf.bind(),r.drawElements(r.LINES,l.edgeIndicesBuf.numItems,l.edgeIndicesBuf.itemType,0),l.edgeIndicesBuf.unbind()):r.drawArrays(r.POINTS,0,l.positionsBuf.numItems)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new we(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aFlags=s.getAttribute("flags"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this.uVectorA=s.getLocation("snapVectorA"),this.uInverseVectorAB=s.getLocation("snapInvVectorAB"),this._uLayerNumber=s.getLocation("layerNumber"),this._uCoordinateScaler=s.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0;e.pointsMaterial._state;const s=[];return s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// SnapBatchingDepthRenderer 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 int layerNumber;"),n.push("uniform vec3 coordinateScaler;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in highp vec3 relativeToOriginPosition;"),n.push("out highp ivec4 outCoords;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class da{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new ha(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new Aa(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const fa={};const Ia=h.mat4(),ya=h.mat4(),ma=h.vec4([0,0,0,1]),va=h.vec4([0,0,0,1]),wa=h.vec4([0,0,0,1]),ga=h.OBB3(),Ta=h.vec3(),Ea=h.vec3(),ba=h.vec3(),Da=h.vec3(),Pa=h.vec3(),Ra=h.vec3(),Ca=h.vec3();class _a{constructor(e){console.log("Creating TrianglesBatchingLayer"),this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=sa[t];return s||(s=new ta(e),sa[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete sa[t],s._destroy()}))),s}(e.model.scene),this._snapBatchingRenderers=function(e){const t=e.id;let s=fa[t];return s||(s=new da(e),fa[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete fa[t],s._destroy()}))),s}(e.model.scene),this._buffer=new na(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ve({origin:h.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:e.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=h.collapseAABB3(),this._portions=[],this._numVerts=0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=h.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=h.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.aabb=h.collapseAABB3(),this.solid=!!e.solid}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t<this._buffer.maxIndices}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,n=e.normals,i=e.normalsCompressed,a=e.uv,r=e.uvCompressed,l=e.colors,o=e.colorsCompressed,c=e.indices,u=e.edgeIndices,p=e.color,A=e.metallic,d=e.roughness,f=e.opacity,I=e.meshMatrix,y=e.sceneModelMatrix,m=e.worldAABB,v=e.pickColor,w=this.model.scene,g=this._buffer,T=g.positions.length/3;let E;if(this._state.positionsDecodeMatrix){if(!s)throw"positionsCompressed expected";E=s.length/3;for(let e=0,t=s.length;e<t;e++)g.positions.push(s[e]);const e=wt.getPositionsBounds(s),t=wt.decompressPosition(e.min,this._state.positionsDecodeMatrix,[]),n=wt.decompressPosition(e.max,this._state.positionsDecodeMatrix,[]);m[0]=t[0],m[1]=t[1],m[2]=t[2],m[3]=n[0],m[4]=n[1],m[5]=n[2],y&&(h.AABB3ToOBB3(m,ga),h.transformOBB3(y,ga),h.OBB3ToAABB3(ga,m))}else{if(!t)throw"positions expected";E=t.length/3;const e=t.length,s=g.positions.length;for(let e=0,s=t.length;e<s;e++)g.positions.push(t[e]);if(I)for(let t=s,n=s+e;t<n;t+=3)ma[0]=g.positions[t+0],ma[1]=g.positions[t+1],ma[2]=g.positions[t+2],h.transformPoint4(I,ma,va),g.positions[t+0]=va[0],g.positions[t+1]=va[1],g.positions[t+2]=va[2],h.expandAABB3Point3(this._modelAABB,va),y?(h.transformPoint4(y,va,wa),h.expandAABB3Point3(m,wa)):h.expandAABB3Point3(m,va);else for(let t=s,n=s+e;t<n;t+=3)ma[0]=g.positions[t+0],ma[1]=g.positions[t+1],ma[2]=g.positions[t+2],h.expandAABB3Point3(this._modelAABB,ma),y?(h.transformPoint4(y,ma,va),h.expandAABB3Point3(m,va)):h.expandAABB3Point3(m,ma)}if(this._state.origin){const e=this._state.origin;m[0]+=e[0],m[1]+=e[1],m[2]+=e[2],m[3]+=e[0],m[4]+=e[1],m[5]+=e[2]}if(h.expandAABB3(this.aabb,m),i&&i.length>0)for(let e=0,t=i.length;e<t;e++)g.normals.push(i[e]);else if(n&&n.length>0){const e=Ia;I?h.inverseMat4(h.transposeMat4(I,ya),e):h.identityMat4(e,e),function(e,t,s,n,i){function a(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let r,l,o,c,u,p,A=new Float32Array([0,0,0,0]),d=new Float32Array([0,0,0,0]);for(p=0;p<s;p+=3)A[0]=t[p],A[1]=t[p+1],A[2]=t[p+2],h.transformVec3(e,A,d),h.normalizeVec3(d,d),o=r=oa(d,"floor","floor"),l=ca(r),c=u=a(d,l),r=oa(d,"ceil","floor"),l=ca(r),c=a(d,l),c>u&&(o=r,u=c),r=oa(d,"floor","ceil"),l=ca(r),c=a(d,l),c>u&&(o=r,u=c),r=oa(d,"ceil","ceil"),l=ca(r),c=a(d,l),c>u&&(o=r,u=c),n[i+p+0]=o[0],n[i+p+1]=o[1],n[i+p+2]=0}(e,n,n.length,g.normals,g.normals.length)}if(l)for(let e=0,t=l.length;e<t;e+=3)g.colors.push(255*l[e]),g.colors.push(255*l[e+1]),g.colors.push(255*l[e+2]),g.colors.push(255);else if(o)for(let e=0,t=l.length;e<t;e+=3)g.colors.push(l[e]),g.colors.push(l[e+1]),g.colors.push(l[e+2]),g.colors.push(255);else if(p){const e=p[0],t=p[1],s=p[2],n=f;for(let i=0;i<E;i++)g.colors.push(e),g.colors.push(t),g.colors.push(s),g.colors.push(n)}const b=null!=A?A:0,D=null!=d?d:255;for(let e=0;e<E;e++)g.metallicRoughness.push(b),g.metallicRoughness.push(D);if(a&&a.length>0)for(let e=0,t=a.length;e<t;e++)g.uv.push(a[e]);else if(r&&r.length>0)for(let e=0,t=r.length;e<t;e++)g.uv.push(r[e]);for(let e=0,t=c.length;e<t;e++)g.indices.push(T+c[e]);if(u)for(let e=0,t=u.length;e<t;e++)g.edgeIndices.push(T+u[e]);{const e=g.pickColors.length;for(let t=e,s=e+4*E;t<s;t+=4)g.pickColors.push(v[0]),g.pickColors.push(v[1]),g.pickColors.push(v[2]),g.pickColors.push(v[3])}if(w.entityOffsetsEnabled)for(let e=0;e<E;e++)g.offsets.push(0),g.offsets.push(0),g.offsets.push(0);const P=this._portions.length,R={vertsBaseIndex:T,numVerts:E,indicesBaseIndex:g.indices.length-c.length,numIndices:c.length};return w.pickSurfacePrecisionEnabled&&(R.indices=c,w.entityOffsetsEnabled&&(R.offset=new Float32Array(3))),this._portions.push(R),this._numPortions++,this.model.numPortions++,this._numVerts+=R.numVerts,P}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,s=this._buffer;if(s.positions.length>0){const n=this._state.positionsDecodeMatrix?new Uint16Array(s.positions):ra(s.positions,this._modelAABB,this._state.positionsDecodeMatrix=h.mat4());if(e.positionsBuf=new ge(t,t.ARRAY_BUFFER,n,n.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e<t;e++){const t=this._portions[e],s=3*t.vertsBaseIndex,i=s+3*t.numVerts;t.quantizedPositions=n.slice(s,i)}}if(s.normals.length>0){const n=new Int8Array(s.normals);let i=!0;e.normalsBuf=new ge(t,t.ARRAY_BUFFER,n,s.normals.length,3,t.STATIC_DRAW,i)}if(s.colors.length>0){const n=new Uint8Array(s.colors);let i=!1;e.colorsBuf=new ge(t,t.ARRAY_BUFFER,n,s.colors.length,4,t.DYNAMIC_DRAW,i)}if(s.uv.length>0)if(e.uvDecodeMatrix){let n=!1;e.uvBuf=new ge(t,t.ARRAY_BUFFER,s.uv,s.uv.length,2,t.STATIC_DRAW,n)}else{const n=wt.getUVBounds(s.uv),i=wt.compressUVs(s.uv,n.min,n.max),a=i.quantized;let r=!1;e.uvDecodeMatrix=h.mat3(i.decodeMatrix),e.uvBuf=new ge(t,t.ARRAY_BUFFER,a,a.length,2,t.STATIC_DRAW,r)}if(s.metallicRoughness.length>0){const n=new Uint8Array(s.metallicRoughness);let i=!1;e.metallicRoughnessBuf=new ge(t,t.ARRAY_BUFFER,n,s.metallicRoughness.length,2,t.STATIC_DRAW,i)}if(s.positions.length>0){const n=s.positions.length/3,i=new Float32Array(n),a=!1;e.flagsBuf=new ge(t,t.ARRAY_BUFFER,i,i.length,1,t.DYNAMIC_DRAW,a)}if(s.pickColors.length>0){const n=new Uint8Array(s.pickColors);let i=!1;e.pickColorsBuf=new ge(t,t.ARRAY_BUFFER,n,s.pickColors.length,4,t.STATIC_DRAW,i)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const n=new Float32Array(s.offsets);e.offsetsBuf=new ge(t,t.ARRAY_BUFFER,n,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const n=new Uint32Array(s.indices);e.indicesBuf=new ge(t,t.ELEMENT_ARRAY_BUFFER,n,s.indices.length,1,t.STATIC_DRAW)}if(s.edgeIndices.length>0){const n=new Uint32Array(s.edgeIndices);e.edgeIndicesBuf=new ge(t,t.ELEMENT_ARRAY_BUFFER,n,s.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,s){t&x&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&U&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&F&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&M&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&L&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&x?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&U?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&F?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=e,n=this._portions[s],i=4*n.vertsBaseIndex,a=4*n.numVerts,r=this._scratchMemory.getUInt8Array(a),l=t[0],o=t[1],c=t[2],u=t[3];for(let e=0;e<a;e+=4)r[e+0]=l,r[e+1]=o,r[e+2]=c,r[e+3]=u;this._state.colorsBuf&&this._state.colorsBuf.setData(r,i,a)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s,n=!1){if(!this._finalized)throw"Not finalized";const i=e,a=this._portions[i],r=a.vertsBaseIndex,l=a.numVerts,o=!!(t&x),c=!!(t&U),u=!!(t&G),h=!!(t&V),p=!!(t&j),A=!!(t&M),d=!!(t&L);let f,I;f=!o||d||c||u&&!this.model.scene.highlightMaterial.glowThrough||h&&!this.model.scene.selectedMaterial.glowThrough?Pi.NOT_RENDERED:s?Pi.COLOR_TRANSPARENT:Pi.COLOR_OPAQUE,I=!o||d?Pi.NOT_RENDERED:h?Pi.SILHOUETTE_SELECTED:u?Pi.SILHOUETTE_HIGHLIGHTED:c?Pi.SILHOUETTE_XRAYED:Pi.NOT_RENDERED;let y=0;y=!o||d?Pi.NOT_RENDERED:h?Pi.EDGES_SELECTED:u?Pi.EDGES_HIGHLIGHTED:c?Pi.EDGES_XRAYED:p?s?Pi.EDGES_COLOR_TRANSPARENT:Pi.EDGES_COLOR_OPAQUE:Pi.NOT_RENDERED;let m=o&&!d&&A?Pi.PICK:Pi.NOT_RENDERED;const v=t&F?1:0;if(n){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(let e=r,t=r+l;e<t;e++){let t=0;t|=f,t|=I<<4,t|=y<<8,t|=m<<12,t|=v<<16,this._deferredFlagValues[e]=t}}else if(this._state.flagsBuf){const e=this._scratchMemory.getFloat32Array(l);for(let t=0;t<l;t++){let s=0;s|=f,s|=I<<4,s|=y<<8,s|=m<<12,s|=v<<16,e[t]=s}this._state.flagsBuf.setData(e,r,l)}}_setDeferredFlags(){this._deferredFlagValues&&(this._state.flagsBuf.setData(this._deferredFlagValues),this._deferredFlagValues=null)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const s=e,n=this._portions[s],i=3*n.vertsBaseIndex,a=3*n.numVerts,r=this._scratchMemory.getFloat32Array(a),l=t[0],o=t[1],c=t[2];for(let e=0;e<a;e+=3)r[e+0]=l,r[e+1]=o,r[e+2]=c;this._state.offsetsBuf&&this._state.offsetsBuf.setData(r,i,a),this.model.scene.pickSurfacePrecisionEnabled&&(n.offset[0]=t[0],n.offset[1]=t[1],n.offset[2]=t[2])}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return;const s=this._state,n=this._portions[e];if(!n)return void this.model.error("portion not found: "+e);const i=n.quantizedPositions,a=s.origin,r=n.offset,l=a[0]+r[0],o=a[1]+r[1],c=a[2]+r[2],u=ma;for(let e=0,n=i.length;e<n;e+=3)u[0]=i[e],u[1]=i[e+1],u[2]=i[e+2],u[3]=1,h.decompressPosition(u,s.positionsDecodeMatrix),h.transformPoint4(this.model.worldMatrix,u),u[0]+=l,u[1]+=o,u[2]+=c,t(u)}getElementsCountAndOffset(e){let t=null,s=null;const n=this._portions[e];return n&&(t=n.numIndices,s=n.indicesBaseIndex),{count:t,offset:s}}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._batchingRenderers.pbrRendererWithSAO&&this._batchingRenderers.pbrRendererWithSAO.drawLayer(t,this,Pi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._batchingRenderers.colorTextureRendererWithSAO&&this._batchingRenderers.colorTextureRendererWithSAO.drawLayer(t,this,Pi.COLOR_OPAQUE):this._state.normalsBuf?this._batchingRenderers.colorRendererWithSAO&&this._batchingRenderers.colorRendererWithSAO.drawLayer(t,this,Pi.COLOR_OPAQUE):this._batchingRenderers.flatColorRendererWithSAO&&this._batchingRenderers.flatColorRendererWithSAO.drawLayer(t,this,Pi.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._batchingRenderers.pbrRenderer&&this._batchingRenderers.pbrRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._batchingRenderers.colorTextureRenderer&&this._batchingRenderers.colorTextureRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE):this._state.normalsBuf?this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE):this._batchingRenderers.flatColorRenderer&&this._batchingRenderers.flatColorRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const s=this.model.backfaces||!this.solid||e.sectioned;if(t.backfaces!==s){const e=t.gl;s?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=s}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._batchingRenderers.pbrRenderer&&this._batchingRenderers.pbrRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._batchingRenderers.colorTextureRenderer&&this._batchingRenderers.colorTextureRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT):this._state.normalsBuf?this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT):this._batchingRenderers.flatColorRenderer&&this._batchingRenderers.flatColorRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.depthRenderer&&this._batchingRenderers.depthRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.normalsRenderer&&this._batchingRenderers.normalsRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._batchingRenderers.edgesColorRenderer&&this._batchingRenderers.edgesColorRenderer.drawLayer(t,this,Pi.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._batchingRenderers.edgesColorRenderer&&this._batchingRenderers.edgesColorRenderer.drawLayer(t,this,Pi.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(t,this,Pi.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(t,this,Pi.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(t,this,Pi.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.occlusionRenderer&&this._batchingRenderers.occlusionRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.shadowRenderer&&this._batchingRenderers.shadowRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE))}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.pickMeshRenderer&&this._batchingRenderers.pickMeshRenderer.drawLayer(t,this,Pi.PICK))}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.pickDepthRenderer&&this._batchingRenderers.pickDepthRenderer.drawLayer(t,this,Pi.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.pickNormalsFlatRenderer&&this._batchingRenderers.pickNormalsFlatRenderer.drawLayer(t,this,Pi.PICK))}drawSnapInitDepthBuf(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapBatchingRenderers.snapDepthBufInitRenderer&&this._snapBatchingRenderers.snapDepthBufInitRenderer.drawLayer(t,this,Pi.PICK))}drawSnapDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapBatchingRenderers.snapDepthRenderer&&this._snapBatchingRenderers.snapDepthRenderer.drawLayer(t,this,Pi.PICK))}precisionRayPickSurface(e,t,s,n,i){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const a=this._state,r=this._portions[e];if(!r)return this.model.error("portion not found: "+e),!1;const l=r.quantizedPositions,o=r.indices,c=a.origin,u=r.offset,p=Ta,A=Ea;p.set(c?h.subVec3(t,c,ba):t),A.set(s),u&&h.subVec3(p,u),h.transformRay(this.model.worldNormalMatrix,p,A,p,A);const d=Da,f=Pa,I=Ra;let y=!1,m=0;const v=Ca;for(let e=0,s=o.length;e<s;e+=3){const s=3*o[e],r=3*o[e+1],w=3*o[e+2];if(d[0]=l[s],d[1]=l[s+1],d[2]=l[s+2],f[0]=l[r],f[1]=l[r+1],f[2]=l[r+2],I[0]=l[w],I[1]=l[w+1],I[2]=l[w+2],h.decompressPosition(d,a.positionsDecodeMatrix),h.decompressPosition(f,a.positionsDecodeMatrix),h.decompressPosition(I,a.positionsDecodeMatrix),h.rayTriangleIntersect(p,A,d,f,I,v)){h.transformPoint3(this.model.worldMatrix,v,v),u&&h.addVec3(v,u),c&&h.addVec3(v,c);const e=Math.abs(h.lenVec3(h.subVec3(v,t,[])));(!y||e>m)&&(m=e,n.set(v),i&&h.triangleNormal(d,f,I,i),y=!0)}}return y&&i&&(h.transformVec3(this.model.worldNormalMatrix,i,i),h.normalizeVec3(i)),y}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}class Ba extends xi{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0;let i,a,r;const l=[];for(l.push("#version 300 es"),l.push("// Instancing geometry drawing vertex shader"),l.push("uniform int renderPass;"),l.push("in vec3 position;"),l.push("in vec2 normal;"),l.push("in vec4 color;"),l.push("in float flags;"),e.entityOffsetsEnabled&&l.push("in vec3 offset;"),l.push("in vec4 modelMatrixCol0;"),l.push("in vec4 modelMatrixCol1;"),l.push("in vec4 modelMatrixCol2;"),l.push("in vec4 modelNormalMatrixCol0;"),l.push("in vec4 modelNormalMatrixCol1;"),l.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(l,!0),e.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;")),l.push("uniform vec4 lightAmbient;"),i=0,a=s.lights.length;i<a;i++)r=s.lights[i],"ambient"!==r.type&&(l.push("uniform vec4 lightColor"+i+";"),"dir"===r.type&&l.push("uniform vec3 lightDir"+i+";"),"point"===r.type&&l.push("uniform vec3 lightPos"+i+";"),"spot"===r.type&&(l.push("uniform vec3 lightPos"+i+";"),l.push("uniform vec3 lightDir"+i+";")));for(l.push("vec3 octDecode(vec2 oct) {"),l.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),l.push(" if (v.z < 0.0) {"),l.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"),n&&(l.push("out vec4 vWorldPosition;"),l.push("out float vFlags;")),l.push("out vec4 vColor;"),l.push("void main(void) {"),l.push("int colorFlag = int(flags) & 0xF;"),l.push("if (colorFlag != renderPass) {"),l.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),l.push("} else {"),l.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),l.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&l.push(" worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix * worldPosition; "),l.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),l.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),l.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),i=0,a=s.lights.length;i<a;i++)if(r=s.lights[i],"ambient"!==r.type){if("dir"===r.type)"view"===r.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);");else if("point"===r.type)"view"===r.space?l.push("viewLightDir = -normalize(lightPos"+i+" - viewPosition.xyz);"):l.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+i+", 0.0)).xyz);");else{if("spot"!==r.type)continue;"view"===r.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);")}l.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),l.push("reflectedColor += lambertian * (lightColor"+i+".rgb * lightColor"+i+".a);")}return l.push("vec3 rgb = (vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0));"),l.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),l.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(l.push("vFragDepth = 1.0 + clipPos.w;"),l.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n&&(l.push("vWorldPosition = worldPosition;"),l.push("vFlags = flags;")),l.push("gl_Position = clipPos;"),l.push("}"),l.push("}"),l}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,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;")),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){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):n.push(" outColor = vColor;"),n.push("}"),n}}class Oa extends xi{_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.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry flat-shading drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState;let n,i;const a=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Instancing geometry flat-shading drawing 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("}")),a){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}for(this._addMatricesUniformBlockLines(r),r.push("uniform vec4 lightAmbient;"),n=0,i=s.lights.length;n<i;n++){const e=s.lights[n];"ambient"!==e.type&&(r.push("uniform vec4 lightColor"+n+";"),"dir"===e.type&&r.push("uniform vec3 lightDir"+n+";"),"point"===e.type&&r.push("uniform vec3 lightPos"+n+";"),"spot"===e.type&&(r.push("uniform vec3 lightPos"+n+";"),r.push("uniform vec3 lightDir"+n+";")))}if(r.push("in vec4 vViewPosition;"),r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),a){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }"),r.push("}")}for(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 ) );"),n=0,i=s.lights.length;n<i;n++){const e=s.lights[n];if("ambient"!==e.type){if("dir"===e.type)"view"===e.space?r.push("viewLightDir = normalize(lightDir"+n+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+n+", 0.0)).xyz);");else if("point"===e.type)"view"===e.space?r.push("viewLightDir = -normalize(lightPos"+n+" - viewPosition.xyz);"):r.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+n+", 0.0)).xyz);");else{if("spot"!==e.type)continue;"view"===e.space?r.push("viewLightDir = normalize(lightDir"+n+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+n+", 0.0)).xyz);")}r.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),r.push("reflectedColor += lambertian * (lightColor"+n+".rgb * lightColor"+n+".a);")}}return r.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" outColor = vec4(fragColor.rgb * ambient, 1.0);")):r.push(" outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}class Sa extends xi{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing fill 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class Na extends Li{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class xa extends Li{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class La extends xi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry picking vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry picking 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vPickColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vPickColor; "),n.push("}"),n}}class Ma extends xi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry depth 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 float pickZNear;"),n.push("uniform float pickZFar;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vViewPosition;"),n.push("vec4 packDepth(const in float depth) {"),n.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),n.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),n.push(" vec4 res = fract(depth * bitShift);"),n.push(" res -= res.xxyz * bitMask;"),n.push(" return res;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class Fa extends xi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec2 normal;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("in vec4 modelNormalMatrixCol0;"),s.push("in vec4 modelNormalMatrixCol1;"),s.push("in vec4 modelNormalMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),s.push(" vWorldNormal = worldNormal;"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry normals 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vWorldNormal;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),n.push("}"),n}}class Ha extends xi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("in float isPerspective;")),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("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing occlusion 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return n.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class Ua extends xi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry depth drawing fragment shader"),a.push("precision highp float;"),a.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("in vec2 vHighPrecisionZW;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push("if (dist > 0.0) { discard; }"),a.push("}")}return e.logarithmicDepthBufferEnabled&&a.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),a.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),a.push("}"),a}}class Ga extends xi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}class Va extends xi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}const ja={3e3:"linearToLinear",3001:"sRGBToLinear"};class ka extends xi{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0,i=t.clippingCaps,a=[];return a.push("#version 300 es"),a.push("// Instancing geometry quality drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec3 normal;"),a.push("in vec4 color;"),a.push("in vec2 uv;"),a.push("in vec2 metallicRoughness;"),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),a.push("uniform mat3 uvDecodeMatrix;"),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("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),a.push("out vec4 vViewPosition;"),a.push("out vec3 vViewNormal;"),a.push("out vec4 vColor;"),a.push("out vec2 vUV;"),a.push("out vec2 vMetallicRoughness;"),s.lightMaps.length>0&&a.push("out vec3 vWorldNormal;"),n&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;"),i&&a.push("out vec4 vClipPosition;")),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), 1.0);"),a.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),a.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(a.push("vFragDepth = 1.0 + clipPos.w;"),a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags = flags;"),i&&a.push("vClipPosition = clipPos;")),a.push("vViewPosition = viewPosition;"),a.push("vViewNormal = viewNormal;"),a.push("vColor = color;"),a.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),a.push("vMetallicRoughness = metallicRoughness;"),s.lightMaps.length>0&&a.push("vWorldNormal = worldNormal.xyz;"),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,n=e._lightsState,i=s.sectionPlanes.length>0,a=s.clippingCaps,r=[];r.push("#version 300 es"),r.push("// Instancing geometry quality drawing 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;")),r.push("uniform sampler2D uColorMap;"),r.push("uniform sampler2D uMetallicRoughMap;"),r.push("uniform sampler2D uEmissiveMap;"),r.push("uniform sampler2D uNormalMap;"),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("}")),n.reflectionMaps.length>0&&r.push("uniform samplerCube reflectionMap;"),n.lightMaps.length>0&&r.push("uniform samplerCube lightMap;"),r.push("uniform vec4 lightAmbient;");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];"ambient"!==t.type&&(r.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&r.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&r.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(r.push("uniform vec3 lightPos"+e+";"),r.push("uniform vec3 lightDir"+e+";")))}if(r.push("uniform float gammaFactor;"),r.push("vec4 linearToLinear( in vec4 value ) {"),r.push(" return value;"),r.push("}"),r.push("vec4 sRGBToLinear( in vec4 value ) {"),r.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 );"),r.push("}"),r.push("vec4 gammaToLinear( in vec4 value) {"),r.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),r.push("}"),t&&(r.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),r.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),r.push("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;"),a&&r.push("in vec4 vClipPosition;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}if(r.push("in vec4 vViewPosition;"),r.push("in vec3 vViewNormal;"),r.push("in vec4 vColor;"),r.push("in vec2 vUV;"),r.push("in vec2 vMetallicRoughness;"),n.lightMaps.length>0&&r.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(r,!0),r.push("#define PI 3.14159265359"),r.push("#define RECIPROCAL_PI 0.31830988618"),r.push("#define RECIPROCAL_PI2 0.15915494"),r.push("#define EPSILON 1e-6"),r.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),r.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),r.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),r.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),r.push(" return normalize(surf_norm );"),r.push(" }"),r.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),r.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),r.push(" vec2 st0 = dFdx( uv.st );"),r.push(" vec2 st1 = dFdy( uv.st );"),r.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),r.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),r.push(" vec3 N = normalize( surf_norm );"),r.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),r.push(" mat3 tsn = mat3( S, T, N );"),r.push(" return normalize( tsn * mapN );"),r.push("}"),r.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),r.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),r.push("}"),r.push("struct IncidentLight {"),r.push(" vec3 color;"),r.push(" vec3 direction;"),r.push("};"),r.push("struct ReflectedLight {"),r.push(" vec3 diffuse;"),r.push(" vec3 specular;"),r.push("};"),r.push("struct Geometry {"),r.push(" vec3 position;"),r.push(" vec3 viewNormal;"),r.push(" vec3 worldNormal;"),r.push(" vec3 viewEyeDir;"),r.push("};"),r.push("struct Material {"),r.push(" vec3 diffuseColor;"),r.push(" float specularRoughness;"),r.push(" vec3 specularColor;"),r.push(" float shine;"),r.push("};"),r.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),r.push(" float r = ggxRoughness + 0.0001;"),r.push(" return (2.0 / (r * r) - 2.0);"),r.push("}"),r.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),r.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),r.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),r.push("}"),n.reflectionMaps.length>0&&(r.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),r.push(" vec3 envMapColor = "+ja[n.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),r.push(" return envMapColor;"),r.push("}")),r.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),r.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),r.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),r.push("}"),r.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" return 1.0 / ( gl * gv );"),r.push("}"),r.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" return 0.5 / max( gv + gl, EPSILON );"),r.push("}"),r.push("float D_GGX(const in float alpha, const in float dotNH) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),r.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float alpha = ( roughness * roughness );"),r.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),r.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),r.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),r.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),r.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),r.push(" vec3 F = F_Schlick( specularColor, dotLH );"),r.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),r.push(" float D = D_GGX( alpha, dotNH );"),r.push(" return F * (G * D);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),r.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),r.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),r.push(" vec4 r = roughness * c0 + c1;"),r.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),r.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),r.push(" return specularColor * AB.x + AB.y;"),r.push("}"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&(r.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.lightMaps.length>0&&(r.push(" vec3 irradiance = "+ja[n.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),r.push(" irradiance *= PI;"),r.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),n.reflectionMaps.length>0&&(r.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),r.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),r.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),r.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),r.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),r.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),r.push("}")),r.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),r.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),r.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),r.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");a?(r.push(" if (dist > (0.002 * vClipPosition.w)) {"),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" return;"),r.push("}")):(r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }")),r.push("}")}r.push("IncidentLight light;"),r.push("Material material;"),r.push("Geometry geometry;"),r.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),r.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),r.push("float opacity = float(vColor.a) / 255.0;"),r.push("vec3 baseColor = rgb;"),r.push("float specularF0 = 1.0;"),r.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),r.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),r.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),r.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),r.push("baseColor *= colorTexel.rgb;"),r.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),r.push("metallic *= metalRoughTexel.b;"),r.push("roughness *= metalRoughTexel.g;"),r.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),r.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),r.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),r.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),r.push("geometry.position = vViewPosition.xyz;"),r.push("geometry.viewNormal = -normalize(viewNormal);"),r.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),n.lightMaps.length>0&&r.push("geometry.worldNormal = normalize(vWorldNormal);"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&r.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?r.push("light.direction = normalize(lightPos"+e+" - vViewPosition.xyz);"):r.push("light.direction = normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}r.push("light.color = lightColor"+e+".rgb * lightColor"+e+".a;"),r.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return r.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;"),r.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;"),r.push("vec4 fragColor;"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" fragColor = vec4(outgoingLight.rgb * ambient, opacity);")):r.push(" fragColor = vec4(outgoingLight.rgb, opacity);"),t&&r.push("fragColor = linearToGamma(fragColor, gammaFactor);"),r.push("outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}class Qa extends xi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&s.push("out float vFlags;"),s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&s.push("vFlags = flags;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry normals 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("in vec4 vWorldPosition;"),s){n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vWorldNormal;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),n.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),n.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),n.push(" outColor = vec4((worldNormal * 0.5) + 0.5, 1.0);"),n.push("}"),n}}class Wa extends xi{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,n=e._lightsState;let i,a;const r=s.sectionPlanes.length>0,l=[];if(l.push("#version 300 es"),l.push("// Instancing geometry drawing fragment shader"),l.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),l.push("precision highp float;"),l.push("precision highp int;"),l.push("#else"),l.push("precision mediump float;"),l.push("precision mediump int;"),l.push("#endif"),e.logarithmicDepthBufferEnabled&&(l.push("in float isPerspective;"),l.push("uniform float logDepthBufFC;"),l.push("in float vFragDepth;")),l.push("uniform sampler2D uColorMap;"),this._withSAO&&(l.push("uniform sampler2D uOcclusionTexture;"),l.push("uniform vec4 uSAOParams;"),l.push("const float packUpscale = 256. / 255.;"),l.push("const float unpackDownScale = 255. / 256.;"),l.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),l.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),l.push("float unpackRGBToFloat( const in vec4 v ) {"),l.push(" return dot( v, unPackFactors );"),l.push("}")),l.push("uniform float gammaFactor;"),l.push("vec4 linearToLinear( in vec4 value ) {"),l.push(" return value;"),l.push("}"),l.push("vec4 sRGBToLinear( in vec4 value ) {"),l.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 );"),l.push("}"),l.push("vec4 gammaToLinear( in vec4 value) {"),l.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),l.push("}"),t&&(l.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),l.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),l.push("}")),r){l.push("in vec4 vWorldPosition;"),l.push("in float vFlags;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)l.push("uniform bool sectionPlaneActive"+e+";"),l.push("uniform vec3 sectionPlanePos"+e+";"),l.push("uniform vec3 sectionPlaneDir"+e+";")}for(this._addMatricesUniformBlockLines(l),l.push("uniform vec4 lightAmbient;"),i=0,a=n.lights.length;i<a;i++){const e=n.lights[i];"ambient"!==e.type&&(l.push("uniform vec4 lightColor"+i+";"),"dir"===e.type&&l.push("uniform vec3 lightDir"+i+";"),"point"===e.type&&l.push("uniform vec3 lightPos"+i+";"),"spot"===e.type&&(l.push("uniform vec3 lightPos"+i+";"),l.push("uniform vec3 lightDir"+i+";")))}if(l.push("in vec4 vViewPosition;"),l.push("in vec4 vColor;"),l.push("in vec2 vUV;"),l.push("out vec4 outColor;"),l.push("void main(void) {"),r){l.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),l.push(" if (clippable) {"),l.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)l.push("if (sectionPlaneActive"+e+") {"),l.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),l.push("}");l.push(" if (dist > 0.0) { "),l.push(" discard;"),l.push(" }"),l.push("}")}for(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;"),l.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),l.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),l.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),i=0,a=n.lights.length;i<a;i++){const e=n.lights[i];if("ambient"!==e.type){if("dir"===e.type)"view"===e.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);");else if("point"===e.type)"view"===e.space?l.push("viewLightDir = -normalize(lightPos"+i+" - viewPosition.xyz);"):l.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+i+", 0.0)).xyz);");else{if("spot"!==e.type)continue;"view"===e.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);")}l.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),l.push("reflectedColor += lambertian * (lightColor"+i+".rgb * lightColor"+i+".a);")}}return l.push("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),t?l.push("vec4 colorTexel = color * sRGBToLinear(texture(uColorMap, vUV));"):l.push("vec4 colorTexel = color * texture(uColorMap, vUV);"),l.push("float opacity = color.a;"),this._withSAO?(l.push(" float viewportWidth = uSAOParams[0];"),l.push(" float viewportHeight = uSAOParams[1];"),l.push(" float blendCutoff = uSAOParams[2];"),l.push(" float blendFactor = uSAOParams[3];"),l.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),l.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),l.push(" outColor = vec4(vColor.rgb * colorTexel.rgb * ambient, opacity);")):l.push(" outColor = vec4(vColor.rgb * colorTexel.rgb, opacity);"),t&&l.push("outColor = linearToGamma(outColor, gammaFactor);"),e.logarithmicDepthBufferEnabled&&l.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),l.push("}"),l}}class za{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._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=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&&!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)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Ba(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Ba(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Oa(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Oa(this._scene,!0)),this._flatColorRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new ka(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new ka(this._scene,!0)),this._pbrRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Wa(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Wa(this._scene,!0)),this._colorTextureRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Sa(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Ua(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Ga(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Na(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new xa(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new La(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Fa(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Qa(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Ma(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Ha(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Va(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.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()}}const Ka={};const Ya=h.vec3();class Xa{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const n=t.model,i=n.scene,a=i.canvas.gl,r=t._state,l=t._state.origin;e.snapPickOrigin[0]=l[0],e.snapPickOrigin[1]=l[1],e.snapPickOrigin[2]=l[2];const o=t.aabb,c=[h.safeInv(o[3]-o[0])*h.MAX_INT,h.safeInv(o[4]-o[1])*h.MAX_INT,h.safeInv(o[5]-o[2])*h.MAX_INT];if(e.snapPickCoordinateScale[0]=h.safeInv(c[0]),e.snapPickCoordinateScale[1]=h.safeInv(c[1]),e.snapPickCoordinateScale[2]=h.safeInv(c[2]),!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const u=i.camera;let p=u.eye;e.pickViewMatrix&&(p=e.pickOrigin||p);const A=[p[0]-l[0],p[1]-l[1],p[2]-l[2]];a.uniform3fv(this._uCameraEyeRtc,A),a.uniform2fv(this.uVectorA,e.snapVectorA),a.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),a.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),a.uniform3fv(this._uCoordinateScaler,c),a.uniform1i(this._uRenderPass,s),a.uniform1i(this._uPickInvisible,e.pickInvisible);const d=e.pickViewMatrix||u.viewMatrix,f=l?B(d,l):d;if(a.uniformMatrix4fv(this._uViewMatrix,!1,f),a.uniformMatrix4fv(this._uWorldMatrix,!1,n.worldMatrix),a.uniformMatrix4fv(this._uProjMatrix,!1,u.projMatrix),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,t)}const I=i._sectionPlanesState.sectionPlanes.length;if(I>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,r=n.renderFlags;for(let t=0;t<I;t++){const n=this._uSectionPlanes[t];if(n){const i=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(n.active,i?1:0),i){const s=e[t];if(l){const e=N(s.dist,s.dir,l,Ya);a.uniform3fv(n.pos,e)}else a.uniform3fv(n.pos,s.pos);a.uniform3fv(n.dir,s.dir)}}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(r.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(r.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(r.modelMatrixCol2Buf),a.vertexAttribDivisor(this._aModelMatrixCol0.location,1),a.vertexAttribDivisor(this._aModelMatrixCol1.location,1),a.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(r.positionsBuf),this._aFlags&&(this._aFlags.bindArrayBuffer(r.flagsBuf),a.vertexAttribDivisor(this._aFlags.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(r.offsetsBuf),a.vertexAttribDivisor(this._aOffset.location,1)),r.indicesBuf.bind(),a.drawElementsInstanced(a.TRIANGLES,r.indicesBuf.numItems,r.indicesBuf.itemType,0,r.numInstances),r.indicesBuf.unbind(),a.vertexAttribDivisor(this._aModelMatrixCol0.location,0),a.vertexAttribDivisor(this._aModelMatrixCol1.location,0),a.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&a.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&a.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new we(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aFlags=s.getAttribute("flags"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this.uVectorA=s.getLocation("snapVectorA"),this.uInverseVectorAB=s.getLocation("snapInvVectorAB"),this._uLayerNumber=s.getLocation("layerNumber"),this._uCoordinateScaler=s.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in 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;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.z += 0.0001;"),s.push("clipPos.xyzw *= tmp;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing pick depth 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 int layerNumber;"),n.push("uniform vec3 coordinateScaler;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in highp vec3 relativeToOriginPosition;"),n.push("out highp ivec4 outCoords;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const qa=h.vec3();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,s){const n=t.model,i=n.scene,a=i.canvas.gl,r=t._state,l=t._state.origin;e.snapPickOrigin[0]=l[0],e.snapPickOrigin[1]=l[1],e.snapPickOrigin[2]=l[2];const o=t.aabb,c=[h.safeInv(o[3]-o[0])*h.MAX_INT,h.safeInv(o[4]-o[1])*h.MAX_INT,h.safeInv(o[5]-o[2])*h.MAX_INT];if(e.snapPickCoordinateScale[0]=h.safeInv(c[0]),e.snapPickCoordinateScale[1]=h.safeInv(c[1]),e.snapPickCoordinateScale[2]=h.safeInv(c[2]),!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const u=i.camera;let p=u.eye;e.pickViewMatrix&&(p=e.pickOrigin||p);const A=[p[0]-l[0],p[1]-l[1],p[2]-l[2]];a.uniform3fv(this._uCameraEyeRtc,A),a.uniform2fv(this.uVectorA,e.snapVectorA),a.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),a.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),a.uniform3fv(this._uCoordinateScaler,c),a.uniform1i(this._uRenderPass,s),a.uniform1i(this._uPickInvisible,e.pickInvisible);const d=e.pickViewMatrix||u.viewMatrix,f=l?B(d,l):d;if(a.uniformMatrix4fv(this._uViewMatrix,!1,f),a.uniformMatrix4fv(this._uWorldMatrix,!1,n.worldMatrix),a.uniformMatrix4fv(this._uProjMatrix,!1,u.projMatrix),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,t)}const I=i._sectionPlanesState.sectionPlanes.length;if(I>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,r=n.renderFlags;for(let t=0;t<I;t++){const n=this._uSectionPlanes[t];if(n){const i=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(n.active,i?1:0),i){const s=e[t];if(l){const e=N(s.dist,s.dir,l,qa);a.uniform3fv(n.pos,e)}else a.uniform3fv(n.pos,s.pos);a.uniform3fv(n.dir,s.dir)}}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(r.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(r.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(r.modelMatrixCol2Buf),a.vertexAttribDivisor(this._aModelMatrixCol0.location,1),a.vertexAttribDivisor(this._aModelMatrixCol1.location,1),a.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(r.positionsBuf),this._aFlags.bindArrayBuffer(r.flagsBuf),a.vertexAttribDivisor(this._aFlags.location,1),this._aOffset&&(this._aOffset.bindArrayBuffer(r.offsetsBuf),a.vertexAttribDivisor(this._aOffset.location,1)),"edge"===e.snapMode?(r.edgeIndicesBuf.bind(),a.drawElementsInstanced(a.LINES,r.edgeIndicesBuf.numItems,r.edgeIndicesBuf.itemType,0,r.numInstances),r.edgeIndicesBuf.unbind()):a.drawArraysInstanced(a.POINTS,0,r.positionsBuf.numItems,r.numInstances),a.vertexAttribDivisor(this._aModelMatrixCol0.location,0),a.vertexAttribDivisor(this._aModelMatrixCol1.location,0),a.vertexAttribDivisor(this._aModelMatrixCol2.location,0),a.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&a.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new we(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aFlags=s.getAttribute("flags"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this.uVectorA=s.getLocation("snapVectorA"),this.uInverseVectorAB=s.getLocation("snapInvVectorAB"),this._uLayerNumber=s.getLocation("layerNumber"),this._uCoordinateScaler=s.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// SnapInstancingDepthRenderer 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 int layerNumber;"),n.push("uniform vec3 coordinateScaler;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in highp vec3 relativeToOriginPosition;"),n.push("out highp ivec4 outCoords;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Za{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new Xa(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new Ja(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const $a={};const er=new Uint8Array(4),tr=new Float32Array(1),sr=h.vec4([0,0,0,1]),nr=h.vec4([0,0,0,1]),ir=h.vec4([0,0,0,1]),ar=new Float32Array(3),rr=h.vec3(),lr=h.vec3(),or=h.vec3(),cr=h.vec3(),ur=h.vec3(),hr=h.vec3(),pr=h.vec3();class Ar{constructor(e){console.log("Creating TrianglesInstancingLayer"),this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._instancingRenderers=function(e){const t=e.id;let s=Ka[t];return s||(s=new za(e),Ka[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Ka[t],s._destroy()}))),s}(e.model.scene),this._snapInstancingRenderers=function(e){const t=e.id;let s=$a[t];return s||(s=new Za(e),$a[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete $a[t],s._destroy()}))),s}(e.model.scene),this._aabb=h.collapseAABB3(),this._state=new Ve({numInstances:0,obb:h.OBB3(),origin:h.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,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._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.aabb=h.collapseAABB3(),this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}createPortion(e){const t=e.color,s=e.metallic,n=e.roughness,i=null!==e.opacity&&void 0!==e.opacity?e.opacity:255,a=e.meshMatrix,r=e.sceneModelMatrix,l=e.aabb,o=e.pickColor;if(this._finalized)throw"Already finalized";const c=t[0],u=t[1],p=t[2];if(this._colors.push(c),this._colors.push(u),this._colors.push(p),this._colors.push(i),this._metallicRoughness.push(null!=s?s:0),this._metallicRoughness.push(null!=n?n:255),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(a[0]),this._modelMatrixCol0.push(a[4]),this._modelMatrixCol0.push(a[8]),this._modelMatrixCol0.push(a[12]),this._modelMatrixCol1.push(a[1]),this._modelMatrixCol1.push(a[5]),this._modelMatrixCol1.push(a[9]),this._modelMatrixCol1.push(a[13]),this._modelMatrixCol2.push(a[2]),this._modelMatrixCol2.push(a[6]),this._modelMatrixCol2.push(a[10]),this._modelMatrixCol2.push(a[14]),this._state.geometry.normals){let e=h.transposeMat4(a,h.mat4()),t=h.inverseMat4(e);this._modelNormalMatrixCol0.push(t[0]),this._modelNormalMatrixCol0.push(t[4]),this._modelNormalMatrixCol0.push(t[8]),this._modelNormalMatrixCol0.push(t[12]),this._modelNormalMatrixCol1.push(t[1]),this._modelNormalMatrixCol1.push(t[5]),this._modelNormalMatrixCol1.push(t[9]),this._modelNormalMatrixCol1.push(t[13]),this._modelNormalMatrixCol2.push(t[2]),this._modelNormalMatrixCol2.push(t[6]),this._modelNormalMatrixCol2.push(t[10]),this._modelNormalMatrixCol2.push(t[14])}this._pickColors.push(o[0]),this._pickColors.push(o[1]),this._pickColors.push(o[2]),this._pickColors.push(o[3]);const A=this._state.geometry.positionsCompressed.length,d=this._state.geometry.positionsCompressed,f=this._state.geometry.positionsDecodeMatrix;for(let e=0;e<A;e+=3)sr[0]=d[e+0],sr[1]=d[e+1],sr[2]=d[e+2],h.transformPoint4(f,sr,nr),h.transformPoint4(a,nr,sr),r?(h.transformPoint4(r,sr,ir),h.expandAABB3Point3(l,ir)):h.expandAABB3Point3(l,sr);if(this._state.origin){const e=this._state.origin;l[0]+=e[0],l[1]+=e[1],l[2]+=e[2],l[3]+=e[0],l[4]+=e[1],l[5]+=e[2]}h.expandAABB3(this.aabb,l),this._state.numInstances++;const I=this._portions.length,y={};return this.model.scene.pickSurfacePrecisionEnabled&&(y.matrix=a.slice(),y.inverseMatrix=null,y.normalMatrix=null),this._portions.push(y),this._numPortions++,this.model.numPortions++,I}finalize(){if(this._finalized)return;const e=this._state,t=e.geometry,s=e.textureSet,n=this.model.scene.canvas.gl,i=this._colors.length,a=i/4;if(i>0){let t=!1;e.colorsBuf=new ge(n,n.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,n.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let s=!1;e.metallicRoughnessBuf=new ge(n,n.ARRAY_BUFFER,t,this._metallicRoughness.length,2,n.STATIC_DRAW,s)}if(a>0){let t=!1;e.flagsBuf=new ge(n,n.ARRAY_BUFFER,new Float32Array(a),a,1,n.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new ge(n,n.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,n.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const s=!1;e.positionsBuf=new ge(n,n.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,n.STATIC_DRAW,s),e.positionsDecodeMatrix=h.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const s=new Uint8Array(t.colorsCompressed),i=!1;e.colorsBuf=new ge(n,n.ARRAY_BUFFER,s,s.length,4,n.STATIC_DRAW,i)}if(t.uvCompressed&&t.uvCompressed.length>0){const s=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new ge(n,n.ARRAY_BUFFER,s,s.length,2,n.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new ge(n,n.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,n.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new ge(n,n.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,n.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new ge(n,n.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,n.STATIC_DRAW,t),e.modelMatrixCol1Buf=new ge(n,n.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,n.STATIC_DRAW,t),e.modelMatrixCol2Buf=new ge(n,n.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,n.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new ge(n,n.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,n.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new ge(n,n.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,n.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new ge(n,n.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,n.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new ge(n,n.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,n.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&s&&s.colorTexture&&s.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!s&&!!s.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&x&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&U&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&F&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&M&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&L&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&x?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&U?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&F?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";er[0]=t[0],er[1]=t[1],er[2]=t[2],er[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(er,4*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=!!(t&x),i=!!(t&U),a=!!(t&G),r=!!(t&V),l=!!(t&j),o=!!(t&M),c=!!(t&L);let u,h;u=!n||c||i||a&&!this.model.scene.highlightMaterial.glowThrough||r&&!this.model.scene.selectedMaterial.glowThrough?Pi.NOT_RENDERED:s?Pi.COLOR_TRANSPARENT:Pi.COLOR_OPAQUE,h=!n||c?Pi.NOT_RENDERED:r?Pi.SILHOUETTE_SELECTED:a?Pi.SILHOUETTE_HIGHLIGHTED:i?Pi.SILHOUETTE_XRAYED:Pi.NOT_RENDERED;let p=0;p=!n||c?Pi.NOT_RENDERED:r?Pi.EDGES_SELECTED:a?Pi.EDGES_HIGHLIGHTED:i?Pi.EDGES_XRAYED:l?s?Pi.EDGES_COLOR_TRANSPARENT:Pi.EDGES_COLOR_OPAQUE:Pi.NOT_RENDERED;let A=0;A|=u,A|=h<<4,A|=p<<8,A|=(n&&!c&&o?Pi.PICK:Pi.NOT_RENDERED)<<12,A|=(t&F?1:0)<<16,tr[0]=A,this._state.flagsBuf&&this._state.flagsBuf.setData(tr,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(ar[0]=t[0],ar[1]=t[1],ar[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(ar,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const s=this._state,n=s.geometry,i=this._portions[e];if(!i)return void this.model.error("portion not found: "+e);const a=n.quantizedPositions,r=s.origin,l=i.offset,o=r[0]+l[0],c=r[1]+l[1],u=r[2]+l[2],p=sr,A=i.matrix,d=this.model.sceneModelMatrix,f=s.positionsDecodeMatrix;for(let e=0,s=a.length;e<s;e+=3)p[0]=a[e],p[1]=a[e+1],p[2]=a[e+2],h.decompressPosition(p,f),h.transformPoint3(A,p),h.transformPoint3(d,p),p[0]+=o,p[1]+=c,p[2]+=u,t(p)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._instancingRenderers.pbrRendererWithSAO&&this._instancingRenderers.pbrRendererWithSAO.drawLayer(t,this,Pi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._instancingRenderers.colorTextureRendererWithSAO&&this._instancingRenderers.colorTextureRendererWithSAO.drawLayer(t,this,Pi.COLOR_OPAQUE):this._state.normalsBuf?this._instancingRenderers.colorRendererWithSAO&&this._instancingRenderers.colorRendererWithSAO.drawLayer(t,this,Pi.COLOR_OPAQUE):this._instancingRenderers.flatColorRendererWithSAO&&this._instancingRenderers.flatColorRendererWithSAO.drawLayer(t,this,Pi.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._instancingRenderers.pbrRenderer&&this._instancingRenderers.pbrRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._instancingRenderers.colorTextureRenderer&&this._instancingRenderers.colorTextureRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE):this._state.normalsBuf?this._instancingRenderers.colorRenderer&&this._instancingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE):this._instancingRenderers.flatColorRenderer&&this._instancingRenderers.flatColorRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const s=this.model.backfaces||!this.solid||e.sectioned;if(t.backfaces!==s){const e=t.gl;s?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=s}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._instancingRenderers.pbrRenderer&&this._instancingRenderers.pbrRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._instancingRenderers.colorTextureRenderer&&this._instancingRenderers.colorTextureRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT):this._state.normalsBuf?this._instancingRenderers.colorRenderer&&this._instancingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT):this._instancingRenderers.flatColorRenderer&&this._instancingRenderers.flatColorRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.depthRenderer&&this._instancingRenderers.depthRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.normalsRenderer&&this._instancingRenderers.normalsRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.silhouetteRenderer&&this._instancingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.silhouetteRenderer&&this._instancingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.silhouetteRenderer&&this._instancingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._instancingRenderers.edgesColorRenderer&&this._instancingRenderers.edgesColorRenderer.drawLayer(t,this,Pi.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._instancingRenderers.edgesColorRenderer&&this._instancingRenderers.edgesColorRenderer.drawLayer(t,this,Pi.EDGES_COLOR_TRANSPARENT)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(t,this,Pi.EDGES_XRAYED)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(t,this,Pi.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(t,this,Pi.EDGES_SELECTED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.occlusionRenderer&&this._instancingRenderers.occlusionRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.shadowRenderer&&this._instancingRenderers.shadowRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE))}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.pickMeshRenderer&&this._instancingRenderers.pickMeshRenderer.drawLayer(t,this,Pi.PICK))}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.pickDepthRenderer&&this._instancingRenderers.pickDepthRenderer.drawLayer(t,this,Pi.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.pickNormalsRenderer&&this._instancingRenderers.pickNormalsRenderer.drawLayer(t,this,Pi.PICK))}drawSnapInitDepthBuf(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapInstancingRenderers.snapDepthBufInitRenderer&&this._snapInstancingRenderers.snapDepthBufInitRenderer.drawLayer(t,this,Pi.PICK))}drawSnapDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapInstancingRenderers.snapDepthRenderer&&this._snapInstancingRenderers.snapDepthRenderer.drawLayer(t,this,Pi.PICK))}precisionRayPickSurface(e,t,s,n,i){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const a=this._state.geometry,r=this._state,l=this._portions[e];if(!l)return this.model.error("portion not found: "+e),!1;l.inverseMatrix||(l.inverseMatrix=h.inverseMat4(l.matrix,h.mat4())),i&&!l.normalMatrix&&(l.normalMatrix=h.transposeMat4(l.inverseMatrix,h.mat4()));const o=a.quantizedPositions,c=a.indices,u=r.origin,p=l.offset,A=rr,d=lr;A.set(u?h.subVec3(t,u,or):t),d.set(s),p&&h.subVec3(A,p),h.transformRay(this.model.worldNormalMatrix,A,d,A,d),h.transformRay(l.inverseMatrix,A,d,A,d);const f=cr,I=ur,y=hr;let m=!1,v=0;const w=pr;for(let e=0,s=c.length;e<s;e+=3){const s=3*c[e+0],a=3*c[e+1],g=3*c[e+2];f[0]=o[s],f[1]=o[s+1],f[2]=o[s+2],I[0]=o[a],I[1]=o[a+1],I[2]=o[a+2],y[0]=o[g],y[1]=o[g+1],y[2]=o[g+2];const{positionsDecodeMatrix:T}=r.geometry;if(h.decompressPosition(f,T),h.decompressPosition(I,T),h.decompressPosition(y,T),h.rayTriangleIntersect(A,d,f,I,y,w)){h.transformPoint3(l.matrix,w,w),h.transformPoint3(this.model.worldMatrix,w,w),p&&h.addVec3(w,p),u&&h.addVec3(w,u);const e=Math.abs(h.lenVec3(h.subVec3(w,t,[])));(!m||e>v)&&(v=e,n.set(w),i&&h.triangleNormal(f,I,y,i),m=!0)}}return m&&i&&(h.transformVec3(l.normalMatrix,i,i),h.transformVec3(this.model.worldNormalMatrix,i,i),h.normalizeVec3(i)),m}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 dr extends Hi{drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Lines batching color 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return n.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class fr extends Hi{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Lines batching silhouette 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("uniform vec4 color;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = color;"),n.push("}"),n}}class Ir{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new dr(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new fr(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const yr={};class mr{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}const vr=h.vec4([0,0,0,1]),wr=h.vec4([0,0,0,1]),gr=h.vec4([0,0,0,1]),Tr=h.OBB3();class Er{constructor(e){this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=yr[t];return s||(s=new Ir(e),yr[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete yr[t],s._destroy()}))),s}(e.model.scene),this.model=e.model,this._buffer=new mr(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ve({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:h.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=h.collapseAABB3(),this._portions=[],this._numVerts=0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=h.vec3(e.origin)),this.aabb=h.collapseAABB3()}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t<this._buffer.maxIndices}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,n=e.indices,i=e.color,a=e.opacity,r=e.meshMatrix,l=e.worldMatrix,o=e.worldAABB;e.pickColor;const c=this._buffer,u=c.positions.length/3;let p;if(this._preCompressedPositionsExpected){if(!s)throw"positionsCompressed expected";p=s.length/3;for(let e=0,t=s.length;e<t;e++)c.positions.push(s[e]);const e=wt.getPositionsBounds(s),t=wt.decompressPosition(e.min,this._state.positionsDecodeMatrix,[]),n=wt.decompressPosition(e.max,this._state.positionsDecodeMatrix,[]);o[0]=t[0],o[1]=t[1],o[2]=t[2],o[3]=n[0],o[4]=n[1],o[5]=n[2],l&&(h.AABB3ToOBB3(o,Tr),h.transformOBB3(l,Tr),h.OBB3ToAABB3(Tr,o))}else{if(!t)throw"positions expected";p=t.length/3;const e=t.length,s=c.positions.length;for(let e=0,s=t.length;e<s;e++)c.positions.push(t[e]);if(r)for(let t=s,n=s+e;t<n;t+=3)vr[0]=c.positions[t+0],vr[1]=c.positions[t+1],vr[2]=c.positions[t+2],h.transformPoint4(r,vr,wr),c.positions[t+0]=wr[0],c.positions[t+1]=wr[1],c.positions[t+2]=wr[2],h.expandAABB3Point3(this._modelAABB,wr),l?(h.transformPoint4(l,wr,gr),h.expandAABB3Point3(o,gr)):h.expandAABB3Point3(o,wr);else for(let t=s,n=s+e;t<n;t+=3)vr[0]=c.positions[t+0],vr[1]=c.positions[t+1],vr[2]=c.positions[t+2],h.expandAABB3Point3(this._modelAABB,vr),l?(h.transformPoint4(l,vr,wr),h.expandAABB3Point3(o,wr)):h.expandAABB3Point3(o,vr)}if(this._state.origin){const e=this._state.origin;o[0]+=e[0],o[1]+=e[1],o[2]+=e[2],o[3]+=e[0],o[4]+=e[1],o[5]+=e[2]}if(h.expandAABB3(this.aabb,o),i){const e=i[0],t=i[1],s=i[2],n=a;for(let i=0;i<p;i++)c.colors.push(e),c.colors.push(t),c.colors.push(s),c.colors.push(n)}if(n)for(let e=0,t=n.length;e<t;e++)c.indices.push(n[e]+u);if(this.model.scene.entityOffsetsEnabled)for(let e=0;e<p;e++)c.offsets.push(0),c.offsets.push(0),c.offsets.push(0);const A=this._portions.length/2;return this._portions.push(u),this._portions.push(p),this._numPortions++,this.model.numPortions++,this._numVerts+=p,A}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,s=this._buffer;if(s.positions.length>0)if(this._preCompressedPositionsExpected){const n=new Uint16Array(s.positions);e.positionsBuf=new ge(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}else{const n=ra(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new ge(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const n=new Uint8Array(s.colors);let i=!1;e.colorsBuf=new ge(t,t.ARRAY_BUFFER,n,s.colors.length,4,t.DYNAMIC_DRAW,i)}if(s.colors.length>0){const n=s.colors.length/4,i=new Float32Array(n);let a=!1;e.flagsBuf=new ge(t,t.ARRAY_BUFFER,i,i.length,1,t.DYNAMIC_DRAW,a)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const n=new Float32Array(s.offsets);e.offsetsBuf=new ge(t,t.ARRAY_BUFFER,n,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const n=new Uint32Array(s.indices);e.indicesBuf=new ge(t,t.ELEMENT_ARRAY_BUFFER,n,s.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&x&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&U&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&F&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&M&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&L&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&x?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&U?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&F?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,n=4*this._portions[s],i=4*this._portions[s+1],a=this._scratchMemory.getUInt8Array(i),r=t[0],l=t[1],o=t[2],c=t[3];for(let e=0;e<i;e+=4)a[e+0]=r,a[e+1]=l,a[e+2]=o,a[e+3]=c;this._state.colorsBuf.setData(a,n,i)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s,n=!1){if(!this._finalized)throw"Not finalized";const i=2*e,a=this._portions[i],r=this._portions[i+1],l=!!(t&x),o=!!(t&U),c=!!(t&G),u=!!(t&V),h=!!(t&M),p=!!(t&L);let A,d;A=!l||p||o||c&&!this.model.scene.highlightMaterial.glowThrough||u&&!this.model.scene.selectedMaterial.glowThrough?Pi.NOT_RENDERED:s?Pi.COLOR_TRANSPARENT:Pi.COLOR_OPAQUE,d=!l||p?Pi.NOT_RENDERED:u?Pi.SILHOUETTE_SELECTED:c?Pi.SILHOUETTE_HIGHLIGHTED:o?Pi.SILHOUETTE_XRAYED:Pi.NOT_RENDERED;let f=l&&!p&&h?Pi.PICK:Pi.NOT_RENDERED;const I=t&F?1:0;if(n){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(let e=a,t=a+r;e<t;e++){let t=0;t|=A,t|=d<<4,t|=f<<12,t|=I<<16,this._deferredFlagValues[e]=t}}else if(this._state.flagsBuf){const e=this._scratchMemory.getFloat32Array(r);for(let t=0;t<r;t++){let s=0;s|=A,s|=d<<4,s|=f<<12,s|=I<<16,e[t]=s}this._state.flagsBuf.setData(e,a,r)}}_setDeferredFlags(){this._deferredFlagValues&&(this._state.flagsBuf.setData(this._deferredFlagValues),this._deferredFlagValues=null)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const s=2*e,n=3*this._portions[s],i=3*this._portions[s+1],a=this._scratchMemory.getFloat32Array(i),r=t[0],l=t[1],o=t[2];for(let e=0;e<i;e+=3)a[e+0]=r,a[e+1]=l,a[e+2]=o;this._state.offsetsBuf.setData(a,n,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawPickMesh(e){}drawPickDepths(e){}drawPickNormals(e){}drawOcclusion(e){}drawShadow(e){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicesBuf=null),e.destroy()}}class br extends Ui{drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 lightAmbient;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Lines instancing color fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push("if (dist > 0.0) { discard; }"),a.push("}")}return this._withSAO?(a.push(" float viewportWidth = uSAOParams[0];"),a.push(" float viewportHeight = uSAOParams[1];"),a.push(" float blendCutoff = uSAOParams[2];"),a.push(" float blendFactor = uSAOParams[3];"),a.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),a.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):a.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}}class Dr extends Ui{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 color;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Lines instancing silhouette 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("uniform vec4 color;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = color;"),n.push("}"),n}}class Pr{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new br(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Dr(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const Rr={};const Cr=new Uint8Array(4),_r=new Float32Array(1),Br=h.vec4([0,0,0,1]),Or=h.vec4([0,0,0,1]),Sr=h.vec4([0,0,0,1]),Nr=new Float32Array(3);class xr{constructor(e){this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._linesInstancingRenderers=function(e){const t=e.id;let s=Rr[t];return s||(s=new Pr(e),Rr[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Rr[t],s._destroy()}))),s}(e.model.scene),this._aabb=h.collapseAABB3(),this._state=new Ve({obb:h.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],e.origin&&(this._state.origin=h.vec3(e.origin)),this._finalized=!1,this.aabb=h.collapseAABB3()}createPortion(e){const t=e.color,s=e.opacity,n=e.meshMatrix,i=e.worldMatrix,a=e.aabb;if(this._finalized)throw"Already finalized";const r=t[0],l=t[1],o=t[2];t[3],this._colors.push(r),this._colors.push(l),this._colors.push(o),this._colors.push(s),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(n[0]),this._modelMatrixCol0.push(n[4]),this._modelMatrixCol0.push(n[8]),this._modelMatrixCol0.push(n[12]),this._modelMatrixCol1.push(n[1]),this._modelMatrixCol1.push(n[5]),this._modelMatrixCol1.push(n[9]),this._modelMatrixCol1.push(n[13]),this._modelMatrixCol2.push(n[2]),this._modelMatrixCol2.push(n[6]),this._modelMatrixCol2.push(n[10]),this._modelMatrixCol2.push(n[14]),h.collapseAABB3(a);const c=this._state.obb,u=c.length;for(let e=0;e<u;e+=4)Br[0]=c[e+0],Br[1]=c[e+1],Br[2]=c[e+2],h.transformPoint4(n,Br,Or),i?(h.transformPoint4(i,Or,Sr),h.expandAABB3Point3(a,Sr)):h.expandAABB3Point3(a,Or);if(this._state.origin){const e=this._state.origin;a[0]+=e[0],a[1]+=e[1],a[2]+=e[2],a[3]+=e[0],a[4]+=e[1],a[5]+=e[2]}h.expandAABB3(this.aabb,a),this._state.numInstances++;const p=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,p}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl,t=this._colors.length,s=t/4;if(t>0){let t=!1;this._state.colorsBuf=new ge(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(s>0){let t=!1;this._state.flagsBuf=new ge(e,e.ARRAY_BUFFER,new Float32Array(s),s,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&x&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&U&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&F&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&M&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&L&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&x?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&U?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&F?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";Cr[0]=t[0],Cr[1]=t[1],Cr[2]=t[2],Cr[3]=t[3],this._state.colorsBuf.setData(Cr,4*e,4)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=!!(t&x),i=!!(t&U),a=!!(t&G),r=!!(t&V),l=!!(t&j),o=!!(t&M),c=!!(t&L);let u,h;u=!n||c||i||a&&!this.model.scene.highlightMaterial.glowThrough||r&&!this.model.scene.selectedMaterial.glowThrough?Pi.NOT_RENDERED:s?Pi.COLOR_TRANSPARENT:Pi.COLOR_OPAQUE,h=!n||c?Pi.NOT_RENDERED:r?Pi.SILHOUETTE_SELECTED:a?Pi.SILHOUETTE_HIGHLIGHTED:i?Pi.SILHOUETTE_XRAYED:Pi.NOT_RENDERED;let p=0;p=!n||c?Pi.NOT_RENDERED:r?Pi.EDGES_SELECTED:a?Pi.EDGES_HIGHLIGHTED:i?Pi.EDGES_XRAYED:l?s?Pi.EDGES_COLOR_TRANSPARENT:Pi.EDGES_COLOR_OPAQUE:Pi.NOT_RENDERED;let A=0;A|=u,A|=h<<4,A|=p<<8,A|=(n&&!c&&o?Pi.PICK:Pi.NOT_RENDERED)<<12,A|=(t&F?255:0)<<16,_r[0]=A,this._state.flagsBuf.setData(_r,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Nr[0]=t[0],Nr[1]=t[1],Nr[2]=t[2],this._state.offsetsBuf.setData(Nr,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class Lr extends Mi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial,n=[];return n.push("#version 300 es"),n.push("// Points batching color vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec4 color;"),n.push("in float flags;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),s.filterIntensity&&n.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),s.filterIntensity&&(n.push("float intensity = float(color.a) / 255.0;"),n.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {")),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),s.filterIntensity&&n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points batching color 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(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(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return n.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class Mr extends Mi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batching silhouette vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),this._addMatricesUniformBlockLines(n),n.push("uniform vec4 color;"),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),n.push("if (silhouetteFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Points batching silhouette vertex shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("uniform vec4 color;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),e.pointsMaterial.roundPoints&&(a.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push(" float r = dot(cxy, cxy);"),a.push(" if (r > 1.0) {"),a.push(" discard;"),a.push(" }")),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}return e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("outColor = color;"),a.push("}"),a}}class Fr extends Mi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batching pick mesh vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 pickColor;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vPickColor;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),n.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("gl_PointSize += 10.0;"),n.push(" }"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points batching pick mesh vertex 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("in vec4 vPickColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(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(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vPickColor; "),n.push("}"),n}}class Hr extends Mi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batched pick depth vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vViewPosition;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vViewPosition = viewPosition;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("gl_PointSize += 10.0;"),n.push(" }"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points batched pick depth 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform float pickZNear;"),n.push("uniform float pickZFar;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vViewPosition;"),n.push("vec4 packDepth(const in float depth) {"),n.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),n.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),n.push(" vec4 res = fract(depth * bitShift);"),n.push(" res -= res.xxyz * bitMask;"),n.push(" return res;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(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(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class Ur extends Mi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batching occlusion vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push(" gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push(" }"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points batching occlusion 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(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(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),n.push("}"),n}}class Gr{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Lr(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Mr(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Fr(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Hr(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Ur(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const Vr={};class jr{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}const kr=h.vec4(),Qr=h.vec4(),Wr=h.vec4([0,0,0,1]),zr=h.vec4([0,0,0,1]),Kr=h.vec4([0,0,0,1]),Yr=h.OBB3();class Xr{constructor(e){this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._pointsBatchingRenderers=function(e){const t=e.id;let s=Vr[t];return s||(s=new Gr(e),Vr[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Vr[t],s._destroy()}))),s}(e.model.scene),this._buffer=new jr(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ve({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:h.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=h.collapseAABB3(),this._portions=[],this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=h.vec3(e.origin)),this.aabb=h.collapseAABB3()}canCreatePortion(e){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,n=e.color,i=e.colorsCompressed,a=e.colors,r=e.meshMatrix,l=e.worldMatrix,o=e.worldAABB,c=e.pickColor,u=this._buffer,p=u.positions.length/3;let A;if(this._preCompressedPositionsExpected){if(!s)throw"positionsCompressed expected";for(let e=0,t=s.length;e<t;e++)u.positions.push(s[e]);const e=wt.getPositionsBounds(s),t=wt.decompressPosition(e.min,this._state.positionsDecodeMatrix,kr),n=wt.decompressPosition(e.max,this._state.positionsDecodeMatrix,Qr);o[0]=t[0],o[1]=t[1],o[2]=t[2],o[3]=n[0],o[4]=n[1],o[5]=n[2],l&&(h.AABB3ToOBB3(o,Yr),h.transformOBB3(l,Yr),h.OBB3ToAABB3(Yr,o)),A=s.length/3}else{if(!t)throw"positions expected";A=t.length/3;const e=t.length,s=u.positions.length;for(let e=0,s=t.length;e<s;e++)u.positions.push(t[e]);if(r)for(let t=s,n=s+e;t<n;t+=3)Wr[0]=u.positions[t+0],Wr[1]=u.positions[t+1],Wr[2]=u.positions[t+2],h.transformPoint4(r,Wr,zr),u.positions[t+0]=zr[0],u.positions[t+1]=zr[1],u.positions[t+2]=zr[2],h.expandAABB3Point3(this._modelAABB,zr),l?(h.transformPoint4(l,zr,Kr),h.expandAABB3Point3(o,Kr)):h.expandAABB3Point3(o,zr);else for(let t=s,n=s+e;t<n;t+=3)Wr[0]=u.positions[t+0],Wr[1]=u.positions[t+1],Wr[2]=u.positions[t+2],h.expandAABB3Point3(this._modelAABB,Wr),l?(h.transformPoint4(l,Wr,zr),h.expandAABB3Point3(o,zr)):h.expandAABB3Point3(o,Wr)}if(this._state.origin){const e=this._state.origin;o[0]+=e[0],o[1]+=e[1],o[2]+=e[2],o[3]+=e[0],o[4]+=e[1],o[5]+=e[2]}if(h.expandAABB3(this.aabb,o),i)for(let e=0,t=i.length;e<t;e++)u.colors.push(i[e]);else if(a)for(let e=0,t=a.length;e<t;e++)u.colors.push(255*a[e]);else if(n){const e=n[0],t=n[1],s=n[2],i=1;for(let n=0;n<A;n++)u.colors.push(e),u.colors.push(t),u.colors.push(s),u.colors.push(i)}{const e=u.pickColors.length;for(let t=e,s=e+4*A;t<s;t+=4)u.pickColors.push(c[0]),u.pickColors.push(c[1]),u.pickColors.push(c[2]),u.pickColors.push(c[3])}if(this.model.scene.entityOffsetsEnabled)for(let e=0;e<A;e++)u.offsets.push(0),u.offsets.push(0),u.offsets.push(0);const d=this._portions.length/2;return this._portions.push(p),this._portions.push(A),this._numPortions++,this.model.numPortions++,d}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,s=this._buffer;if(s.positions.length>0)if(this._preCompressedPositionsExpected){const n=new Uint16Array(s.positions);e.positionsBuf=new ge(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}else{const n=ra(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new ge(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const n=new Uint8Array(s.colors);let i=!1;e.colorsBuf=new ge(t,t.ARRAY_BUFFER,n,s.colors.length,4,t.STATIC_DRAW,i)}if(s.positions.length>0){const n=s.positions.length/3,i=new Float32Array(n);let a=!1;e.flagsBuf=new ge(t,t.ARRAY_BUFFER,i,i.length,1,t.DYNAMIC_DRAW,a)}if(s.pickColors.length>0){const n=new Uint8Array(s.pickColors);let i=!1;e.pickColorsBuf=new ge(t,t.ARRAY_BUFFER,n,s.pickColors.length,4,t.STATIC_DRAW,i)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const n=new Float32Array(s.offsets);e.offsetsBuf=new ge(t,t.ARRAY_BUFFER,n,s.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&x&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&U&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&F&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&M&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&L&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&x?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&U?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&F?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,n=4*this._portions[s],i=4*this._portions[s+1],a=this._scratchMemory.getUInt8Array(i),r=t[0],l=t[1],o=t[2];for(let e=0;e<i;e+=4)a[e+0]=r,a[e+1]=l,a[e+2]=o;this._state.colorsBuf.setData(a,n,i)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=2*e,i=this._portions[n],a=this._portions[n+1],r=this._scratchMemory.getFloat32Array(a),l=!!(t&x),o=!!(t&U),c=!!(t&G),u=!!(t&V),h=!!(t&M),p=!!(t&L);let A,d;A=!l||p||o||c&&!this.model.scene.highlightMaterial.glowThrough||u&&!this.model.scene.selectedMaterial.glowThrough?Pi.NOT_RENDERED:s?Pi.COLOR_TRANSPARENT:Pi.COLOR_OPAQUE,d=!l||p?Pi.NOT_RENDERED:u?Pi.SILHOUETTE_SELECTED:c?Pi.SILHOUETTE_HIGHLIGHTED:o?Pi.SILHOUETTE_XRAYED:Pi.NOT_RENDERED;let f=l&&!p&&h?Pi.PICK:Pi.NOT_RENDERED;const I=t&F?1:0;for(let e=0;e<a;e++){let t=0;t|=A,t|=d<<4,t|=f<<12,t|=I<<16,r[e]=t}this._state.flagsBuf.setData(r,i)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const s=2*e,n=3*this._portions[s],i=3*this._portions[s+1],a=this._scratchMemory.getFloat32Array(i),r=t[0],l=t[1],o=t[2];for(let e=0;e<i;e+=3)a[e+0]=r,a[e+1]=l,a[e+2]=o;this._state.offsetsBuf.setData(a,n,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsBatchingRenderers.colorRenderer&&this._pointsBatchingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsBatchingRenderers.colorRenderer&&this._pointsBatchingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsBatchingRenderers.silhouetteRenderer&&this._pointsBatchingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsBatchingRenderers.silhouetteRenderer&&this._pointsBatchingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsBatchingRenderers.silhouetteRenderer&&this._pointsBatchingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsBatchingRenderers.pickMeshRenderer&&this._pointsBatchingRenderers.pickMeshRenderer.drawLayer(t,this,Pi.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsBatchingRenderers.pickDepthRenderer&&this._pointsBatchingRenderers.pickDepthRenderer.drawLayer(t,this,Pi.PICK)}drawPickNormals(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsBatchingRenderers.occlusionRenderer&&this._pointsBatchingRenderers.occlusionRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE)}drawShadow(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}class qr extends Fi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing color vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec4 color;"),n.push("in float flags;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),s.filterIntensity&&n.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),s.filterIntensity&&(n.push("float intensity = float(color.a) / 255.0;"),n.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {")),n.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),s.filterIntensity&&n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing color 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(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(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return n.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class Jr extends Fi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing silhouette vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 color;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),n.push("uniform vec4 silhouetteColor;"),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),n.push("if (silhouetteFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing silhouette 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(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(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class Zr extends Fi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing pick mesh vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 pickColor;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vPickColor;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),n.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing pick mesh 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vPickColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(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(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vPickColor; "),n.push("}"),n}}class $r extends Fi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing pick depth vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vViewPosition;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push(" vViewPosition = viewPosition;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing pick depth 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform float pickZNear;"),n.push("uniform float pickZFar;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vViewPosition;"),n.push("vec4 packDepth(const in float depth) {"),n.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),n.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),n.push(" vec4 res = fract(depth * bitShift);"),n.push(" res -= res.xxyz * bitMask;"),n.push(" return res;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(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(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class el extends Fi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing occlusion vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in vec4 color;"),n.push("in float flags;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing occlusion vertex 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(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(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return n.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class tl extends Fi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing depth vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Points instancing depth vertex shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("const float packUpScale = 256. / 255.;"),a.push("const float unpackDownscale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. );"),a.push("const float shiftRight8 = 1.0 / 256.;"),a.push("vec4 packDepthToRGBA( const in float v ) {"),a.push(" vec4 r = vec4( fract( v * packFactors ), v );"),a.push(" r.yzw -= r.xyz * shiftRight8;"),a.push(" return r * packUpScale;"),a.push("}"),a.push("out vec4 outColor;"),a.push("void main(void) {"),e.pointsMaterial.roundPoints&&(a.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push(" float r = dot(cxy, cxy);"),a.push(" if (r > 1.0) {"),a.push(" discard;"),a.push(" }")),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push("if (dist > 0.0) { discard; }"),a.push("}")}return a.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}}class sl extends Fi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("gl_PointSize = pointSize;"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),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(" }"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}class nl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new qr(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Jr(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new tl(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Zr(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new $r(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new el(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new sl(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const il={};const al=new Uint8Array(4),rl=new Float32Array(1),ll=h.vec4([0,0,0,1]),ol=h.vec4([0,0,0,1]),cl=h.vec4([0,0,0,1]),ul=new Float32Array(3);class hl{constructor(e){this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._pointsInstancingRenderers=function(e){const t=e.id;let s=il[t];return s||(s=new nl(e),il[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete il[t],s._destroy()}))),s}(e.model.scene),this._aabb=h.collapseAABB3(),this._state=new Ve({obb:h.OBB3(),numInstances:0,origin:e.origin?h.vec3(e.origin):null,geometry:e.geometry,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._finalized=!1,this.aabb=h.collapseAABB3()}createPortion(e){const t=e.meshMatrix,s=e.worldMatrix,n=e.aabb,i=e.pickColor;if(this._finalized)throw"Already finalized";this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(t[0]),this._modelMatrixCol0.push(t[4]),this._modelMatrixCol0.push(t[8]),this._modelMatrixCol0.push(t[12]),this._modelMatrixCol1.push(t[1]),this._modelMatrixCol1.push(t[5]),this._modelMatrixCol1.push(t[9]),this._modelMatrixCol1.push(t[13]),this._modelMatrixCol2.push(t[2]),this._modelMatrixCol2.push(t[6]),this._modelMatrixCol2.push(t[10]),this._modelMatrixCol2.push(t[14]),this._pickColors.push(i[0]),this._pickColors.push(i[1]),this._pickColors.push(i[2]),this._pickColors.push(i[3]),h.collapseAABB3(n);const a=this._state.obb,r=a.length;for(let e=0;e<r;e+=4)ll[0]=a[e+0],ll[1]=a[e+1],ll[2]=a[e+2],h.transformPoint4(t,ll,ol),s?(h.transformPoint4(s,ol,cl),h.expandAABB3Point3(n,cl)):h.expandAABB3Point3(n,ol);if(this._state.origin){const e=this._state.origin;n[0]+=e[0],n[1]+=e[1],n[2]+=e[2],n[3]+=e[0],n[4]+=e[1],n[5]+=e[2]}h.expandAABB3(this.aabb,n),this._state.numInstances++;const l=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,l}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl,t=this._pickColors.length/4;if(t>0){let s=!1;this._state.flagsBuf=new ge(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;this._state.offsetsBuf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new ge(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;this._state.pickColorsBuf=new ge(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&x&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&U&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&F&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&M&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&L&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&x?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&U?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&F?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";al[0]=t[0],al[1]=t[1],al[2]=t[2],this._state.colorsBuf.setData(al,3*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=!!(t&x),i=!!(t&U),a=!!(t&G),r=!!(t&V),l=!!(t&j),o=!!(t&M),c=!!(t&L);let u,h;u=!n||c||i||a&&!this.model.scene.highlightMaterial.glowThrough||r&&!this.model.scene.selectedMaterial.glowThrough?Pi.NOT_RENDERED:s?Pi.COLOR_TRANSPARENT:Pi.COLOR_OPAQUE,h=!n||c?Pi.NOT_RENDERED:r?Pi.SILHOUETTE_SELECTED:a?Pi.SILHOUETTE_HIGHLIGHTED:i?Pi.SILHOUETTE_XRAYED:Pi.NOT_RENDERED;let p=0;p=!n||c?Pi.NOT_RENDERED:r?Pi.EDGES_SELECTED:a?Pi.EDGES_HIGHLIGHTED:i?Pi.EDGES_XRAYED:l?s?Pi.EDGES_COLOR_TRANSPARENT:Pi.EDGES_COLOR_OPAQUE:Pi.NOT_RENDERED;let A=0;A|=u,A|=h<<4,A|=p<<8,A|=(n&&!c&&o?Pi.PICK:Pi.NOT_RENDERED)<<12,A|=(t&F?255:0)<<16,rl[0]=A,this._state.flagsBuf.setData(rl,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(ul[0]=t[0],ul[1]=t[1],ul[2]=t[2],this._state.offsetsBuf.setData(ul,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.occlusionRenderer&&this._pointsInstancingRenderers.occlusionRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickMeshRenderer&&this._pointsInstancingRenderers.pickMeshRenderer.drawLayer(t,this,Pi.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickDepthRenderer&&this._pointsInstancingRenderers.pickDepthRenderer.drawLayer(t,this,Pi.PICK)}drawPickNormals(e,t){}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}class pl{constructor(e){this.id=e.id,this.colorTexture=e.colorTexture,this.metallicRoughnessTexture=e.metallicRoughnessTexture,this.normalsTexture=e.normalsTexture,this.emissiveTexture=e.emissiveTexture,this.occlusionTexture=e.occlusionTexture}destroy(){}}class Al{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const dl={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(this.files[e]=t)},get:function(e){if(!1!==this.enabled)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};class fl{constructor(e,t,s){this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=s}itemStart(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}itemEnd(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}itemError(e){void 0!==this.onError&&this.onError(e)}resolveURL(e){return this.urlModifier?this.urlModifier(e):e}setURLModifier(e){return this.urlModifier=e,this}addHandler(e,t){return this.handlers.push(e,t),this}removeHandler(e){const t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}getHandler(e){for(let t=0,s=this.handlers.length;t<s;t+=2){const s=this.handlers[t],n=this.handlers[t+1];if(s.global&&(s.lastIndex=0),s.test(e))return n}return null}}const Il=new fl;class yl{constructor(e){this.manager=void 0!==e?e:Il,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){const s=this;return new Promise((function(n,i){s.load(e,n,t,i)}))}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}}const ml={};class vl extends yl{constructor(e){super(e)}load(e,t,s,n){void 0===e&&(e=""),void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const i=dl.get(e);if(void 0!==i)return this.manager.itemStart(e),setTimeout((()=>{t&&t(i),this.manager.itemEnd(e)}),0),i;if(void 0!==ml[e])return void ml[e].push({onLoad:t,onProgress:s,onError:n});ml[e]=[],ml[e].push({onLoad:t,onProgress:s,onError:n});const a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),r=this.mimeType,l=this.responseType;fetch(a).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;const s=ml[e],n=t.body.getReader(),i=t.headers.get("Content-Length"),a=i?parseInt(i):0,r=0!==a;let l=0;const o=new ReadableStream({start(e){!function t(){n.read().then((({done:n,value:i})=>{if(n)e.close();else{l+=i.byteLength;const n=new ProgressEvent("progress",{lengthComputable:r,loaded:l,total:a});for(let e=0,t=s.length;e<t;e++){const t=s[e];t.onProgress&&t.onProgress(n)}e.enqueue(i),t()}}))}()}});return new Response(o)}throw Error(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`)})).then((e=>{switch(l){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,r)));case"json":return e.json();default:if(void 0===r)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(r),s=t&&t[1]?t[1].toLowerCase():void 0,n=new TextDecoder(s);return e.arrayBuffer().then((e=>n.decode(e)))}}})).then((t=>{dl.add(e,t);const s=ml[e];delete ml[e];for(let e=0,n=s.length;e<n;e++){const n=s[e];n.onLoad&&n.onLoad(t)}})).catch((t=>{const s=ml[e];if(void 0===s)throw this.manager.itemError(e),t;delete ml[e];for(let e=0,n=s.length;e<n;e++){const n=s[e];n.onError&&n.onError(t)}this.manager.itemError(e)})).finally((()=>{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class wl{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e<this.pool;e++)if(!(this.workerStatus&1<<e))return e;return-1}_onMessage(e,t){const s=this.workersResolve[e];if(s&&s(t),this.queue.length){const{resolve:t,msg:s,transfer:n}=this.queue.shift();this.workersResolve[e]=t,this.workers[e].postMessage(s,n)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise((s=>{const n=this._getIdleWorker();-1!==n?(this._initWorker(n),this.workerStatus|=1<<n,this.workersResolve[n]=s,this.workers[n].postMessage(e,t)):this.queue.push({resolve:s,msg:e,transfer:t})}))}destroy(){this.workers.forEach((e=>e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let gl=0;class Tl{constructor({viewer:e,transcoderPath:t,workerLimit:s}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new wl,this._workerSourceURL="",s&&this._workerPool.setWorkerLimit(s);const n=e.capabilities;this._workerConfig={astcSupported:n.astcSupported,etc1Supported:n.etc1Supported,etc2Supported:n.etc2Supported,dxtSupported:n.dxtSupported,bptcSupported:n.bptcSupported,pvrtcSupported:n.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new vl;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),s=new vl;s.setPath(this._transcoderPath),s.setResponseType("arraybuffer"),s.setWithCredentials(this.withCredentials);const n=s.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,n]).then((([e,t])=>{const s=Tl.BasisWorker.toString(),n=["/* constants */","let _EngineFormat = "+JSON.stringify(Tl.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(Tl.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(Tl.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",s.substring(s.indexOf("{")+1,s.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([n])),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}))})),gl>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),gl++}return this._transcoderPending}transcode(e,t,s={}){return new Promise(((n,i)=>{const a=s;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:a},e))).then((e=>{const s=e.data,{mipmaps:a,width:r,height:l,format:o,type:c,error:u,dfdTransferFn:h,dfdFlags:p}=s;if("error"===c)return i(u);t.setCompressedData({mipmaps:a,props:{format:o,minFilter:1===a.length?1006:1008,magFilter:1===a.length?1006:1008,encoding:2===h?3001:3e3,premultiplyAlpha:!!(1&p)}}),n()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),gl--}}Tl.BasisFormat={ETC1S:0,UASTC_4x4:1},Tl.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},Tl.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},Tl.BasisWorker=function(){let e,t,s;const n=_EngineFormat,i=_TranscoderFormat,a=_BasisFormat;self.addEventListener("message",(function(r){const u=r.data;switch(u.type){case"init":e=u.config,h=u.transcoderBinary,t=new Promise((e=>{s={wasmBinary:h,onRuntimeInitialized:e},BASIS(s)})).then((()=>{s.initializeBasis(),void 0===s.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:r,hasAlpha:h,mipmaps:p,format:A,dfdTransferFn:d,dfdFlags:f}=function(t){const r=new s.KTX2File(new Uint8Array(t));function u(){r.close(),r.delete()}if(!r.isValid())throw u(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const h=r.isUASTC()?a.UASTC_4x4:a.ETC1S,p=r.getWidth(),A=r.getHeight(),d=r.getLevels(),f=r.getHasAlpha(),I=r.getDFDTransferFunc(),y=r.getDFDFlags(),{transcoderFormat:m,engineFormat:v}=function(t,s,r,u){let h,p;const A=t===a.ETC1S?l:o;for(let n=0;n<A.length;n++){const i=A[n];if(e[i.if]&&(i.basisFormat.includes(t)&&!(u&&i.transcoderFormat.length<2)&&(!i.needsPowerOfTwo||c(s)&&c(r))))return h=i.transcoderFormat[u?1:0],p=i.engineFormat[u?1:0],{transcoderFormat:h,engineFormat:p}}return console.warn("KTX2TextureTranscoder: No suitable compressed texture format found. Decoding to RGBA32."),h=i.RGBA32,p=n.RGBAFormat,{transcoderFormat:h,engineFormat:p}}(h,p,A,f);if(!p||!A||!d)throw u(),new Error("KTX2TextureTranscoder: Invalid texture");if(!r.startTranscoding())throw u(),new Error("KTX2TextureTranscoder: .startTranscoding failed");const w=[];for(let e=0;e<d;e++){const t=r.getImageLevelInfo(e,0,0),s=t.origWidth,n=t.origHeight,i=new Uint8Array(r.getImageTranscodedSizeInBytes(e,0,0,m));if(!r.transcodeImage(i,e,0,0,m,0,-1,-1))throw u(),new Error("KTX2TextureTranscoder: .transcodeImage failed.");w.push({data:i,width:s,height:n})}return u(),{width:p,height:A,hasAlpha:f,mipmaps:w,format:v,dfdTransferFn:I,dfdFlags:y}}(u.buffers[0]),I=[];for(let e=0;e<p.length;++e)I.push(p[e].data.buffer);self.postMessage({type:"transcode",id:u.id,width:t,height:r,hasAlpha:h,mipmaps:p,format:A,dfdTransferFn:d,dfdFlags:f},I)}catch(e){console.error(`[KTX2TextureTranscoder.BasisWorker]: ${e}`),self.postMessage({type:"error",id:u.id,error:e.message})}}))}var h}));const r=[{if:"astcSupported",basisFormat:[a.UASTC_4x4],transcoderFormat:[i.ASTC_4x4,i.ASTC_4x4],engineFormat:[n.RGBA_ASTC_4x4_Format,n.RGBA_ASTC_4x4_Format],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.BC7_M5,i.BC7_M5],engineFormat:[n.RGBA_BPTC_Format,n.RGBA_BPTC_Format],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.BC1,i.BC3],engineFormat:[n.RGB_S3TC_DXT1_Format,n.RGBA_S3TC_DXT5_Format],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.ETC1,i.ETC2],engineFormat:[n.RGB_ETC2_Format,n.RGBA_ETC2_EAC_Format],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.ETC1],engineFormat:[n.RGB_ETC1_Format],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.PVRTC1_4_RGB,i.PVRTC1_4_RGBA],engineFormat:[n.RGB_PVRTC_4BPPV1_Format,n.RGBA_PVRTC_4BPPV1_Format],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0}],l=r.sort((function(e,t){return e.priorityETC1S-t.priorityETC1S})),o=r.sort((function(e,t){return e.priorityUASTC-t.priorityUASTC}));function c(e){return e<=2||0==(e&e-1)&&0!==e}};const El={};function bl(e){const t=e.scene.id;let s=El[t];return s||(s=new Tl({viewer:e}),El[t]=s,e.scene.on("destroyed",(()=>{delete El[t],s.destroy()}))),s}
|
|
10
|
+
function es(e,t){t.length;const s=e.length,n=[],i=[],a=e=>{for(let s=0,n=e.meshIds.length;s<n;s++)if(t[e.meshIds[s]].geometryId)return!0;return!1};for(let r=0;r<s;r++){const s=e[r];if(a(s)){i.push(r);continue}const l=h.collapseAABB3();let o=0;s.meshIds.forEach((e=>{const s=t[e];let n,i;if(s.positionsCompressed){const e=wt.getPositionsBounds(s.positionsCompressed);n=wt.decompressPosition(e.min,s.positionsDecodeMatrix,[]),i=wt.decompressPosition(e.max,s.positionsDecodeMatrix,[])}else{const e=wt.getPositionsBounds(s.positions);n=e.min,i=e.max}n[0]+=s.origin[0],n[1]+=s.origin[1],n[2]+=s.origin[2],i[0]+=s.origin[0],i[1]+=s.origin[1],i[2]+=s.origin[2],h.expandAABB3Point3(l,n),h.expandAABB3Point3(l,i),o+=s.numPrimitives})),n[r]={aabb:l,numPrimitives:o,entityId:s.id}}let r,l=[],o={};if(Object.keys(n).length>0){r=function(e){const t=[];for(let s=0,n=e.length;s<n;s++){const n=e[s];n&&t.push({minX:n.aabb[0],minY:n.aabb[1],minZ:n.aabb[2],maxX:n.aabb[3],maxY:n.aabb[4],maxZ:n.aabb[5],entity:{id:s,xeokitId:n.entityId,meshes:[{numPrimitives:n.numPrimitives}]},numPrimitives:n.numPrimitives})}const s=new Zt(4);return s.load(t),s}(n);let e=$t({aabbTree:r});l=e.orderedEntityIds,o=e.clusteringResult.entityIdToClusterIdMapping}return{orderedClusteredIndexes:l,entityIdToClusterIdMapping:o,instancedIndexes:i,rTreeBasedAabbTree:r}}const ts=h.vec3(),ss=180/Math.PI,ns=new Float32Array(262144);for(let e=-256;e<256;e++)for(let t=-256;t<256;t++){const s=(e+256<<9)+(t+256),n=Math.max(Math.abs(e),Math.abs(t));ns[s]=Math.atan2(e/n,t/n)}function is(e,t){const s=256/Math.max(Math.abs(e),Math.abs(t)),n=Math.round(e*s)+255,i=Math.round(t*s)+255;return ns[(n<<9)+i]}class as{constructor(){this._aabbTree=null,this._orderedMeshList=[],this._orderedEntityList=[],this._frustumProps={dirty:!0,wMultiply:1,hMultiply:1},this._cullFrame=0,this.finalized=!1}initializeVFCState(e,t){if(this.finalized)throw"Already finalized";const s=es(e,t);this._aabbTree=s.rTreeBasedAabbTree;for(let n=0,i=s.orderedClusteredIndexes.length;n<i;n++){const i=s.orderedClusteredIndexes[n],a=s.entityIdToClusterIdMapping[i],r=e[i],l=[];for(let e=0,s=r.meshIds.length;e<s;e++){const s=r.meshIds[e];t[s].id=this._orderedMeshList.length,l.push(this._orderedMeshList.length),this._orderedMeshList.push({clusterNumber:a,mesh:t[s]})}r.meshIds=l,this._orderedEntityList.push(r)}for(let n=0,i=s.instancedIndexes.length;n<i;n++){let i=e[s.instancedIndexes[n]];const a=[];for(let e=0,s=i.meshIds.length;e<s;e++){const s=i.meshIds[e];t[s].id=this._orderedMeshList.length,a.push(this._orderedMeshList.length),this._orderedMeshList.push({clusterNumber:99999,mesh:t[s]})}i.meshIds=a,this._orderedEntityList.push(i)}}finalize(e,t){if(this.finalized)throw"Already finalized";let s=-1;for(let n=0,i=this._orderedMeshList.length;n<i;n++){const{clusterNumber:i,mesh:a}=this._orderedMeshList[n];-1!==s&&s!==i&&t.call(e),e._createMesh(a),s=i}for(let t=0,s=this._orderedEntityList.length;t<s;t++)e._createEntity(this._orderedEntityList[t]);this._orderedMeshList=[],this._orderedEntityList=[],this.finalized=!0}applyViewFrustumCulling(e){if(!this.finalized)throw"Not finalized";if(!this._aabbTree)return;this._canvasElement||(this._canvasElement=e.scene.canvas.canvas),this._camera||(this._camera=e.scene.camera),this._ensureFrustumPropsUpdated(e),this._initializeCullingDataIfNeeded(e);const t=this._searchVisibleNodesWithFrustumCulling();this._cullFrame++,this._markVisibleFrameOfVisibleNodes(t,this._cullFrame),this._cullNonVisibleNodes(e,this._cullFrame)}_initializeCullingDataIfNeeded(e){if(this._internalNodesList)return;if(!this._aabbTree)return;const t=this._aabbTree.all();let s=0;t.forEach((e=>{s=Math.max(s,e.entity.id)}));const n=new Array(s+1);t.forEach((t=>{n[t.entity.id]=e.objects[t.entity.xeokitId]})),this._internalNodesList=n,this._lastVisibleFrameOfNodes=new Array(n.length),this._lastVisibleFrameOfNodes.fill(0)}_searchVisibleNodesWithFrustumCulling(){return this._aabbTree.searchCustom(((e,t)=>this._aabbIntersectsCameraFrustum(e,t)),(e=>this._aabbContainedInCameraFrustum(e)))}_markVisibleFrameOfVisibleNodes(e,t){const s=this._lastVisibleFrameOfNodes;for(let n=0,i=e.length;n<i;n++)s[e[n].entity.id]=t}_cullNonVisibleNodes(e,t){const s=this._internalNodesList,n=this._lastVisibleFrameOfNodes;for(let e=0,i=s.length;e<i;e++)s[e]&&(s[e].culledVFC=n[e]!==t)}_getPointsForBBox(e){const t=[];for(let s=0;s<8;s++)t.push(new Float32Array([1&s?e.maxX:e.minX,2&s?e.maxY:e.minY,4&s?e.maxZ:e.minZ]));return t}_aabbIntersectsCameraFrustum(e,t){if(t)return!0;if("ortho"===this._camera.projection)return this._frustumProps.dirty=!1,!0;const s=this._aabbIntersectsCameraFrustum_internal(e);return!!((4096&s||!(1&s||2&s)||1&s)&&(8192&s||!(16&s||32&s)||16&s)&&(16384&s||!(256&s||512&s)||256&s))}_aabbContainedInCameraFrustum(e){if("ortho"===this._camera.projection)return this._frustumProps.dirty=!1,!0;const t=e._check;return 1&t&&16&t&&256&t}_ensureFrustumPropsUpdated(e){const t=Math.min(this._canvasElement.width,this._canvasElement.height);this._frustumProps.wMultiply=this._canvasElement.width/t,this._frustumProps.hMultiply=this._canvasElement.height/t;const s=this._canvasElement.width/this._canvasElement.height;let n=this._camera.perspective.fov;s<1&&(n/=s),n=Math.min(n,120),this._frustumProps.fov=n;const i=h.inverseMat4(e.worldMatrix,h.mat4()),a=h.transformVec3(i,this._camera.eye,[0,0,0]),r=h.transformVec3(i,this._camera.look,[0,0,0]);this._frustumProps.forward=h.normalizeVec3(h.subVec3(r,a,[0,0,0]),[0,0,0]),this._frustumProps.up=h.normalizeVec3(this._camera.up,[0,0,0]),this._frustumProps.right=h.normalizeVec3(h.cross3Vec3(this._frustumProps.forward,this._frustumProps.up,[0,0,0]),[0,0,0]),this._frustumProps.eye=a.slice(),this._frustumProps.CAM_FACTOR_1=this._frustumProps.fov/2*this._frustumProps.wMultiply/ss,this._frustumProps.CAM_FACTOR_2=this._frustumProps.fov/2*this._frustumProps.hMultiply/ss}_aabbIntersectsCameraFrustum_internal(e){const t=e._points||this._getPointsForBBox(e);e._points=t;let s=819;for(let e=0,n=t.length;e<n;e++){const n=t[e],i=ts;i[0]=n[0]-this._frustumProps.eye[0],i[1]=n[1]-this._frustumProps.eye[1],i[2]=n[2]-this._frustumProps.eye[2];const a=h.dotVec3(i,this._frustumProps.forward);a<0?(s|=4,s&=-2):(s|=8,s&=-3);const r=is(h.dotVec3(i,this._frustumProps.right),a);Math.abs(r)>this._frustumProps.CAM_FACTOR_1?(s|=r<0?64:128,s&=-17):s&=-33;const l=is(h.dotVec3(i,this._frustumProps.up),a);Math.abs(l)>this._frustumProps.CAM_FACTOR_2?(s|=l<0?1024:2048,s&=-257):s&=-513}return 4&s&&8&s&&(s|=4096),64&s&&128&s&&(s|=8192),1024&s&&2048&s&&(s|=16384),e._check=s,s}}class rs{constructor(e,t){this.sceneModel=t,this.entities=[],this.meshes=[],this.finalized=!1}addEntity(e){if(this.finalized)throw"Already finalized";this.entities.push(e)}addMesh(e){if(this.finalized)throw"Already finalized";this.meshes.push(e)}finalize(e){if(this.finalized)throw"Already finalized";this.finalized=!0,this.VFCState=new as,this.VFCState.initializeVFCState(this.entities,this.meshes),this.VFCState.finalize(this.sceneModel,e),this._onSceneRendering=this.sceneModel.scene.on("rendering",(()=>this.applyViewFrustumCulling.call(this)))}applyViewFrustumCulling(){this.finalized&&this.VFCState.applyViewFrustumCulling(this.sceneModel)}destroy(){this.finalized&&this.sceneModel.off(this._onSceneRendering)}}class ls extends C{constructor(e,t={}){super(e,t),this._scene=e,this._vfcManagers={},this._vfcManagerList=[],this.enabled=t.enabled,this._init()}_init(){this._scene.on("rendering",(()=>{for(let e=0,t=this._vfcManagerList.length;e<t;e++)this._vfcManagerList[e].applyViewFrustumCulling()}))}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}get enabled(){return this._enabled}getVFCManager(e){const t=new rs(this.scene,e);return this._vfcManagers[t.id]=t,this._vfcManagerList=Object.values(this._vfcManagers),t}putVFCManager(e){delete this._vfcManagers[e.id],this._vfcManagerList=Object.values(this._vfcManagers)}destroy(){super.destroy()}}function os(e,t){const s={};let n,i;for(let a=0,r=t.length;a<r;a++)n=t[a],i=e.component[n],i?i.isEntity?s[n]=!0:e.warn("pick(): Component is not an Entity: "+n):e.warn("pick(): Component not found: "+n);return s}class cs extends C{get type(){return"Scene"}constructor(e,t={}){super(null,t);const s=t.canvasElement||document.getElementById(t.canvasId);if(!(s instanceof HTMLCanvasElement))throw"Mandatory config expected: valid canvasId or canvasElement";const n=!!t.transparent,i=!!t.alphaDepthMask;this._aabbDirty=!0,this.viewer=e,this.occlusionTestCountdown=0,this.loading=0,this.startTime=(new Date).getTime(),this.models={},this.objects={},this._numObjects=0,this.visibleObjects={},this._numVisibleObjects=0,this.xrayedObjects={},this._numXRayedObjects=0,this.highlightedObjects={},this._numHighlightedObjects=0,this.selectedObjects={},this._numSelectedObjects=0,this.colorizedObjects={},this._numColorizedObjects=0,this.opacityObjects={},this._numOpacityObjects=0,this.offsetObjects={},this._numOffsetObjects=0,this._modelIds=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this._opacityObjectIds=null,this._offsetObjectIds=null,this._collidables={},this._compilables={},this._needRecompile=!1,this.types={},this.components={},this.sectionPlanes={},this.lights={},this.lightMaps={},this.reflectionMaps={},this.bitmaps={},this.lineSets={},this.realWorldOffset=t.realWorldOffset||new Float64Array([0,0,0]),this.canvas=new he(this,{dontClear:!0,canvas:s,spinnerElementId:t.spinnerElementId,transparent:n,webgl2:!1!==t.webgl2,contextAttr:t.contextAttr||{},backgroundColor:t.backgroundColor,backgroundColorFromAmbientLight:t.backgroundColorFromAmbientLight,premultipliedAlpha:t.premultipliedAlpha}),this.canvas.on("boundary",(()=>{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new He(this,{transparent:n,alphaDepthMask:i}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1;let e=null;this.getHash=function(){if(e)return e;const t=this.sectionPlanes;if(0===t.length)return this.hash=";";const s=[];for(let e=0,n=t.length;e<n;e++)s.push("cp");return s.push(";"),e=s.join(""),e},this.addSectionPlane=function(t){this.sectionPlanes.push(t),e=null},this.removeSectionPlane=function(t){for(let s=0,n=this.sectionPlanes.length;s<n;s++)if(this.sectionPlanes[s].id===t.id)return this.sectionPlanes.splice(s,1),void(e=null)}},this._lightsState=new function(){const e=h.vec4([0,0,0,0]),t=h.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let s=null,n=null;this.getHash=function(){if(s)return s;const e=[],t=this.lights;let n;for(let s=0,i=t.length;s<i;s++)n=t[s],e.push("/"),e.push(n.type),e.push("world"===n.space?"w":"v"),n.castsShadow&&e.push("sh");return this.lightMaps.length>0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),s=e.join(""),s},this.addLight=function(e){this.lights.push(e),n=null,s=null},this.removeLight=function(e){for(let t=0,i=this.lights.length;t<i;t++){if(this.lights[t].id===e.id)return this.lights.splice(t,1),n&&n.id===e.id&&(n=null),void(s=null)}},this.addReflectionMap=function(e){this.reflectionMaps.push(e),s=null},this.removeReflectionMap=function(e){for(let t=0,n=this.reflectionMaps.length;t<n;t++)if(this.reflectionMaps[t].id===e.id)return this.reflectionMaps.splice(t,1),void(s=null)},this.addLightMap=function(e){this.lightMaps.push(e),s=null},this.removeLightMap=function(e){for(let t=0,n=this.lightMaps.length;t<n;t++)if(this.lightMaps[t].id===e.id)return this.lightMaps.splice(t,1),void(s=null)},this.getAmbientColorAndIntensity=function(){if(!n)for(let e=0,t=this.lights.length;e<t;e++){const t=this.lights[e];if("ambient"===t.type){n=t;break}}if(n){const e=n.color,s=n.intensity;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=s,t}return e}},this.input=new Ue(this,{dontClear:!0,element:this.canvas.canvas,keyboardEventsElement:t.keyboardEventsElement}),this.metrics=new xt(this,{units:t.units,scale:t.scale,origin:t.origin}),this.sao=new Lt(this,{enabled:t.saoEnabled}),this.ticksPerRender=t.ticksPerRender,this.ticksPerOcclusionTest=t.ticksPerOcclusionTest,this.passes=t.passes,this.clearEachPass=t.clearEachPass,this.gammaInput=t.gammaInput,this.gammaOutput=t.gammaOutput,this.gammaFactor=t.gammaFactor,this._entityOffsetsEnabled=!!t.entityOffsetsEnabled,this._logarithmicDepthBufferEnabled=!!t.logarithmicDepthBufferEnabled,this._dtxEnabled=!1!==t.dtxEnabled,this._pbrEnabled=!!t.pbrEnabled,this._colorTextureEnabled=!1!==t.colorTextureEnabled,this._dtxEnabled=!!t.dtxEnabled,P._addScene(this),this._initDefaults(),this._viewport=new je(this,{id:"default.viewport",autoBoundary:!0,dontClear:!0}),this._camera=new ot(this,{id:"default.camera",dontClear:!0}),new ht(this,{color:[1,1,1],intensity:.7}),new ut(this,{dir:[.8,-.5,-.5],color:[.67,.67,1],intensity:.7,space:"world"}),new ut(this,{dir:[-.8,-1,.5],color:[1,1,.9],intensity:.9,space:"world"}),this._camera.on("dirty",(()=>{this._renderer.imageDirty()})),this.lod=new Xt(this,{enabled:t.lodEnabled}),this.vfc=new ls(this,{enabled:t.vfcEnabled})}_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=h.createUUID();this.components[e.id]=e;const t=e.type;let s=this.types[e.type];s||(s=this.types[t]={}),s[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,s=e.type;delete this.components[t];const n=this.types[s];n&&(delete n[t],y.isEmptyObject(n)&&delete this.types[s]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_objectHighlightedUpdated(e,t=!0){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null,t&&this.fire("objectHighlighted",e,!0)}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const s=this.components[t];s._webglContextRestored&&s._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&P.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const s=this._passes,n=this._clearEachPass;let i,a;for(i=0;i<s;i++)t.pass=i,this.fire("rendering",t,!0),a=n||0===i,this._renderer.render({pass:i,clear:a,force:e}),this.fire("rendered",t,!0);this._saveAmbientColor()}_recompile(){for(const e in this._compilables)this._compilables.hasOwnProperty(e)&&this._compilables[e].compile();this._renderer.shadowsDirty(),this.fire("compile",this,!0)}_saveAmbientColor(){const e=this.canvas;if(e.transparent||e.backgroundImage||e.backgroundColor)this._lastAmbientColor=null;else{const t=this._lightsState.getAmbientColorAndIntensity();this._lastAmbientColor&&this._lastAmbientColor[0]===t[0]&&this._lastAmbientColor[1]===t[1]&&this._lastAmbientColor[2]===t[2]&&this._lastAmbientColor[3]===t[3]||(e.backgroundColor=t,this._lastAmbientColor||(this._lastAmbientColor=h.vec4([0,0,0,1])),this._lastAmbientColor.set(t))}}get modelIds(){return this._modelIds||(this._modelIds=Object.keys(this.models)),this._modelIds}get numObjects(){return this._numObjects}get objectIds(){return this._objectIds||(this._objectIds=Object.keys(this.objects)),this._objectIds}get numVisibleObjects(){return this._numVisibleObjects}get visibleObjectIds(){return this._visibleObjectIds||(this._visibleObjectIds=Object.keys(this.visibleObjects)),this._visibleObjectIds}get numXRayedObjects(){return this._numXRayedObjects}get xrayedObjectIds(){return this._xrayedObjectIds||(this._xrayedObjectIds=Object.keys(this.xrayedObjects)),this._xrayedObjectIds}get numHighlightedObjects(){return this._numHighlightedObjects}get highlightedObjectIds(){return this._highlightedObjectIds||(this._highlightedObjectIds=Object.keys(this.highlightedObjects)),this._highlightedObjectIds}get numSelectedObjects(){return this._numSelectedObjects}get selectedObjectIds(){return this._selectedObjectIds||(this._selectedObjectIds=Object.keys(this.selectedObjects)),this._selectedObjectIds}get numColorizedObjects(){return this._numColorizedObjects}get colorizedObjectIds(){return this._colorizedObjectIds||(this._colorizedObjectIds=Object.keys(this.colorizedObjects)),this._colorizedObjectIds}get opacityObjectIds(){return this._opacityObjectIds||(this._opacityObjectIds=Object.keys(this.opacityObjects)),this._opacityObjectIds}get offsetObjectIds(){return this._offsetObjectIds||(this._offsetObjectIds=Object.keys(this.offsetObjects)),this._offsetObjectIds}set ticksPerRender(e){null==e?e=1:(!y.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerRender': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._ticksPerRender&&(this._ticksPerRender=e)}get ticksPerRender(){return this._ticksPerRender}set ticksPerOcclusionTest(e){null==e?e=20:(!y.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerOcclusionTest': '"+e+"' - should be an integer greater than zero."),e=20),e!==this._ticksPerOcclusionTest&&(this._ticksPerOcclusionTest=e)}get ticksPerOcclusionTest(){return this._ticksPerOcclusionTest}set passes(e){null==e?e=1:(!y.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'passes': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._passes&&(this._passes=e,this.glRedraw())}get passes(){return this._passes}set clearEachPass(e){(e=!!e)!==this._clearEachPass&&(this._clearEachPass=e,this.glRedraw())}get clearEachPass(){return this._clearEachPass}set gammaInput(e){(e=!1!==e)!==this._renderer.gammaInput&&(this._renderer.gammaInput=e,this._needRecompile=!0,this.glRedraw())}get gammaInput(){return this._renderer.gammaInput}set gammaOutput(e){(e=!!e)!==this._renderer.gammaOutput&&(this._renderer.gammaOutput=e,this._needRecompile=!0,this.glRedraw())}get gammaOutput(){return this._renderer.gammaOutput}set gammaFactor(e){(e=null==e?2.2:e)!==this._renderer.gammaFactor&&(this._renderer.gammaFactor=e,this.glRedraw())}get gammaFactor(){return this._renderer.gammaFactor}get geometry(){return this.components["default.geometry"]||bt(Et)}get material(){return this.components["default.material"]||new Ct(this,{id:"default.material",emissive:[.4,.4,.4],dontClear:!0})}get xrayMaterial(){return this.components["default.xrayMaterial"]||new Bt(this,{id:"default.xrayMaterial",preset:"sepia",dontClear:!0})}get highlightMaterial(){return this.components["default.highlightMaterial"]||new Bt(this,{id:"default.highlightMaterial",preset:"yellowHighlight",dontClear:!0})}get selectedMaterial(){return this.components["default.selectedMaterial"]||new Bt(this,{id:"default.selectedMaterial",preset:"greenSelected",dontClear:!0})}get edgeMaterial(){return this.components["default.edgeMaterial"]||new St(this,{id:"default.edgeMaterial",preset:"default",edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get pointsMaterial(){return this.components["default.pointsMaterial"]||new Ft(this,{id:"default.pointsMaterial",preset:"default",dontClear:!0})}get linesMaterial(){return this.components["default.linesMaterial"]||new Ut(this,{id:"default.linesMaterial",preset:"default",dontClear:!0})}get viewport(){return this._viewport}get camera(){return this._camera}get center(){if(this._aabbDirty||!this._center){this._center&&this._center||(this._center=h.vec3());const e=this.aabb;this._center[0]=(e[0]+e[3])/2,this._center[1]=(e[1]+e[4])/2,this._center[2]=(e[2]+e[5])/2}return this._center}get aabb(){if(this._aabbDirty){this._aabb||(this._aabb=h.AABB3());let e,t=h.MAX_DOUBLE,s=h.MAX_DOUBLE,n=h.MAX_DOUBLE,i=h.MIN_DOUBLE,a=h.MIN_DOUBLE,r=h.MIN_DOUBLE;const l=this._collidables;let o,c=!1;for(const u in l)if(l.hasOwnProperty(u)){if(o=l[u],!1===o.collidable)continue;e=o.aabb,e[0]<t&&(t=e[0]),e[1]<s&&(s=e[1]),e[2]<n&&(n=e[2]),e[3]>i&&(i=e[3]),e[4]>a&&(a=e[4]),e[5]>r&&(r=e[5]),c=!0}c||(t=-100,s=-100,n=-100,i=100,a=100,r=100),this._aabb[0]=t,this._aabb[1]=s,this._aabb[2]=n,this._aabb[3]=i,this._aabb[4]=a,this._aabb[5]=r,this._aabbDirty=!1}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const s=e.includeEntities||e.include;s&&(e.includeEntityIds=os(this,s));const n=e.excludeEntities||e.exclude;return n&&(e.excludeEntityIds=os(this,n)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=this._renderer.pick(e,t))?(t.entity&&t.entity.fire&&t.entity.fire("picked",t),t):void 0}snapPick(e){return this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapMode||"vertex")}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,s=e.length;t<s;t++)this.lights[e[t]].destroy()}clearSectionPlanes(){const e=Object.keys(this.sectionPlanes);for(let t=0,s=e.length;t<s;t++)this.sectionPlanes[e[t]].destroy()}clearBitmaps(){const e=Object.keys(this.bitmaps);for(let t=0,s=e.length;t<s;t++)this.bitmaps[e[t]].destroy()}clearLines(){const e=Object.keys(this.lineSets);for(let t=0,s=e.length;t<s;t++)this.lineSets[e[t]].destroy()}getAABB(e){if(void 0===e)return this.aabb;if(y.isString(e)){const t=this.objects[e];if(t&&t.aabb)return t.aabb;e=[e]}if(0===e.length)return this.aabb;let t,s=h.MAX_DOUBLE,n=h.MAX_DOUBLE,i=h.MAX_DOUBLE,a=h.MIN_DOUBLE,r=h.MIN_DOUBLE,l=h.MIN_DOUBLE;if(this.withObjects(e,(e=>{if(e.collidable){const o=e.aabb;o[0]<s&&(s=o[0]),o[1]<n&&(n=o[1]),o[2]<i&&(i=o[2]),o[3]>a&&(a=o[3]),o[4]>r&&(r=o[4]),o[5]>l&&(l=o[5]),t=!0}})),t){const e=h.AABB3();return e[0]=s,e[1]=n,e[2]=i,e[3]=a,e[4]=r,e[5]=l,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const s=e.visible!==t;return e.visible=t,s}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const s=e.collidable!==t;return e.collidable=t,s}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const s=e.culled!==t;return e.culled=t,s}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const s=e.selected!==t;return e.selected=t,s}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const s=e.highlighted!==t;return e.highlighted=t,s}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const s=e.xrayed!==t;return e.xrayed=t,s}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const s=e.edges!==t;return e.edges=t,s}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const s=e.opacity!==t;return e.opacity=t,s}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const s=e.pickable!==t;return e.pickable=t,s}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){y.isString(e)&&(e=[e]);let s=!1;for(let n=0,i=e.length;n<i;n++){const i=e[n];let a=this.objects[i];if(a)s=t(a)||s;else{const e=this.modelIds;for(let n=0,r=e.length;n<r;n++){const r=e[n],l=h.globalizeObjectId(r,i);a=this.objects[l],a&&(s=t(a)||s)}}}return s}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.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 us=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,s=e.scene._sectionPlanesState,n=e.scene._lightsState,i=e._geometry._state,a=e._state.billboard,r=e._state.stationary,l=s.sectionPlanes.length>0,o=!!i.compressGeometry,c=[];c.push("#version 300 es"),c.push("// Lambertian drawing vertex shader"),c.push("in vec3 position;"),c.push("uniform mat4 modelMatrix;"),c.push("uniform mat4 viewMatrix;"),c.push("uniform mat4 projMatrix;"),c.push("uniform vec4 colorize;"),c.push("uniform vec3 offset;"),o&&c.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(c.push("uniform float logDepthBufFC;"),c.push("out float vFragDepth;"),c.push("bool isPerspectiveMatrix(mat4 m) {"),c.push(" return (m[2][3] == - 1.0);"),c.push("}"),c.push("out float isPerspective;"));l&&c.push("out vec4 vWorldPosition;");if(c.push("uniform vec4 lightAmbient;"),c.push("uniform vec4 materialColor;"),c.push("uniform vec3 materialEmissive;"),i.normalsBuf){c.push("in vec3 normal;"),c.push("uniform mat4 modelNormalMatrix;"),c.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];"ambient"!==t.type&&(c.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&c.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&c.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(c.push("uniform vec3 lightPos"+e+";"),c.push("uniform vec3 lightDir"+e+";")))}o&&(c.push("vec3 octDecode(vec2 oct) {"),c.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),c.push(" if (v.z < 0.0) {"),c.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);"),c.push(" }"),c.push(" return normalize(v);"),c.push("}"))}c.push("out vec4 vColor;"),"points"===i.primitiveName&&c.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(c.push("void billboard(inout mat4 mat) {"),c.push(" mat[0][0] = 1.0;"),c.push(" mat[0][1] = 0.0;"),c.push(" mat[0][2] = 0.0;"),"spherical"===a&&(c.push(" mat[1][0] = 0.0;"),c.push(" mat[1][1] = 1.0;"),c.push(" mat[1][2] = 0.0;")),c.push(" mat[2][0] = 0.0;"),c.push(" mat[2][1] = 0.0;"),c.push(" mat[2][2] =1.0;"),c.push("}"));c.push("void main(void) {"),c.push("vec4 localPosition = vec4(position, 1.0); "),c.push("vec4 worldPosition;"),o&&c.push("localPosition = positionsDecodeMatrix * localPosition;");i.normalsBuf&&(o?c.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):c.push("vec4 localNormal = vec4(normal, 0.0); "),c.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),c.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));c.push("mat4 viewMatrix2 = viewMatrix;"),c.push("mat4 modelMatrix2 = modelMatrix;"),r&&c.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===a||"cylindrical"===a?(c.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),c.push("billboard(modelMatrix2);"),c.push("billboard(viewMatrix2);"),c.push("billboard(modelViewMatrix);"),i.normalsBuf&&(c.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),c.push("billboard(modelNormalMatrix2);"),c.push("billboard(viewNormalMatrix2);"),c.push("billboard(modelViewNormalMatrix);")),c.push("worldPosition = modelMatrix2 * localPosition;"),c.push("worldPosition.xyz = worldPosition.xyz + offset;"),c.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(c.push("worldPosition = modelMatrix2 * localPosition;"),c.push("worldPosition.xyz = worldPosition.xyz + offset;"),c.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i.normalsBuf&&c.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(c.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),c.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),c.push("float lambertian = 1.0;"),i.normalsBuf)for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?c.push("viewLightDir = normalize(lightDir"+e+");"):c.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?c.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):c.push("viewLightDir = -normalize((viewMatrix2 * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?c.push("viewLightDir = normalize(lightDir"+e+");"):c.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);")}c.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),c.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}c.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * materialColor.rgb) + materialEmissive.rgb + (reflectedColor * materialColor.rgb), materialColor.a) * colorize;"),l&&c.push("vWorldPosition = worldPosition;");"points"===i.primitiveName&&c.push("gl_PointSize = pointSize;");c.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(c.push("vFragDepth = 1.0 + clipPos.w;"),c.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return c.push("gl_Position = clipPos;"),c.push("}"),c}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState;e._material._state;const n=e._geometry._state,i=s.sectionPlanes.length>0,a=t.gammaOutput,r=[];r.push("#version 300 es"),r.push("// Lambertian drawing fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(i){r.push("in vec4 vWorldPosition;"),r.push("uniform bool clippable;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}r.push("in vec4 vColor;"),a&&(r.push("uniform float gammaFactor;"),r.push(" vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),r.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),r.push("}"));if(r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push("if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}"points"===n.primitiveName&&(r.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),r.push("float r = dot(cxy, cxy);"),r.push("if (r > 1.0) {"),r.push(" discard;"),r.push("}"));t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");a?r.push("outColor = linearToGamma(vColor, gammaFactor);"):r.push("outColor = vColor;");return r.push("}"),r}(e)):(this.vertex=function(e){const t=e.scene;e._material;const s=e._state,n=t._sectionPlanesState,i=e._geometry._state,a=t._lightsState;let r;const l=s.billboard,o=s.background,c=s.stationary,u=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),h=As(e),p=n.sectionPlanes.length>0,A=ps(e),d=!!i.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),d&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),p&&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;"));a.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(h){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(let e=0,t=a.lights.length;e<t;e++)r=a.lights[e],"ambient"!==r.type&&("dir"===r.type&&f.push("uniform vec3 lightDir"+e+";"),"point"===r.type&&f.push("uniform vec3 lightPos"+e+";"),"spot"===r.type&&(f.push("uniform vec3 lightPos"+e+";"),f.push("uniform vec3 lightDir"+e+";")),"dir"===r.type&&"view"===r.space||f.push("out vec4 vViewLightReverseDirAndDist"+e+";"));d&&(f.push("vec3 octDecode(vec2 oct) {"),f.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),f.push(" if (v.z < 0.0) {"),f.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}u&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),d&&f.push("uniform mat3 uvDecodeMatrix;"));i.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===i.primitiveName&&f.push("uniform float pointSize;");"spherical"!==l&&"cylindrical"!==l||(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"===l&&(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(A){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=a.lights.length;e<t;e++)a.lights[e].castsShadow&&(f.push("uniform mat4 shadowViewMatrix"+e+";"),f.push("uniform mat4 shadowProjMatrix"+e+";"),f.push("out vec4 vShadowPosFromLight"+e+";"))}f.push("void main(void) {"),f.push("vec4 localPosition = vec4(position, 1.0); "),f.push("vec4 worldPosition;"),d&&f.push("localPosition = positionsDecodeMatrix * localPosition;");h&&(d?f.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):f.push("vec4 localNormal = vec4(normal, 0.0); "),f.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),f.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));f.push("mat4 viewMatrix2 = viewMatrix;"),f.push("mat4 modelMatrix2 = modelMatrix;"),c?f.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"):o&&f.push("viewMatrix2[3] = vec4(0.0, 0.0, 0.0 ,1.0);");"spherical"===l||"cylindrical"===l?(f.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),f.push("billboard(modelMatrix2);"),f.push("billboard(viewMatrix2);"),f.push("billboard(modelViewMatrix);"),h&&(f.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),f.push("billboard(modelNormalMatrix2);"),f.push("billboard(viewNormalMatrix2);"),f.push("billboard(modelViewNormalMatrix);")),f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));if(h){f.push("vec3 worldNormal = (modelNormalMatrix2 * localNormal).xyz; "),a.lightMaps.length>0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(let e=0,t=a.lights.length;e<t;e++)r=a.lights[e],"ambient"!==r.type&&("dir"===r.type&&"world"===r.space&&(f.push("tmpVec3 = vec3(viewMatrix2 * vec4(lightDir"+e+", 0.0) ).xyz;"),f.push("vViewLightReverseDirAndDist"+e+" = vec4(-tmpVec3, 0.0);")),"point"===r.type&&("world"===r.space?(f.push("tmpVec3 = (viewMatrix2 * vec4(lightPos"+e+", 1.0)).xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")):(f.push("tmpVec3 = lightPos"+e+".xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")),f.push("vViewLightReverseDirAndDist"+e+" = vec4(tmpVec3, lightDist);")))}u&&(d?f.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"):f.push("vUV = uv;"));i.colors&&f.push("vColor = color;");"points"===i.primitiveName&&f.push("gl_PointSize = pointSize;");p&&f.push("vWorldPosition = worldPosition;");f.push(" vViewPosition = viewPosition.xyz;"),f.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(f.push("vFragDepth = 1.0 + clipPos.w;"),f.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));o&&f.push("clipPos.z = clipPos.w;");if(f.push("gl_Position = clipPos;"),A){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);"),f.push("vec4 tempx; ");for(let e=0,t=a.lights.length;e<t;e++)a.lights[e].castsShadow&&f.push("vShadowPosFromLight"+e+" = texUnitConverter * shadowProjMatrix"+e+" * (shadowViewMatrix"+e+" * worldPosition); ")}return f.push("}"),f}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const s=e._material,n=e._geometry._state,i=e.scene._sectionPlanesState,a=e.scene._lightsState,r=e._material._state,l=i.sectionPlanes.length>0,o=As(e),c=n.uvBuf,u="PhongMaterial"===r.type,h="MetallicMaterial"===r.type,p="SpecularMaterial"===r.type,A=ps(e);t.gammaInput;const d=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));A&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),d&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(l){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var I=0;I<i.sectionPlanes.length;I++)f.push("uniform bool sectionPlaneActive"+I+";"),f.push("uniform vec3 sectionPlanePos"+I+";"),f.push("uniform vec3 sectionPlaneDir"+I+";")}o&&(a.lightMaps.length>0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),a.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(a.lightMaps.length>0||a.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("};"),u&&((a.lightMaps.length>0||a.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.lightMaps.length>0&&(f.push(" vec3 irradiance = "+hs[a.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;")),a.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(h||p)&&(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("}"),a.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 = "+hs[a.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("}"),(a.lightMaps.length>0||a.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.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;")),a.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;"),n.colors&&f.push("in vec4 vColor;");c&&(o&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._occlusionMap||s._alphaMap)&&f.push("in vec2 vUV;");o&&(a.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));r.ambient&&f.push("uniform vec3 materialAmbient;");r.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==r.alpha&&null!==r.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");r.emissive&&f.push("uniform vec3 materialEmissive;");r.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==r.glossiness&&null!==r.glossiness&&f.push("uniform float materialGlossiness;");void 0!==r.shininess&&null!==r.shininess&&f.push("uniform float materialShininess;");r.specular&&f.push("uniform vec3 materialSpecular;");void 0!==r.metallic&&null!==r.metallic&&f.push("uniform float materialMetallic;");void 0!==r.roughness&&null!==r.roughness&&f.push("uniform float materialRoughness;");void 0!==r.specularF0&&null!==r.specularF0&&f.push("uniform float materialSpecularF0;");c&&s._ambientMap&&(f.push("uniform sampler2D ambientMap;"),s._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));c&&s._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),s._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));c&&s._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),s._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));c&&s._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),s._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));o&&c&&s._metallicMap&&(f.push("uniform sampler2D metallicMap;"),s._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));o&&c&&s._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),s._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));o&&c&&s._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),s._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));o&&s._normalMap&&(f.push("uniform sampler2D normalMap;"),s._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));c&&s._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),s._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));c&&s._alphaMap&&(f.push("uniform sampler2D alphaMap;"),s._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));o&&c&&s._specularMap&&(f.push("uniform sampler2D specularMap;"),s._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));o&&c&&s._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),s._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));o&&c&&s._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),s._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));o&&(s._diffuseFresnel||s._specularFresnel||s._alphaFresnel||s._emissiveFresnel||s._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),s._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),s._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),s._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),s._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),s._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),o)for(let e=0,t=a.lights.length;e<t;e++){const t=a.lights[e];"ambient"!==t.type&&(f.push("uniform vec4 lightColor"+e+";"),"point"===t.type&&f.push("uniform vec3 lightAttenuation"+e+";"),"dir"===t.type&&"view"===t.space&&f.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&"view"===t.space?f.push("uniform vec3 lightPos"+e+";"):f.push("in vec4 vViewLightReverseDirAndDist"+e+";"))}if(A)for(let e=0,t=a.lights.length;e<t;e++)a.lights[e].castsShadow&&(f.push("in vec4 vShadowPosFromLight"+e+";"),f.push("uniform sampler2D shadowMap"+e+";"));if(f.push("uniform vec4 colorize;"),f.push("out vec4 outColor;"),f.push("void main(void) {"),l){f.push("if (clippable) {"),f.push(" float dist = 0.0;");for(I=0;I<i.sectionPlanes.length;I++)f.push("if (sectionPlaneActive"+I+") {"),f.push(" dist += clamp(dot(-sectionPlaneDir"+I+".xyz, vWorldPosition.xyz - sectionPlanePos"+I+".xyz), 0.0, 1000.0);"),f.push("}");f.push(" if (dist > 0.0) { discard; }"),f.push("}")}"points"===n.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;"),r.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");r.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):r.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");n.colors&&f.push("diffuseColor *= vColor.rgb;");r.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");r.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==r.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");n.colors&&f.push("alpha *= vColor.a;");void 0!==r.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==r.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==r.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==r.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");c&&(o&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._occlusionMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));c&&s._ambientMap&&(s._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+hs[s._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));c&&s._diffuseMap&&(s._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+hs[s._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));c&&s._baseColorMap&&(s._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+hs[s._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));c&&s._emissiveMap&&(s._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+hs[s._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));c&&s._alphaMap&&(s._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));c&&s._occlusionMap&&(s._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(o&&(a.lights.length>0||a.lightMaps.length>0||a.reflectionMaps.length>0)){c&&s._normalMap?(s._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),c&&s._specularMap&&(s._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),c&&s._glossinessMap&&(s._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),c&&s._specularGlossinessMap&&(s._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),c&&s._metallicMap&&(s._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),c&&s._roughnessMap&&(s._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),c&&s._metallicRoughnessMap&&(s._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),s._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),s._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),s._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),s._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),u&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),p&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),h&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),a.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),u&&(a.lightMaps.length>0||a.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(p||h)&&(a.lightMaps.length>0||a.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=a.lights.length;e<t;e++){const t=a.lights[e];"ambient"!==t.type&&("dir"===t.type&&"view"===t.space?f.push("viewLightDir = -normalize(lightDir"+e+");"):"point"===t.type&&"view"===t.space?f.push("viewLightDir = normalize(lightPos"+e+" - vViewPosition);"):f.push("viewLightDir = normalize(vViewLightReverseDirAndDist"+e+".xyz);"),A&&t.castsShadow?(f.push("shadow = 0.0;"),f.push("fragmentDepth = vShadowPosFromLight"+e+".xyz;"),f.push("fragmentDepth.z -= shadowAcneRemover;"),f.push("for (int x = -3; x <= 3; x++) {"),f.push(" for (int y = -3; y <= 3; y++) {"),f.push(" float texelDepth = unpackDepth(texture(shadowMap"+e+", fragmentDepth.xy + vec2(x, y) * texelSize));"),f.push(" if (fragmentDepth.z < texelDepth) {"),f.push(" shadow += 1.0;"),f.push(" }"),f.push(" }"),f.push("}"),f.push("shadow = shadow / 9.0;"),f.push("light.color = lightColor"+e+".rgb * (lightColor"+e+".a * shadow);")):f.push("light.color = lightColor"+e+".rgb * (lightColor"+e+".a );"),f.push("light.direction = viewLightDir;"),u&&f.push("computePhongLighting(light, geometry, material, reflectedLight);"),(p||h)&&f.push("computePBRLighting(light, geometry, material, reflectedLight);"))}u?f.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * diffuseColor) + ((occlusion * (( reflectedLight.diffuse + reflectedLight.specular)))) + emissiveColor;"):f.push("vec3 outgoingLight = (occlusion * (reflectedLight.diffuse)) + (occlusion * reflectedLight.specular) + emissiveColor;")}else f.push("ambientColor *= (lightAmbient.rgb * lightAmbient.a);"),f.push("vec3 outgoingLight = emissiveColor + ambientColor;");f.push("vec4 fragColor = vec4(outgoingLight, alpha) * colorize;"),d&&f.push("fragColor = linearToGamma(fragColor, gammaFactor);");f.push("outColor = fragColor;"),t.logarithmicDepthBufferEnabled&&f.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return f.push("}"),f}(e))},hs={};function ps(e){if(!e.receivesShadow)return!1;const t=e.scene._lightsState.lights;if(!t||0===t.length)return!1;for(let e=0,s=t.length;e<s;e++)if(t[e].castsShadow)return!0;return!1}function As(e){const t=e._geometry._state.primitiveName;return!(!e._geometry._state.autoVertexNormals&&!e._geometry._state.normalsBuf||"triangles"!==t&&"triangle-strip"!==t&&"triangle-fan"!==t)}hs[3e3]="linearToLinear",hs[3001]="sRGBToLinear";const ds=h.vec3(),fs=new e({}),Is=function(e,t){this.id=fs.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new us(t),this._allocate(t)},ys={};Is.get=function(e){const t=e.scene,s=[t.canvas.canvas.id,(t.gammaInput?"gi;":";")+(t.gammaOutput?"go":""),t._lightsState.getHash(),t._sectionPlanesState.getHash(),e._geometry._state.hash,e._material._state.hash,e._state.drawHash].join(";");let n=ys[s];if(!n){if(n=new Is(s,e),n.errors)return console.log(n.errors.join("\n")),null;ys[s]=n,A.memory.programs++}return n._useCount++,n},Is.prototype.put=function(){0==--this._useCount&&(fs.removeItem(this.id),this._program&&this._program.destroy(),delete ys[this._hash],A.memory.programs--)},Is.prototype.webglContextRestored=function(){this._program=null},Is.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=oe.MAX_TEXTURE_UNITS,n=t.scene,i=t._material,a=n.canvas.gl,r=this._program,l=t._state,o=t._material._state,c=t._geometry._state,u=n.camera,h=t.origin,p=l.background;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,p&&a.depthFunc(a.LEQUAL),this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(l.originHash,h):u.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,u.viewNormalMatrix),l.clippable){const e=n._sectionPlanesState.sectionPlanes.length;if(e>0){const s=n._sectionPlanesState.sectionPlanes,i=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const n=i.sectionPlanesActivePerLayer[t];if(a.uniform1i(e.active,n?1:0),n){const n=s[t];a.uniform3fv(e.pos,h?N(n.dist,n.dir,h,ds):n.pos),a.uniform3fv(e.dir,n.dir)}}}}}if(o.id!==this._lastMaterialId){e.textureUnit=this._baseTextureUnit;const t=o.backfaces;e.backfaces!==t&&(t?a.disable(a.CULL_FACE):a.enable(a.CULL_FACE),e.backfaces=t);const n=o.frontface;switch(e.frontface!==n&&(n?a.frontFace(a.CCW):a.frontFace(a.CW),e.frontface=n),e.lineWidth!==o.lineWidth&&(a.lineWidth(o.lineWidth),e.lineWidth=o.lineWidth),this._uPointSize&&a.uniform1f(this._uPointSize,o.pointSize),o.type){case"LambertMaterial":this._uMaterialAmbient&&a.uniform3fv(this._uMaterialAmbient,o.ambient),this._uMaterialColor&&a.uniform4f(this._uMaterialColor,o.color[0],o.color[1],o.color[2],o.alpha),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive);break;case"PhongMaterial":this._uMaterialShininess&&a.uniform1f(this._uMaterialShininess,o.shininess),this._uMaterialAmbient&&a.uniform3fv(this._uMaterialAmbient,o.ambient),this._uMaterialDiffuse&&a.uniform3fv(this._uMaterialDiffuse,o.diffuse),this._uMaterialSpecular&&a.uniform3fv(this._uMaterialSpecular,o.specular),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive),this._uAlphaModeCutoff&&a.uniform4f(this._uAlphaModeCutoff,1*o.alpha,1===o.alphaMode?1:0,o.alphaCutoff,0),i._ambientMap&&i._ambientMap._state.texture&&this._uMaterialAmbientMap&&(r.bindTexture(this._uMaterialAmbientMap,i._ambientMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uMaterialAmbientMapMatrix&&a.uniformMatrix4fv(this._uMaterialAmbientMapMatrix,!1,i._ambientMap._state.matrix)),i._diffuseMap&&i._diffuseMap._state.texture&&this._uDiffuseMap&&(r.bindTexture(this._uDiffuseMap,i._diffuseMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uDiffuseMapMatrix&&a.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,i._diffuseMap._state.matrix)),i._specularMap&&i._specularMap._state.texture&&this._uSpecularMap&&(r.bindTexture(this._uSpecularMap,i._specularMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uSpecularMapMatrix&&a.uniformMatrix4fv(this._uSpecularMapMatrix,!1,i._specularMap._state.matrix)),i._emissiveMap&&i._emissiveMap._state.texture&&this._uEmissiveMap&&(r.bindTexture(this._uEmissiveMap,i._emissiveMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uEmissiveMapMatrix&&a.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,i._emissiveMap._state.matrix)),i._alphaMap&&i._alphaMap._state.texture&&this._uAlphaMap&&(r.bindTexture(this._uAlphaMap,i._alphaMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uAlphaMapMatrix&&a.uniformMatrix4fv(this._uAlphaMapMatrix,!1,i._alphaMap._state.matrix)),i._reflectivityMap&&i._reflectivityMap._state.texture&&this._uReflectivityMap&&(r.bindTexture(this._uReflectivityMap,i._reflectivityMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,this._uReflectivityMapMatrix&&a.uniformMatrix4fv(this._uReflectivityMapMatrix,!1,i._reflectivityMap._state.matrix)),i._normalMap&&i._normalMap._state.texture&&this._uNormalMap&&(r.bindTexture(this._uNormalMap,i._normalMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uNormalMapMatrix&&a.uniformMatrix4fv(this._uNormalMapMatrix,!1,i._normalMap._state.matrix)),i._occlusionMap&&i._occlusionMap._state.texture&&this._uOcclusionMap&&(r.bindTexture(this._uOcclusionMap,i._occlusionMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uOcclusionMapMatrix&&a.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,i._occlusionMap._state.matrix)),i._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias&&a.uniform1f(this._uDiffuseFresnelEdgeBias,i._diffuseFresnel.edgeBias),this._uDiffuseFresnelCenterBias&&a.uniform1f(this._uDiffuseFresnelCenterBias,i._diffuseFresnel.centerBias),this._uDiffuseFresnelEdgeColor&&a.uniform3fv(this._uDiffuseFresnelEdgeColor,i._diffuseFresnel.edgeColor),this._uDiffuseFresnelCenterColor&&a.uniform3fv(this._uDiffuseFresnelCenterColor,i._diffuseFresnel.centerColor),this._uDiffuseFresnelPower&&a.uniform1f(this._uDiffuseFresnelPower,i._diffuseFresnel.power)),i._specularFresnel&&(this._uSpecularFresnelEdgeBias&&a.uniform1f(this._uSpecularFresnelEdgeBias,i._specularFresnel.edgeBias),this._uSpecularFresnelCenterBias&&a.uniform1f(this._uSpecularFresnelCenterBias,i._specularFresnel.centerBias),this._uSpecularFresnelEdgeColor&&a.uniform3fv(this._uSpecularFresnelEdgeColor,i._specularFresnel.edgeColor),this._uSpecularFresnelCenterColor&&a.uniform3fv(this._uSpecularFresnelCenterColor,i._specularFresnel.centerColor),this._uSpecularFresnelPower&&a.uniform1f(this._uSpecularFresnelPower,i._specularFresnel.power)),i._alphaFresnel&&(this._uAlphaFresnelEdgeBias&&a.uniform1f(this._uAlphaFresnelEdgeBias,i._alphaFresnel.edgeBias),this._uAlphaFresnelCenterBias&&a.uniform1f(this._uAlphaFresnelCenterBias,i._alphaFresnel.centerBias),this._uAlphaFresnelEdgeColor&&a.uniform3fv(this._uAlphaFresnelEdgeColor,i._alphaFresnel.edgeColor),this._uAlphaFresnelCenterColor&&a.uniform3fv(this._uAlphaFresnelCenterColor,i._alphaFresnel.centerColor),this._uAlphaFresnelPower&&a.uniform1f(this._uAlphaFresnelPower,i._alphaFresnel.power)),i._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias&&a.uniform1f(this._uReflectivityFresnelEdgeBias,i._reflectivityFresnel.edgeBias),this._uReflectivityFresnelCenterBias&&a.uniform1f(this._uReflectivityFresnelCenterBias,i._reflectivityFresnel.centerBias),this._uReflectivityFresnelEdgeColor&&a.uniform3fv(this._uReflectivityFresnelEdgeColor,i._reflectivityFresnel.edgeColor),this._uReflectivityFresnelCenterColor&&a.uniform3fv(this._uReflectivityFresnelCenterColor,i._reflectivityFresnel.centerColor),this._uReflectivityFresnelPower&&a.uniform1f(this._uReflectivityFresnelPower,i._reflectivityFresnel.power)),i._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias&&a.uniform1f(this._uEmissiveFresnelEdgeBias,i._emissiveFresnel.edgeBias),this._uEmissiveFresnelCenterBias&&a.uniform1f(this._uEmissiveFresnelCenterBias,i._emissiveFresnel.centerBias),this._uEmissiveFresnelEdgeColor&&a.uniform3fv(this._uEmissiveFresnelEdgeColor,i._emissiveFresnel.edgeColor),this._uEmissiveFresnelCenterColor&&a.uniform3fv(this._uEmissiveFresnelCenterColor,i._emissiveFresnel.centerColor),this._uEmissiveFresnelPower&&a.uniform1f(this._uEmissiveFresnelPower,i._emissiveFresnel.power));break;case"MetallicMaterial":this._uBaseColor&&a.uniform3fv(this._uBaseColor,o.baseColor),this._uMaterialMetallic&&a.uniform1f(this._uMaterialMetallic,o.metallic),this._uMaterialRoughness&&a.uniform1f(this._uMaterialRoughness,o.roughness),this._uMaterialSpecularF0&&a.uniform1f(this._uMaterialSpecularF0,o.specularF0),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive),this._uAlphaModeCutoff&&a.uniform4f(this._uAlphaModeCutoff,1*o.alpha,1===o.alphaMode?1:0,o.alphaCutoff,0);const t=i._baseColorMap;t&&t._state.texture&&this._uBaseColorMap&&(r.bindTexture(this._uBaseColorMap,t._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uBaseColorMapMatrix&&a.uniformMatrix4fv(this._uBaseColorMapMatrix,!1,t._state.matrix));const n=i._metallicMap;n&&n._state.texture&&this._uMetallicMap&&(r.bindTexture(this._uMetallicMap,n._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uMetallicMapMatrix&&a.uniformMatrix4fv(this._uMetallicMapMatrix,!1,n._state.matrix));const l=i._roughnessMap;l&&l._state.texture&&this._uRoughnessMap&&(r.bindTexture(this._uRoughnessMap,l._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uRoughnessMapMatrix&&a.uniformMatrix4fv(this._uRoughnessMapMatrix,!1,l._state.matrix));const c=i._metallicRoughnessMap;c&&c._state.texture&&this._uMetallicRoughnessMap&&(r.bindTexture(this._uMetallicRoughnessMap,c._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uMetallicRoughnessMapMatrix&&a.uniformMatrix4fv(this._uMetallicRoughnessMapMatrix,!1,c._state.matrix)),(A=i._emissiveMap)&&A._state.texture&&this._uEmissiveMap&&(r.bindTexture(this._uEmissiveMap,A._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uEmissiveMapMatrix&&a.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,A._state.matrix)),(d=i._occlusionMap)&&i._occlusionMap._state.texture&&this._uOcclusionMap&&(r.bindTexture(this._uOcclusionMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uOcclusionMapMatrix&&a.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,d._state.matrix)),(f=i._alphaMap)&&f._state.texture&&this._uAlphaMap&&(r.bindTexture(this._uAlphaMap,f._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uAlphaMapMatrix&&a.uniformMatrix4fv(this._uAlphaMapMatrix,!1,f._state.matrix)),(I=i._normalMap)&&I._state.texture&&this._uNormalMap&&(r.bindTexture(this._uNormalMap,I._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uNormalMapMatrix&&a.uniformMatrix4fv(this._uNormalMapMatrix,!1,I._state.matrix));break;case"SpecularMaterial":this._uMaterialDiffuse&&a.uniform3fv(this._uMaterialDiffuse,o.diffuse),this._uMaterialSpecular&&a.uniform3fv(this._uMaterialSpecular,o.specular),this._uMaterialGlossiness&&a.uniform1f(this._uMaterialGlossiness,o.glossiness),this._uMaterialReflectivity&&a.uniform1f(this._uMaterialReflectivity,o.reflectivity),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive),this._uAlphaModeCutoff&&a.uniform4f(this._uAlphaModeCutoff,1*o.alpha,1===o.alphaMode?1:0,o.alphaCutoff,0);const u=i._diffuseMap;u&&u._state.texture&&this._uDiffuseMap&&(r.bindTexture(this._uDiffuseMap,u._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uDiffuseMapMatrix&&a.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,u._state.matrix));const h=i._specularMap;h&&h._state.texture&&this._uSpecularMap&&(r.bindTexture(this._uSpecularMap,h._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uSpecularMapMatrix&&a.uniformMatrix4fv(this._uSpecularMapMatrix,!1,h._state.matrix));const p=i._glossinessMap;p&&p._state.texture&&this._uGlossinessMap&&(r.bindTexture(this._uGlossinessMap,p._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uGlossinessMapMatrix&&a.uniformMatrix4fv(this._uGlossinessMapMatrix,!1,p._state.matrix));const y=i._specularGlossinessMap;var A,d,f,I;y&&y._state.texture&&this._uSpecularGlossinessMap&&(r.bindTexture(this._uSpecularGlossinessMap,y._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uSpecularGlossinessMapMatrix&&a.uniformMatrix4fv(this._uSpecularGlossinessMapMatrix,!1,y._state.matrix)),(A=i._emissiveMap)&&A._state.texture&&this._uEmissiveMap&&(r.bindTexture(this._uEmissiveMap,A._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uEmissiveMapMatrix&&a.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,A._state.matrix)),(d=i._occlusionMap)&&d._state.texture&&this._uOcclusionMap&&(r.bindTexture(this._uOcclusionMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uOcclusionMapMatrix&&a.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,d._state.matrix)),(f=i._alphaMap)&&f._state.texture&&this._uAlphaMap&&(r.bindTexture(this._uAlphaMap,f._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uAlphaMapMatrix&&a.uniformMatrix4fv(this._uAlphaMapMatrix,!1,f._state.matrix)),(I=i._normalMap)&&I._state.texture&&this._uNormalMap&&(r.bindTexture(this._uNormalMap,I._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uNormalMapMatrix&&a.uniformMatrix4fv(this._uNormalMapMatrix,!1,I._state.matrix))}this._lastMaterialId=o.id}if(a.uniformMatrix4fv(this._uModelMatrix,a.FALSE,t.worldMatrix),this._uModelNormalMatrix&&a.uniformMatrix4fv(this._uModelNormalMatrix,a.FALSE,t.worldNormalMatrix),this._uClippable&&a.uniform1i(this._uClippable,l.clippable),this._uColorize){const e=l.colorize,t=this._lastColorize;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(a.uniform4fv(this._uColorize,e),t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3])}a.uniform3fv(this._uOffset,l.offset),c.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,c.positionsDecodeMatrix),this._uUVDecodeMatrix&&a.uniformMatrix3fv(this._uUVDecodeMatrix,!1,c.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(c.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(c.normalsBuf),e.bindArray++),this._aUV&&(this._aUV.bindArrayBuffer(c.uvBuf),e.bindArray++),this._aColor&&(this._aColor.bindArrayBuffer(c.colorsBuf),e.bindArray++),this._aFlags&&(this._aFlags.bindArrayBuffer(c.flagsBuf),e.bindArray++),c.indicesBuf&&(c.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=c.id),c.indicesBuf?(a.drawElements(c.primitive,c.indicesBuf.numItems,c.indicesBuf.itemType,0),e.drawElements++):c.positions&&(a.drawArrays(a.TRIANGLES,0,c.positions.numItems),e.drawArrays++),p&&a.depthFunc(a.LESS)},Is.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl,n=e._material,i=t._lightsState,a=t._sectionPlanesState,r=e._material._state;if(this._program=new we(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const l=this._program;this._uPositionsDecodeMatrix=l.getLocation("positionsDecodeMatrix"),this._uUVDecodeMatrix=l.getLocation("uvDecodeMatrix"),this._uModelMatrix=l.getLocation("modelMatrix"),this._uModelNormalMatrix=l.getLocation("modelNormalMatrix"),this._uViewMatrix=l.getLocation("viewMatrix"),this._uViewNormalMatrix=l.getLocation("viewNormalMatrix"),this._uProjMatrix=l.getLocation("projMatrix"),this._uGammaFactor=l.getLocation("gammaFactor"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[],this._uShadowViewMatrix=[],this._uShadowProjMatrix=[],t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=l.getLocation("logDepthBufFC"));const o=i.lights;let c;for(var u=0,h=o.length;u<h;u++){switch(c=o[u],c.type){case"ambient":this._uLightAmbient[u]=l.getLocation("lightAmbient");break;case"dir":this._uLightColor[u]=l.getLocation("lightColor"+u),this._uLightPos[u]=null,this._uLightDir[u]=l.getLocation("lightDir"+u);break;case"point":this._uLightColor[u]=l.getLocation("lightColor"+u),this._uLightPos[u]=l.getLocation("lightPos"+u),this._uLightDir[u]=null,this._uLightAttenuation[u]=l.getLocation("lightAttenuation"+u);break;case"spot":this._uLightColor[u]=l.getLocation("lightColor"+u),this._uLightPos[u]=l.getLocation("lightPos"+u),this._uLightDir[u]=l.getLocation("lightDir"+u),this._uLightAttenuation[u]=l.getLocation("lightAttenuation"+u)}c.castsShadow&&(this._uShadowViewMatrix[u]=l.getLocation("shadowViewMatrix"+u),this._uShadowProjMatrix[u]=l.getLocation("shadowProjMatrix"+u))}i.lightMaps.length>0&&(this._uLightMap="lightMap"),i.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(u=0,h=a.sectionPlanes.length;u<h;u++)this._uSectionPlanes.push({active:l.getLocation("sectionPlaneActive"+u),pos:l.getLocation("sectionPlanePos"+u),dir:l.getLocation("sectionPlaneDir"+u)});switch(this._uPointSize=l.getLocation("pointSize"),r.type){case"LambertMaterial":this._uMaterialColor=l.getLocation("materialColor"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff");break;case"PhongMaterial":this._uMaterialAmbient=l.getLocation("materialAmbient"),this._uMaterialDiffuse=l.getLocation("materialDiffuse"),this._uMaterialSpecular=l.getLocation("materialSpecular"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff"),this._uMaterialShininess=l.getLocation("materialShininess"),n._ambientMap&&(this._uMaterialAmbientMap="ambientMap",this._uMaterialAmbientMapMatrix=l.getLocation("ambientMapMatrix")),n._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=l.getLocation("diffuseMapMatrix")),n._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=l.getLocation("specularMapMatrix")),n._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=l.getLocation("emissiveMapMatrix")),n._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=l.getLocation("alphaMapMatrix")),n._reflectivityMap&&(this._uReflectivityMap="reflectivityMap",this._uReflectivityMapMatrix=l.getLocation("reflectivityMapMatrix")),n._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=l.getLocation("normalMapMatrix")),n._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=l.getLocation("occlusionMapMatrix")),n._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias=l.getLocation("diffuseFresnelEdgeBias"),this._uDiffuseFresnelCenterBias=l.getLocation("diffuseFresnelCenterBias"),this._uDiffuseFresnelEdgeColor=l.getLocation("diffuseFresnelEdgeColor"),this._uDiffuseFresnelCenterColor=l.getLocation("diffuseFresnelCenterColor"),this._uDiffuseFresnelPower=l.getLocation("diffuseFresnelPower")),n._specularFresnel&&(this._uSpecularFresnelEdgeBias=l.getLocation("specularFresnelEdgeBias"),this._uSpecularFresnelCenterBias=l.getLocation("specularFresnelCenterBias"),this._uSpecularFresnelEdgeColor=l.getLocation("specularFresnelEdgeColor"),this._uSpecularFresnelCenterColor=l.getLocation("specularFresnelCenterColor"),this._uSpecularFresnelPower=l.getLocation("specularFresnelPower")),n._alphaFresnel&&(this._uAlphaFresnelEdgeBias=l.getLocation("alphaFresnelEdgeBias"),this._uAlphaFresnelCenterBias=l.getLocation("alphaFresnelCenterBias"),this._uAlphaFresnelEdgeColor=l.getLocation("alphaFresnelEdgeColor"),this._uAlphaFresnelCenterColor=l.getLocation("alphaFresnelCenterColor"),this._uAlphaFresnelPower=l.getLocation("alphaFresnelPower")),n._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias=l.getLocation("reflectivityFresnelEdgeBias"),this._uReflectivityFresnelCenterBias=l.getLocation("reflectivityFresnelCenterBias"),this._uReflectivityFresnelEdgeColor=l.getLocation("reflectivityFresnelEdgeColor"),this._uReflectivityFresnelCenterColor=l.getLocation("reflectivityFresnelCenterColor"),this._uReflectivityFresnelPower=l.getLocation("reflectivityFresnelPower")),n._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias=l.getLocation("emissiveFresnelEdgeBias"),this._uEmissiveFresnelCenterBias=l.getLocation("emissiveFresnelCenterBias"),this._uEmissiveFresnelEdgeColor=l.getLocation("emissiveFresnelEdgeColor"),this._uEmissiveFresnelCenterColor=l.getLocation("emissiveFresnelCenterColor"),this._uEmissiveFresnelPower=l.getLocation("emissiveFresnelPower"));break;case"MetallicMaterial":this._uBaseColor=l.getLocation("materialBaseColor"),this._uMaterialMetallic=l.getLocation("materialMetallic"),this._uMaterialRoughness=l.getLocation("materialRoughness"),this._uMaterialSpecularF0=l.getLocation("materialSpecularF0"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff"),n._baseColorMap&&(this._uBaseColorMap="baseColorMap",this._uBaseColorMapMatrix=l.getLocation("baseColorMapMatrix")),n._metallicMap&&(this._uMetallicMap="metallicMap",this._uMetallicMapMatrix=l.getLocation("metallicMapMatrix")),n._roughnessMap&&(this._uRoughnessMap="roughnessMap",this._uRoughnessMapMatrix=l.getLocation("roughnessMapMatrix")),n._metallicRoughnessMap&&(this._uMetallicRoughnessMap="metallicRoughnessMap",this._uMetallicRoughnessMapMatrix=l.getLocation("metallicRoughnessMapMatrix")),n._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=l.getLocation("emissiveMapMatrix")),n._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=l.getLocation("occlusionMapMatrix")),n._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=l.getLocation("alphaMapMatrix")),n._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=l.getLocation("normalMapMatrix"));break;case"SpecularMaterial":this._uMaterialDiffuse=l.getLocation("materialDiffuse"),this._uMaterialSpecular=l.getLocation("materialSpecular"),this._uMaterialGlossiness=l.getLocation("materialGlossiness"),this._uMaterialReflectivity=l.getLocation("reflectivityFresnel"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff"),n._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=l.getLocation("diffuseMapMatrix")),n._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=l.getLocation("specularMapMatrix")),n._glossinessMap&&(this._uGlossinessMap="glossinessMap",this._uGlossinessMapMatrix=l.getLocation("glossinessMapMatrix")),n._specularGlossinessMap&&(this._uSpecularGlossinessMap="materialSpecularGlossinessMap",this._uSpecularGlossinessMapMatrix=l.getLocation("materialSpecularGlossinessMapMatrix")),n._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=l.getLocation("emissiveMapMatrix")),n._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=l.getLocation("occlusionMapMatrix")),n._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=l.getLocation("alphaMapMatrix")),n._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=l.getLocation("normalMapMatrix"))}this._aPosition=l.getAttribute("position"),this._aNormal=l.getAttribute("normal"),this._aUV=l.getAttribute("uv"),this._aColor=l.getAttribute("color"),this._aFlags=l.getAttribute("flags"),this._uClippable=l.getLocation("clippable"),this._uColorize=l.getLocation("colorize"),this._uOffset=l.getLocation("offset"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize=new Float32Array(4),this._baseTextureUnit=0},Is.prototype._bindProgram=function(e){const t=oe.MAX_TEXTURE_UNITS,s=this._scene,n=s.canvas.gl,i=s._lightsState,a=s.camera.project;let r;const l=this._program;if(l.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize[0]=-1,this._lastColorize[1]=-1,this._lastColorize[2]=-1,this._lastColorize[3]=-1,n.uniformMatrix4fv(this._uProjMatrix,!1,a.matrix),s.logarithmicDepthBufferEnabled){const e=2/(Math.log(a.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}for(var o=0,c=i.lights.length;o<c;o++)if(r=i.lights[o],this._uLightAmbient[o])n.uniform4f(this._uLightAmbient[o],r.color[0],r.color[1],r.color[2],r.intensity);else if(this._uLightColor[o]&&n.uniform4f(this._uLightColor[o],r.color[0],r.color[1],r.color[2],r.intensity),this._uLightPos[o]&&(n.uniform3fv(this._uLightPos[o],r.pos),this._uLightAttenuation[o]&&n.uniform1f(this._uLightAttenuation[o],r.attenuation)),this._uLightDir[o]&&n.uniform3fv(this._uLightDir[o],r.dir),r.castsShadow){this._uShadowViewMatrix[o]&&n.uniformMatrix4fv(this._uShadowViewMatrix[o],!1,r.getShadowViewMatrix()),this._uShadowProjMatrix[o]&&n.uniformMatrix4fv(this._uShadowProjMatrix[o],!1,r.getShadowProjMatrix());const s=r.getShadowRenderBuf();s&&(l.bindTexture("shadowMap"+o,s.getTexture(),e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++)}i.lightMaps.length>0&&i.lightMaps[0].texture&&this._uLightMap&&(l.bindTexture(this._uLightMap,i.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),i.reflectionMaps.length>0&&i.reflectionMaps[0].texture&&this._uReflectionMap&&(l.bindTexture(this._uReflectionMap,i.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&n.uniform1f(this._uGammaFactor,s.gammaFactor),this._baseTextureUnit=e.textureUnit};class ms{constructor(e){this.vertex=function(e){const t=e.scene,s=t._lightsState,n=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),i=t._sectionPlanesState.sectionPlanes.length>0,a=!!e._geometry._state.compressGeometry,r=e._state.billboard,l=e._state.stationary,o=[];o.push("#version 300 es"),o.push("// EmphasisFillShaderSource vertex shader"),o.push("in vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform vec4 colorize;"),o.push("uniform vec3 offset;"),a&&o.push("uniform mat4 positionsDecodeMatrix;");t.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;"));i&&o.push("out vec4 vWorldPosition;");if(o.push("uniform vec4 lightAmbient;"),o.push("uniform vec4 fillColor;"),n){o.push("in vec3 normal;"),o.push("uniform mat4 modelNormalMatrix;"),o.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(o.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&o.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&o.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&o.push("uniform vec3 lightPos"+e+";"))}a&&(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 vColor;"),("spherical"===r||"cylindrical"===r)&&(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = 1.0;"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===r&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}"));o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),o.push("vec4 worldPosition;"),a&&o.push("localPosition = positionsDecodeMatrix * localPosition;");n&&(a?o.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):o.push("vec4 localNormal = vec4(normal, 0.0); "),o.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),o.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),l&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"),o.push("billboard(modelViewMatrix);"),n&&(o.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),o.push("billboard(modelNormalMatrix2);"),o.push("billboard(viewNormalMatrix2);"),o.push("billboard(modelViewNormalMatrix);")),o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n&&o.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(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;"),n)for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);");else{if("point"!==t.type)continue;"view"===t.space?o.push("viewLightDir = normalize(lightPos"+e+" - viewPosition.xyz);"):o.push("viewLightDir = normalize((viewMatrix2 * vec4(lightPos"+e+", 0.0)).xyz);")}o.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),o.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}o.push("vColor = vec4(reflectedColor * fillColor.rgb, fillColor.a);"),i&&o.push("vWorldPosition = worldPosition;");"points"===e._geometry._state.primitiveName&&o.push("gl_PointSize = pointSize;");o.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return o.push("gl_Position = clipPos;"),o.push("}"),o}(e),this.fragment=function(e){const t=e.scene,s=e.scene._sectionPlanesState,n=e.scene.gammaOutput,i=s.sectionPlanes.length>0,a=[];a.push("#version 300 es"),a.push("// Lambertian drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),t.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;"));n&&(a.push("uniform float gammaFactor;"),a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}"));if(i){a.push("in vec4 vWorldPosition;"),a.push("uniform bool clippable;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){a.push("if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}"points"===e._geometry._state.primitiveName&&(a.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push("float r = dot(cxy, cxy);"),a.push("if (r > 1.0) {"),a.push(" discard;"),a.push("}"));t.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");n?a.push("outColor = linearToGamma(vColor, gammaFactor);"):a.push("outColor = vColor;");return a.push("}"),a}(e)}}const vs=new e({}),ws=h.vec3(),gs=function(e,t){this.id=vs.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new ms(t),this._allocate(t)},Ts={};gs.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=Ts[t];return s||(s=new gs(t,e),Ts[t]=s,A.memory.programs++),s._useCount++,s},gs.prototype.put=function(){0==--this._useCount&&(vs.removeItem(this.id),this._program&&this._program.destroy(),delete Ts[this._hash],A.memory.programs--)},gs.prototype.webglContextRestored=function(){this._program=null},gs.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const n=this._scene,i=n.camera,a=n.canvas.gl,r=0===s?t._xrayMaterial._state:1===s?t._highlightMaterial._state:t._selectedMaterial._state,l=t._state,o=t._geometry._state,c=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,c?e.getRTCViewMatrix(l.originHash,c):i.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,i.viewNormalMatrix),l.clippable){const e=n._sectionPlanesState.sectionPlanes.length;if(e>0){const s=n._sectionPlanesState.sectionPlanes,i=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const n=i.sectionPlanesActivePerLayer[t];if(a.uniform1i(e.active,n?1:0),n){const n=s[t];a.uniform3fv(e.pos,c?N(n.dist,n.dir,c,ws):n.pos),a.uniform3fv(e.dir,n.dir)}}}}}if(r.id!==this._lastMaterialId){const t=r.fillColor,s=r.backfaces;e.backfaces!==s&&(s?a.disable(a.CULL_FACE):a.enable(a.CULL_FACE),e.backfaces=s),a.uniform4f(this._uFillColor,t[0],t[1],t[2],r.fillAlpha),this._lastMaterialId=r.id}a.uniformMatrix4fv(this._uModelMatrix,a.FALSE,t.worldMatrix),this._uModelNormalMatrix&&a.uniformMatrix4fv(this._uModelNormalMatrix,a.FALSE,t.worldNormalMatrix),this._uClippable&&a.uniform1i(this._uClippable,l.clippable),a.uniform3fv(this._uOffset,l.offset),o.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,o.positionsDecodeMatrix),this._uUVDecodeMatrix&&a.uniformMatrix3fv(this._uUVDecodeMatrix,!1,o.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(o.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(o.normalsBuf),e.bindArray++),o.indicesBuf?(o.indicesBuf.bind(),e.bindArray++):o.positionsBuf,this._lastGeometryId=o.id),o.indicesBuf?(a.drawElements(o.primitive,o.indicesBuf.numItems,o.indicesBuf.itemType,0),e.drawElements++):o.positionsBuf&&(a.drawArrays(a.TRIANGLES,0,o.positionsBuf.numItems),e.drawArrays++)},gs.prototype._allocate=function(e){const t=e.scene,s=t._lightsState,n=t._sectionPlanesState,i=t.canvas.gl;if(this._program=new we(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const a=this._program;this._uPositionsDecodeMatrix=a.getLocation("positionsDecodeMatrix"),this._uModelMatrix=a.getLocation("modelMatrix"),this._uModelNormalMatrix=a.getLocation("modelNormalMatrix"),this._uViewMatrix=a.getLocation("viewMatrix"),this._uViewNormalMatrix=a.getLocation("viewNormalMatrix"),this._uProjMatrix=a.getLocation("projMatrix"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(let e=0,t=s.lights.length;e<t;e++){switch(s.lights[e].type){case"ambient":this._uLightAmbient[e]=a.getLocation("lightAmbient");break;case"dir":this._uLightColor[e]=a.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=a.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=a.getLocation("lightColor"+e),this._uLightPos[e]=a.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=a.getLocation("lightAttenuation"+e)}}this._uSectionPlanes=[];for(let e=0,t=n.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:a.getLocation("sectionPlaneActive"+e),pos:a.getLocation("sectionPlanePos"+e),dir:a.getLocation("sectionPlaneDir"+e)});this._uFillColor=a.getLocation("fillColor"),this._aPosition=a.getAttribute("position"),this._aNormal=a.getAttribute("normal"),this._uClippable=a.getLocation("clippable"),this._uGammaFactor=a.getLocation("gammaFactor"),this._uOffset=a.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=a.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},gs.prototype._bindProgram=function(e){const t=this._scene,s=t.canvas.gl,n=t._lightsState,i=t.camera,a=i.project;if(this._program.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastIndicesBufId=null,s.uniformMatrix4fv(this._uViewNormalMatrix,!1,i.normalMatrix),s.uniformMatrix4fv(this._uProjMatrix,!1,a.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(a.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];this._uLightAmbient[e]?s.uniform4f(this._uLightAmbient[e],t.color[0],t.color[1],t.color[2],t.intensity):(this._uLightColor[e]&&s.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(s.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&s.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&s.uniform3fv(this._uLightDir[e],t.dir))}this._uGammaFactor&&s.uniform1f(this._uGammaFactor,t.gammaFactor)};class Es{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry,i=e._state.billboard,a=e._state.stationary,r=[];r.push("#version 300 es"),r.push("// Edges drawing vertex shader"),r.push("in vec3 position;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec4 edgeColor;"),r.push("uniform vec3 offset;"),n&&r.push("uniform mat4 positionsDecodeMatrix;");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;"));s&&r.push("out vec4 vWorldPosition;");r.push("out vec4 vColor;"),("spherical"===i||"cylindrical"===i)&&(r.push("void billboard(inout mat4 mat) {"),r.push(" mat[0][0] = 1.0;"),r.push(" mat[0][1] = 0.0;"),r.push(" mat[0][2] = 0.0;"),"spherical"===i&&(r.push(" mat[1][0] = 0.0;"),r.push(" mat[1][1] = 1.0;"),r.push(" mat[1][2] = 0.0;")),r.push(" mat[2][0] = 0.0;"),r.push(" mat[2][1] = 0.0;"),r.push(" mat[2][2] =1.0;"),r.push("}"));r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),r.push("vec4 worldPosition;"),n&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push("mat4 viewMatrix2 = viewMatrix;"),r.push("mat4 modelMatrix2 = modelMatrix;"),a&&r.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===i||"cylindrical"===i?(r.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),r.push("billboard(modelMatrix2);"),r.push("billboard(viewMatrix2);"),r.push("billboard(modelViewMatrix);"),r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.push("vColor = edgeColor;"),s&&r.push("vWorldPosition = worldPosition;");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 = clipPos;"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,s=e.scene._sectionPlanesState,n=e.scene.gammaOutput,i=s.sectionPlanes.length>0,a=[];a.push("#version 300 es"),a.push("// Edges drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),t.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;"));n&&(a.push("uniform float gammaFactor;"),a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}"));if(i){a.push("in vec4 vWorldPosition;"),a.push("uniform bool clippable;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){a.push("if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}t.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");n?a.push("outColor = linearToGamma(vColor, gammaFactor);"):a.push("outColor = vColor;");return a.push("}"),a}(e)}}const bs=new e({}),Ds=h.vec3(),Ps=function(e,t){this.id=bs.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Es(t),this._allocate(t)},Rs={};Ps.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=Rs[t];return s||(s=new Ps(t,e),Rs[t]=s,A.memory.programs++),s._useCount++,s},Ps.prototype.put=function(){0==--this._useCount&&(bs.removeItem(this.id),this._program&&this._program.destroy(),delete Rs[this._hash],A.memory.programs--)},Ps.prototype.webglContextRestored=function(){this._program=null},Ps.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const n=this._scene,i=n.camera,a=n.canvas.gl;let r;const l=t._state,o=t._geometry,c=o._state,u=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,u?e.getRTCViewMatrix(l.originHash,u):i.viewMatrix),l.clippable){const e=n._sectionPlanesState.sectionPlanes.length;if(e>0){const s=n._sectionPlanesState.sectionPlanes,i=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const n=i.sectionPlanesActivePerLayer[t];if(a.uniform1i(e.active,n?1:0),n){const n=s[t];a.uniform3fv(e.pos,u?N(n.dist,n.dir,u,Ds):n.pos),a.uniform3fv(e.dir,n.dir)}}}}}switch(s){case 0:r=t._xrayMaterial._state;break;case 1:r=t._highlightMaterial._state;break;case 2:r=t._selectedMaterial._state;break;default:r=t._edgeMaterial._state}if(r.id!==this._lastMaterialId){const t=r.backfaces;if(e.backfaces!==t&&(t?a.disable(a.CULL_FACE):a.enable(a.CULL_FACE),e.backfaces=t),e.lineWidth!==r.edgeWidth&&(a.lineWidth(r.edgeWidth),e.lineWidth=r.edgeWidth),this._uEdgeColor){const e=r.edgeColor,t=r.edgeAlpha;a.uniform4f(this._uEdgeColor,e[0],e[1],e[2],t)}this._lastMaterialId=r.id}let h;a.uniformMatrix4fv(this._uModelMatrix,a.FALSE,t.worldMatrix),this._uClippable&&a.uniform1i(this._uClippable,l.clippable),a.uniform3fv(this._uOffset,l.offset),c.primitive===a.TRIANGLES?h=o._getEdgeIndices():c.primitive===a.LINES&&(h=c.indicesBuf),h&&(c.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,c.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(c.positionsBuf,c.compressGeometry?a.UNSIGNED_SHORT:a.FLOAT),e.bindArray++),h.bind(),e.bindArray++,this._lastGeometryId=c.id),a.drawElements(a.LINES,h.numItems,h.itemType,0),e.drawElements++)},Ps.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl,n=t._sectionPlanesState;if(this._program=new we(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=n.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+e),pos:i.getLocation("sectionPlanePos"+e),dir:i.getLocation("sectionPlaneDir"+e)});this._uEdgeColor=i.getLocation("edgeColor"),this._aPosition=i.getAttribute("position"),this._uClippable=i.getLocation("clippable"),this._uGammaFactor=i.getLocation("gammaFactor"),this._uOffset=i.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Ps.prototype._bindProgram=function(e){const t=this._program,s=this._scene,n=s.canvas.gl,i=s.camera.project;if(t.bind(),e.useProgram++,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,n.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),s.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}this._uGammaFactor&&n.uniform1f(this._uGammaFactor,s.gammaFactor)};class Cs{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry,i=e._state.billboard,a=e._state.stationary,r=[];r.push("#version 300 es"),r.push("// Mesh picking vertex shader"),r.push("in vec3 position;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("out vec4 vViewPosition;"),r.push("uniform vec3 offset;"),n&&r.push("uniform mat4 positionsDecodeMatrix;");s&&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;"));"spherical"!==i&&"cylindrical"!==i||(r.push("void billboard(inout mat4 mat) {"),r.push(" mat[0][0] = 1.0;"),r.push(" mat[0][1] = 0.0;"),r.push(" mat[0][2] = 0.0;"),"spherical"===i&&(r.push(" mat[1][0] = 0.0;"),r.push(" mat[1][1] = 1.0;"),r.push(" mat[1][2] = 0.0;")),r.push(" mat[2][0] = 0.0;"),r.push(" mat[2][1] = 0.0;"),r.push(" mat[2][2] =1.0;"),r.push("}"));r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),n&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push("mat4 viewMatrix2 = viewMatrix;"),r.push("mat4 modelMatrix2 = modelMatrix;"),a&&r.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==i&&"cylindrical"!==i||(r.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),r.push("billboard(modelMatrix2);"),r.push("billboard(viewMatrix2);"));r.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),s&&r.push(" vWorldPosition = worldPosition;");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 = clipPos;"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];i.push("#version 300 es"),i.push("// Mesh 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"),t.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"));if(i.push("uniform vec4 pickColor;"),n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(var a=0;a<s.sectionPlanes.length;a++)i.push("uniform bool sectionPlaneActive"+a+";"),i.push("uniform vec3 sectionPlanePos"+a+";"),i.push("uniform vec3 sectionPlaneDir"+a+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(a=0;a<s.sectionPlanes.length;a++)i.push("if (sectionPlaneActive"+a+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}t.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return i.push(" outColor = pickColor; "),i.push("}"),i}(e)}}const _s=h.vec3(),Bs=function(e,t){this._hash=e,this._shaderSource=new Cs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Os={};Bs.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=Os[t];if(!s){if(s=new Bs(t,e),s.errors)return console.log(s.errors.join("\n")),null;Os[t]=s,A.memory.programs++}return s._useCount++,s},Bs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Os[this._hash],A.memory.programs--)},Bs.prototype.webglContextRestored=function(){this._program=null},Bs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,n=s.canvas.gl,i=t._state,a=t._material._state,r=t._geometry._state,l=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),n.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(i.originHash,l):e.pickViewMatrix),i.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,a=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const s=a.sectionPlanesActivePerLayer[t];if(n.uniform1i(e.active,s?1:0),s){const s=i[t];n.uniform3fv(e.pos,l?N(s.dist,s.dir,l,_s):s.pos),n.uniform3fv(e.dir,s.dir)}}}}}if(a.id!==this._lastMaterialId){const t=a.backfaces;e.backfaces!==t&&(t?n.disable(n.CULL_FACE):n.enable(n.CULL_FACE),e.backfaces=t);const s=a.frontface;e.frontface!==s&&(s?n.frontFace(n.CCW):n.frontFace(n.CW),e.frontface=s),this._lastMaterialId=a.id}n.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),n.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&n.uniform1i(this._uClippable,t._state.clippable),n.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&n.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?n.UNSIGNED_SHORT:n.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=r.id);var o=t._state.pickID;const c=o>>24&255,u=o>>16&255,h=o>>8&255,p=255&o;n.uniform4f(this._uPickColor,p/255,h/255,u/255,c/255),r.indicesBuf?(n.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&n.drawArrays(n.TRIANGLES,0,r.positions.numItems)},Bs.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new we(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._uClippable=n.getLocation("clippable"),this._uPickColor=n.getLocation("pickColor"),this._uOffset=n.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastGeometryId=null},Bs.prototype._bindProgram=function(e){const t=this._scene,s=t.canvas.gl,n=t.camera.project;if(this._program.bind(),e.useProgram++,t.logarithmicDepthBufferEnabled){const e=2/(Math.log(n.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}this._lastMaterialId=null,this._lastGeometryId=null};class Ss{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry;e._state.billboard,e._state.stationary;const i=[];i.push("#version 300 es"),i.push("// Surface picking vertex shader"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform vec3 offset;"),s&&(i.push("uniform bool clippable;"),i.push("out vec4 vWorldPosition;"));t.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 vColor;"),n&&i.push("uniform mat4 positionsDecodeMatrix;");i.push("void main(void) {"),i.push("vec4 localPosition = vec4(position, 1.0); "),n&&i.push("localPosition = positionsDecodeMatrix * localPosition;");i.push(" vec4 worldPosition = modelMatrix * localPosition; "),i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),s&&i.push(" vWorldPosition = worldPosition;");i.push(" vColor = color;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return i.push("gl_Position = clipPos;"),i.push("}"),i}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];i.push("#version 300 es"),i.push("// Surface 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"),i.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"));if(n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(let e=0;e<s.sectionPlanes.length;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e<s.sectionPlanes.length;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}t.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return i.push(" outColor = vColor;"),i.push("}"),i}(e)}}const Ns=h.vec3(),xs=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Ss(t),this._allocate(t)},Ls={};xs.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=Ls[t];if(!s){if(s=new xs(t,e),s.errors)return console.log(s.errors.join("\n")),null;Ls[t]=s,A.memory.programs++}return s._useCount++,s},xs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ls[this._hash],A.memory.programs--)},xs.prototype.webglContextRestored=function(){this._program=null},xs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,n=s.canvas.gl,i=t._state,a=t._material._state,r=t._geometry,l=t._geometry._state,o=t.origin,c=a.backfaces,u=a.frontface,h=s.camera.project,p=r._getPickTrianglePositions(),A=r._getPickTriangleColors();if(this._program.bind(),e.useProgram++,s.logarithmicDepthBufferEnabled){const e=2/(Math.log(h.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}if(n.uniformMatrix4fv(this._uViewMatrix,!1,o?e.getRTCPickViewMatrix(i.originHash,o):e.pickViewMatrix),i.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,a=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const s=a.sectionPlanesActivePerLayer[t];if(n.uniform1i(e.active,s?1:0),s){const s=i[t];n.uniform3fv(e.pos,o?N(s.dist,s.dir,o,Ns):s.pos),n.uniform3fv(e.dir,s.dir)}}}}}n.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),s.logarithmicDepthBufferEnabled&&n.uniform1f(this._uZFar,s.camera.project.far),e.backfaces!==c&&(c?n.disable(n.CULL_FACE):n.enable(n.CULL_FACE),e.backfaces=c),e.frontface!==u&&(u?n.frontFace(n.CCW):n.frontFace(n.CW),e.frontface=u),n.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&n.uniform1i(this._uClippable,t._state.clippable),n.uniform3fv(this._uOffset,t._state.offset),this._uPositionsDecodeMatrix?(n.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,l.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(p,l.compressGeometry?n.UNSIGNED_SHORT:n.FLOAT)):this._aPosition.bindArrayBuffer(p),A.bind(),n.enableVertexAttribArray(this._aColor.location),n.vertexAttribPointer(this._aColor.location,A.itemSize,A.itemType,!0,0,0),n.drawArrays(l.primitive,0,p.numItems/3)},xs.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new we(s,this._shaderSource),this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._aColor=n.getAttribute("color"),this._uClippable=n.getLocation("clippable"),this._uOffset=n.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC"))};class Ms{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry,i=e._state.billboard,a=e._state.stationary,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion vertex shader"),r.push("in vec3 position;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),n&&r.push("uniform mat4 positionsDecodeMatrix;");s&&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;"));"spherical"!==i&&"cylindrical"!==i||(r.push("void billboard(inout mat4 mat) {"),r.push(" mat[0][0] = 1.0;"),r.push(" mat[0][1] = 0.0;"),r.push(" mat[0][2] = 0.0;"),"spherical"===i&&(r.push(" mat[1][0] = 0.0;"),r.push(" mat[1][1] = 1.0;"),r.push(" mat[1][2] = 0.0;")),r.push(" mat[2][0] = 0.0;"),r.push(" mat[2][1] = 0.0;"),r.push(" mat[2][2] =1.0;"),r.push("}"));r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),r.push("vec4 worldPosition;"),n&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push("mat4 viewMatrix2 = viewMatrix;"),r.push("mat4 modelMatrix2 = modelMatrix;"),a&&r.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===i||"cylindrical"===i?(r.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),r.push("billboard(modelMatrix2);"),r.push("billboard(viewMatrix2);"),r.push("billboard(modelViewMatrix);"),r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&r.push(" vWorldPosition = worldPosition;");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 = clipPos;"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];i.push("#version 300 es"),i.push("// Mesh 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.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"));if(n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(var a=0;a<s.sectionPlanes.length;a++)i.push("uniform bool sectionPlaneActive"+a+";"),i.push("uniform vec3 sectionPlanePos"+a+";"),i.push("uniform vec3 sectionPlaneDir"+a+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(a=0;a<s.sectionPlanes.length;a++)i.push("if (sectionPlaneActive"+a+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return i.push("}"),i}(e)}}const Fs=h.vec3(),Hs=function(e,t){this._hash=e,this._shaderSource=new Ms(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Us={};Hs.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let s=Us[t];if(!s){if(s=new Hs(t,e),s.errors)return console.log(s.errors.join("\n")),null;Us[t]=s,A.memory.programs++}return s._useCount++,s},Hs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Us[this._hash],A.memory.programs--)},Hs.prototype.webglContextRestored=function(){this._program=null},Hs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,n=s.canvas.gl,i=t._material._state,a=t._state,r=t._geometry._state,l=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),i.id!==this._lastMaterialId){const t=i.backfaces;e.backfaces!==t&&(t?n.disable(n.CULL_FACE):n.enable(n.CULL_FACE),e.backfaces=t);const s=i.frontface;e.frontface!==s&&(s?n.frontFace(n.CCW):n.frontFace(n.CW),e.frontface=s),this._lastMaterialId=i.id}const o=s.camera;if(n.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCViewMatrix(a.originHash,l):o.viewMatrix),a.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,a=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const s=a.sectionPlanesActivePerLayer[t];if(n.uniform1i(e.active,s?1:0),s){const s=i[t];n.uniform3fv(e.pos,l?N(s.dist,s.dir,l,Fs):s.pos),n.uniform3fv(e.dir,s.dir)}}}}}n.uniformMatrix4fv(this._uProjMatrix,!1,o._project._state.matrix),n.uniformMatrix4fv(this._uModelMatrix,n.FALSE,t.worldMatrix),this._uClippable&&n.uniform1i(this._uClippable,t._state.clippable),n.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&n.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?n.UNSIGNED_SHORT:n.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=r.id),r.indicesBuf?(n.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&n.drawArrays(n.TRIANGLES,0,r.positions.numItems)},Hs.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new we(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._uClippable=n.getLocation("clippable"),this._uOffset=n.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Hs.prototype._bindProgram=function(e){const t=this._scene,s=t.camera.project,n=t.canvas.gl;if(this._program.bind(),e.useProgram++,n.uniformMatrix4fv(this._uProjMatrix,!1,s.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null};class Gs{constructor(e){this.vertex=function(e){const t=e.scene._sectionPlanesState.sectionPlanes.length>0,s=!!e._geometry._state.compressGeometry,n=[];n.push("// Mesh shadow vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 shadowViewMatrix;"),n.push("uniform mat4 shadowProjMatrix;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");t&&n.push("out vec4 vWorldPosition;");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("worldPosition = modelMatrix * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&n.push("vWorldPosition = worldPosition;");return n.push(" gl_Position = shadowProjMatrix * viewPosition;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];if(i.push("// Mesh 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"),n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(var a=0;a<s.sectionPlanes.length;a++)i.push("uniform bool sectionPlaneActive"+a+";"),i.push("uniform vec3 sectionPlanePos"+a+";"),i.push("uniform vec3 sectionPlaneDir"+a+";")}if(i.push("vec4 encodeFloat( const in float depth ) {"),i.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),i.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),i.push(" vec4 comp = fract(depth * bitShift);"),i.push(" comp -= comp.xxyz * bitMask;"),i.push(" return comp;"),i.push("}"),i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(a=0;a<s.sectionPlanes.length;a++)i.push("if (sectionPlaneActive"+a+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}return i.push("outColor = encodeFloat(gl_FragCoord.z);"),i.push("}"),i}(e)}}const Vs=function(e,t){this._hash=e,this._shaderSource=new Gs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},js={};Vs.get=function(e){const t=e.scene,s=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let n=js[s];if(!n){if(n=new Vs(s,e),n.errors)return console.log(n.errors.join("\n")),null;js[s]=n,A.memory.programs++}return n._useCount++,n},Vs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete js[this._hash],A.memory.programs--)},Vs.prototype.webglContextRestored=function(){this._program=null},Vs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene.canvas.gl,n=t._material._state,i=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),n.id!==this._lastMaterialId){const t=n.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=n.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),e.lineWidth!==n.lineWidth&&(s.lineWidth(n.lineWidth),e.lineWidth=n.lineWidth),this._uPointSize&&s.uniform1i(this._uPointSize,n.pointSize),this._lastMaterialId=n.id}if(s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),i.combineGeometry){const n=t.vertexBufs;n.id!==this._lastVertexBufsId&&(n.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(n.positionsBuf,n.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),this._lastVertexBufsId=n.id)}this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),i.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,i.positionsDecodeMatrix),i.combineGeometry?i.indicesBufCombined&&(i.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(i.positionsBuf,i.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),i.indicesBuf&&(i.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=i.id),i.combineGeometry?i.indicesBufCombined&&(s.drawElements(i.primitive,i.indicesBufCombined.numItems,i.indicesBufCombined.itemType,0),e.drawElements++):i.indicesBuf?(s.drawElements(i.primitive,i.indicesBuf.numItems,i.indicesBuf.itemType,0),e.drawElements++):i.positions&&(s.drawArrays(s.TRIANGLES,0,i.positions.numItems),e.drawArrays++)},Vs.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new we(s,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uShadowViewMatrix=n.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=n.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._uClippable=n.getLocation("clippable"),this._uOffset=n.getLocation("offset"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Vs.prototype._bindProgram=function(e){this._program||this._allocate(mesh);const t=this._scene,s=t.canvas.gl,n=t._sectionPlanesState;if(this._program.bind(),e.useProgram++,s.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),s.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,n.sectionPlanes.length>0){let e,t,i,a,r;for(let l=0,o=this._uSectionPlanes.length;l<o;l++)e=this._uSectionPlanes[l],t=e.active,i=n.sectionPlanes[l],t&&s.uniform1i(t,i.active),a=e.pos,a&&s.uniform3fv(e.pos,i.pos),r=e.dir,r&&s.uniform3fv(e.dir,i.dir)}};class ks{constructor(){this.visibleLayers=[],this.sectionPlanesActivePerLayer=[],this.reset()}reset(){this.culled=!1,this.sectioned=!1,this.numLayers=0,this.numVisibleLayers=0,this.colorOpaque=!1,this.colorTransparent=!1,this.edgesOpaque=!1,this.edgesTransparent=!1,this.xrayedSilhouetteOpaque=!1,this.xrayedEdgesOpaque=!1,this.xrayedSilhouetteTransparent=!1,this.xrayedEdgesTransparent=!1,this.highlightedSilhouetteOpaque=!1,this.highlightedEdgesOpaque=!1,this.highlightedSilhouetteTransparent=!1,this.highlightedEdgesTransparent=!1,this.selectedSilhouetteOpaque=!1,this.selectedEdgesOpaque=!1,this.selectedSilhouetteTransparent=!1,this.selectedEdgesTransparent=!1}}const Qs=h.OBB3(),Ws=h.vec4(),zs=h.vec4(),Ks=h.vec4(),Ys=h.vec3([1,0,0]),Xs=h.vec3([0,1,0]),qs=h.vec3([0,0,1]),Js=h.vec3(3),Zs=h.vec3(3),$s=h.identityMat4();class en extends C{constructor(e,t={}){super(e,t),this.originalSystemId=t.originalSystemId||this.id,this.renderFlags=new ks,this._state=new Ve({visible:!0,culled:!1,pickable:null,clippable:null,collidable:null,occluder:!1!==t.occluder,castsShadow:null,receivesShadow:null,xrayed:!1,highlighted:!1,selected:!1,edges:!1,stationary:!!t.stationary,background:!!t.background,billboard:this._checkBillboard(t.billboard),layer:null,colorize:null,pickID:this.scene._renderer.getPickID(this),drawHash:"",pickHash:"",offset:h.vec3(),origin:null,originHash:null}),this._drawRenderer=null,this._shadowRenderer=null,this._emphasisFillRenderer=null,this._emphasisEdgesRenderer=null,this._pickMeshRenderer=null,this._pickTriangleRenderer=null,this._occlusionRenderer=null,this._geometry=t.geometry?this._checkComponent2(["ReadableGeometry","VBOGeometry"],t.geometry):this.scene.geometry,this._material=t.material?this._checkComponent2(["PhongMaterial","MetallicMaterial","SpecularMaterial","LambertMaterial"],t.material):this.scene.material,this._xrayMaterial=t.xrayMaterial?this._checkComponent("EmphasisMaterial",t.xrayMaterial):this.scene.xrayMaterial,this._highlightMaterial=t.highlightMaterial?this._checkComponent("EmphasisMaterial",t.highlightMaterial):this.scene.highlightMaterial,this._selectedMaterial=t.selectedMaterial?this._checkComponent("EmphasisMaterial",t.selectedMaterial):this.scene.selectedMaterial,this._edgeMaterial=t.edgeMaterial?this._checkComponent("EdgeMaterial",t.edgeMaterial):this.scene.edgeMaterial,this._parentNode=null,this._aabb=null,this._aabbDirty=!0,this._numTriangles=this._geometry?this._geometry.numTriangles:0,this.scene._aabbDirty=!0,this._scale=h.vec3(),this._quaternion=h.identityQuaternion(),this._rotation=h.vec3(),this._position=h.vec3(),this._worldMatrix=h.identityMat4(),this._worldNormalMatrix=h.identityMat4(),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0;const s=t.origin||t.rtcCenter;if(s&&(this._state.origin=h.vec3(s),this._state.originHash=s.join()),t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),this._isObject=t.isObject,this._isObject&&this.scene._registerObject(this),this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.layer=t.layer,this.colorize=t.colorize,this.opacity=t.opacity,this.offset=t.offset,t.parentId){const e=this.scene.components[t.parentId];e?e.isNode?e.addChild(this):this.error("Parent is not a Node: '"+t.parentId+"'"):this.error("Parent not found: '"+t.parentId+"'"),this._parentNode=e}else t.parent&&(t.parent.isNode||this.error("Parent is not a Node"),t.parent.addChild(this),this._parentNode=t.parent);this.compile()}get type(){return"Mesh"}get isMesh(){return!0}get parent(){return this._parentNode}get geometry(){return this._geometry}get material(){return this._material}get position(){return this._position}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set rotation(e){this._rotation.set(e||[0,0,0]),h.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),h.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get scale(){return this._scale}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get matrix(){return this._localMatrixDirty&&(this.__localMatrix||(this.__localMatrix=h.identityMat4()),h.composeMat4(this._position,this._quaternion,this._scale,this.__localMatrix),this._localMatrixDirty=!1),this.__localMatrix}set matrix(e){this.__localMatrix||(this.__localMatrix=h.identityMat4()),this.__localMatrix.set(e||$s),h.decomposeMat4(this.__localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}get worldNormalMatrix(){return this._worldNormalMatrixDirty&&this._buildWorldNormalMatrix(),this._worldNormalMatrix}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return this._isObject}get aabb(){return this._aabbDirty&&this._updateAABB(),this._aabb}get origin(){return this._state.origin}set origin(e){e?(this._state.origin||(this._state.origin=h.vec3()),this._state.origin.set(e),this._state.originHash=e.join(),this._setAABBDirty(),this.scene._aabbDirty=!0):this._state.origin&&(this._state.origin=null,this._state.originHash=null,this._setAABBDirty(),this.scene._aabbDirty=!0)}get rtcCenter(){return this.origin}set rtcCenter(e){this.origin=e}get numTriangles(){return this._numTriangles}get visible(){return this._state.visible}set visible(e){e=!1!==e,this._state.visible=e,this._isObject&&this.scene._objectVisibilityUpdated(this,e),this.glRedraw()}get xrayed(){return this._state.xrayed}set xrayed(e){e=!!e,this._state.xrayed!==e&&(this._state.xrayed=e,this._isObject&&this.scene._objectXRayedUpdated(this,e),this.glRedraw())}get highlighted(){return this._state.highlighted}set highlighted(e){(e=!!e)!==this._state.highlighted&&(this._state.highlighted=e,this._isObject&&this.scene._objectHighlightedUpdated(this,e),this.glRedraw())}get selected(){return this._state.selected}set selected(e){(e=!!e)!==this._state.selected&&(this._state.selected=e,this._isObject&&this.scene._objectSelectedUpdated(this,e),this.glRedraw())}get edges(){return this._state.edges}set edges(e){(e=!!e)!==this._state.edges&&(this._state.edges=e,this.glRedraw())}get culled(){return this._state.culled}set culled(e){this._state.culled=!!e,this.glRedraw()}get clippable(){return this._state.clippable}set clippable(e){e=!1!==e,this._state.clippable!==e&&(this._state.clippable=e,this.glRedraw())}get collidable(){return this._state.collidable}set collidable(e){(e=!1!==e)!==this._state.collidable&&(this._state.collidable=e,this._setAABBDirty(),this.scene._aabbDirty=!0)}get pickable(){return this._state.pickable}set pickable(e){e=!1!==e,this._state.pickable!==e&&(this._state.pickable=e)}get castsShadow(){return this._state.castsShadow}set castsShadow(e){(e=!1!==e)!==this._state.castsShadow&&(this._state.castsShadow=e,this.glRedraw())}get receivesShadow(){return this._state.receivesShadow}set receivesShadow(e){(e=!1!==e)!==this._state.receivesShadow&&(this._state.receivesShadow=e,this._state.hash=e?"/mod/rs;":"/mod;",this.fire("dirty",this))}get saoEnabled(){return!1}get colorize(){return this._state.colorize}set colorize(e){let t=this._state.colorize;t||(t=this._state.colorize=new Float32Array(4),t[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);const s=!!e;this.scene._objectColorizeUpdated(this,s),this.glRedraw()}get opacity(){return this._state.colorize[3]}set opacity(e){let t=this._state.colorize;t||(t=this._state.colorize=new Float32Array(4),t[0]=1,t[1]=1,t[2]=1);const s=null!=e;t[3]=s?e:1,this.scene._objectOpacityUpdated(this,s),this.glRedraw()}get transparent(){return 2===this._material.alphaMode||this._state.colorize[3]<1}get layer(){return this._state.layer}set layer(e){e=e||0,(e=Math.round(e))!==this._state.layer&&(this._state.layer=e,this._renderer.needStateSort())}get stationary(){return this._state.stationary}get billboard(){return this._state.billboard}get offset(){return this._state.offset}set offset(e){this._state.offset.set(e||[0,0,0]),this._setAABBDirty(),this.glRedraw()}get isDrawable(){return!0}get isStateSortable(){return!0}get xrayMaterial(){return this._xrayMaterial}get highlightMaterial(){return this._highlightMaterial}get selectedMaterial(){return this._selectedMaterial}get edgeMaterial(){return this._edgeMaterial}_checkBillboard(e){return"spherical"!==(e=e||"none")&&"cylindrical"!==e&&"none"!==e&&(this.error("Unsupported value for 'billboard': "+e+" - accepted values are 'spherical', 'cylindrical' and 'none' - defaulting to 'none'."),e="none"),e}compile(){const e=this._makeDrawHash();this._state.drawHash!==e&&(this._state.drawHash=e,this._putDrawRenderers(),this._drawRenderer=Is.get(this),this._emphasisFillRenderer=gs.get(this),this._emphasisEdgesRenderer=Ps.get(this));const t=this._makePickHash();if(this._state.pickHash!==t&&(this._state.pickHash=t,this._putPickRenderers(),this._pickMeshRenderer=Bs.get(this)),this._state.occluder){const e=this._makeOcclusionHash();this._state.occlusionHash!==e&&(this._state.occlusionHash=e,this._putOcclusionRenderer(),this._occlusionRenderer=Hs.get(this))}}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}_setWorldMatrixDirty(){this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0}_buildWorldMatrix(){const e=this.matrix;if(this._parentNode)h.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(let t=0,s=e.length;t<s;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_buildWorldNormalMatrix(){this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldNormalMatrix||(this._worldNormalMatrix=h.mat4()),h.transposeMat4(this._worldMatrix,this._worldNormalMatrix),h.inverseMat4(this._worldNormalMatrix),this._worldNormalMatrixDirty=!1}_setAABBDirty(){if(this.collidable)for(let e=this;e;e=e._parentNode)e._aabbDirty=!0}_updateAABB(){this.scene._aabbDirty=!0,this._aabb||(this._aabb=h.AABB3()),this._buildAABB(this.worldMatrix,this._aabb),this._aabbDirty=!1}_webglContextRestored(){this._drawRenderer&&this._drawRenderer.webglContextRestored(),this._shadowRenderer&&this._shadowRenderer.webglContextRestored(),this._emphasisFillRenderer&&this._emphasisFillRenderer.webglContextRestored(),this._emphasisEdgesRenderer&&this._emphasisEdgesRenderer.webglContextRestored(),this._pickMeshRenderer&&this._pickMeshRenderer.webglContextRestored(),this._pickTriangleRenderer&&this._pickMeshRenderer.webglContextRestored(),this._occlusionRenderer&&this._occlusionRenderer.webglContextRestored()}_makeDrawHash(){const e=this.scene,t=[e.canvas.canvas.id,(e.gammaInput?"gi;":";")+(e.gammaOutput?"go":""),e._lightsState.getHash(),e._sectionPlanesState.getHash()],s=this._state;return s.stationary&&t.push("/s"),"none"===s.billboard?t.push("/n"):"spherical"===s.billboard?t.push("/s"):"cylindrical"===s.billboard&&t.push("/c"),s.receivesShadow&&t.push("/rs"),t.push(";"),t.join("")}_makePickHash(){const e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],s=this._state;return s.stationary&&t.push("/s"),"none"===s.billboard?t.push("/n"):"spherical"===s.billboard?t.push("/s"):"cylindrical"===s.billboard&&t.push("/c"),t.push(";"),t.join("")}_makeOcclusionHash(){const e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],s=this._state;return s.stationary&&t.push("/s"),"none"===s.billboard?t.push("/n"):"spherical"===s.billboard?t.push("/s"):"cylindrical"===s.billboard&&t.push("/c"),t.push(";"),t.join("")}_buildAABB(e,t){h.transformOBB3(e,this._geometry.obb,Qs),h.OBB3ToAABB3(Qs,t);const s=this._state.offset;if(t[0]+=s[0],t[1]+=s[1],t[2]+=s[2],t[3]+=s[0],t[4]+=s[1],t[5]+=s[2],this._state.origin){const e=this._state.origin;t[0]+=e[0],t[1]+=e[1],t[2]+=e[2],t[3]+=e[0],t[4]+=e[1],t[5]+=e[2]}}rotate(e,t){return Ws[0]=e[0],Ws[1]=e[1],Ws[2]=e[2],Ws[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Ws,zs),h.mulQuaternions(this.quaternion,zs,Ks),this.quaternion=Ks,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return Ws[0]=e[0],Ws[1]=e[1],Ws[2]=e[2],Ws[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Ws,zs),h.mulQuaternions(zs,this.quaternion,zs),this}rotateX(e){return this.rotate(Ys,e)}rotateY(e){return this.rotate(Xs,e)}rotateZ(e){return this.rotate(qs,e)}translate(e,t){return h.vec3ApplyQuaternion(this.quaternion,e,Js),h.mulVec3Scalar(Js,t,Zs),h.addVec3(this.position,Zs,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(Ys,e)}translateY(e){return this.translate(Xs,e)}translateZ(e){return this.translate(qs,e)}_putDrawRenderers(){this._drawRenderer&&(this._drawRenderer.put(),this._drawRenderer=null),this._shadowRenderer&&(this._shadowRenderer.put(),this._shadowRenderer=null),this._emphasisFillRenderer&&(this._emphasisFillRenderer.put(),this._emphasisFillRenderer=null),this._emphasisEdgesRenderer&&(this._emphasisEdgesRenderer.put(),this._emphasisEdgesRenderer=null)}_putPickRenderers(){this._pickMeshRenderer&&(this._pickMeshRenderer.put(),this._pickMeshRenderer=null),this._pickTriangleRenderer&&(this._pickTriangleRenderer.put(),this._pickTriangleRenderer=null)}_putOcclusionRenderer(){this._occlusionRenderer&&(this._occlusionRenderer.put(),this._occlusionRenderer=null)}stateSortCompare(e,t){return e._state.layer-t._state.layer||e._drawRenderer.id-t._drawRenderer.id||e._material._state.id-t._material._state.id||e._geometry._state.id-t._geometry._state.id}rebuildRenderFlags(){this.renderFlags.reset(),this._getActiveSectionPlanes()?(this.renderFlags.numLayers=1,this.renderFlags.numVisibleLayers=1,this.renderFlags.visibleLayers[0]=0,this._updateRenderFlags()):this.renderFlags.culled=!0}_updateRenderFlags(){const e=this.renderFlags,t=this._state;if(t.xrayed){const t=this._xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}else{if(this._material._state.alpha<1||t.colorize[3]<1?e.colorTransparent=!0:e.colorOpaque=!0,t.edges){this._edgeMaterial._state.alpha<1?e.edgesTransparent=!0:e.edgesOpaque=!0}if(t.selected){const t=this._selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}else if(t.highlighted){const t=this._highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}}_getActiveSectionPlanes(){if(this._state.clippable){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let s=0;s<t;s++){const t=e[s],n=this.renderFlags;if(t.active)if(this._state.origin){const e=h.planeAABB3Intersect(t.dir,t.dist,this.aabb);if(-1===e)return!1;const i=0===e;n.sectionPlanesActivePerLayer[s]=i}else n.sectionPlanesActivePerLayer[s]=!0;else n.sectionPlanesActivePerLayer[s]=!1}}return!0}drawColorOpaque(e){(this._drawRenderer||(this._drawRenderer=Is.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawColorTransparent(e){(this._drawRenderer||(this._drawRenderer=Is.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawSilhouetteXRayed(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=gs.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,0)}drawSilhouetteHighlighted(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=gs.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,1)}drawSilhouetteSelected(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=gs.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,2)}drawEdgesColorOpaque(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Ps.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawEdgesColorTransparent(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Ps.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawEdgesXRayed(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Ps.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,0)}drawEdgesHighlighted(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Ps.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,1)}drawEdgesSelected(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Ps.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,2)}drawOcclusion(e){(this._state.occluder&&this._occlusionRenderer||(this._occlusionRenderer=Hs.get(this)))&&this._occlusionRenderer.drawMesh(e,this)}drawShadow(e){(this._shadowRenderer||(this._shadowRenderer=Vs.get(this)))&&this._shadowRenderer.drawMesh(e,this)}drawPickMesh(e){(this._pickMeshRenderer||(this._pickMeshRenderer=Bs.get(this)))&&this._pickMeshRenderer.drawMesh(e,this)}canPickTriangle(){return this._geometry.isReadableGeometry}drawPickTriangles(e){(this._pickTriangleRenderer||(this._pickTriangleRenderer=xs.get(this)))&&this._pickTriangleRenderer.drawMesh(e,this)}pickTriangleSurface(e,t,s){tn(this,e,t,s)}drawPickVertices(e){}delegatePickedEntity(){return this}destroy(){super.destroy(),this._putDrawRenderers(),this._putPickRenderers(),this._putOcclusionRenderer(),this.scene._renderer.putPickID(this._state.pickID),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const tn=function(){const e=h.vec3(),t=h.vec3(),s=h.vec3(),n=h.vec3(),i=h.vec3(),a=h.vec3(),r=h.vec4(),l=h.vec3(),o=h.vec3(),c=h.vec3(),u=h.vec3(),p=h.vec3(),A=h.vec3(),d=h.vec3(),f=h.vec3(),I=h.vec3(),y=h.vec4(),m=h.vec4(),v=h.vec4(),w=h.vec3(),g=h.vec3(),T=h.vec3(),E=h.vec3(),b=h.vec3(),D=h.vec3(),P=h.vec3(),R=h.vec3(),C=h.vec3(),_=h.vec3(),O=h.vec3();return function(S,N,x,L){var M=L.primIndex;if(null!=M&&M>-1){const G=S.geometry._state,V=S.scene,j=V.camera,k=V.canvas;if("triangles"===G.primitiveName){L.primitive="triangle";const V=M,Q=G.indices,W=G.positions;let z,K,Y;if(Q){var F=Q[V+0],H=Q[V+1],U=Q[V+2];a[0]=F,a[1]=H,a[2]=U,L.indices=a,z=3*F,K=3*H,Y=3*U}else z=3*V,K=z+3,Y=K+3;if(s[0]=W[z+0],s[1]=W[z+1],s[2]=W[z+2],n[0]=W[K+0],n[1]=W[K+1],n[2]=W[K+2],i[0]=W[Y+0],i[1]=W[Y+1],i[2]=W[Y+2],G.compressGeometry){const e=G.positionsDecodeMatrix;e&&(wt.decompressPosition(s,e,s),wt.decompressPosition(n,e,n),wt.decompressPosition(i,e,i))}L.canvasPos?h.canvasPosToLocalRay(k.canvas,S.origin?B(N,S.origin):N,x,S.worldMatrix,L.canvasPos,e,t):L.origin&&L.direction&&h.worldRayToLocalRay(S.worldMatrix,L.origin,L.direction,e,t),h.normalizeVec3(t),h.rayPlaneIntersect(e,t,s,n,i,r),L.localPos=r,L.position=r,y[0]=r[0],y[1]=r[1],y[2]=r[2],y[3]=1,h.transformVec4(S.worldMatrix,y,m),l[0]=m[0],l[1]=m[1],l[2]=m[2],L.canvasPos&&S.origin&&(l[0]+=S.origin[0],l[1]+=S.origin[1],l[2]+=S.origin[2]),L.worldPos=l,h.transformVec4(j.matrix,m,v),o[0]=v[0],o[1]=v[1],o[2]=v[2],L.viewPos=o,h.cartesianToBarycentric(r,s,n,i,c),L.bary=c;const X=G.normals;if(X){if(G.compressGeometry){const e=3*F,t=3*H,s=3*U;wt.decompressNormal(X.subarray(e,e+2),u),wt.decompressNormal(X.subarray(t,t+2),p),wt.decompressNormal(X.subarray(s,s+2),A)}else u[0]=X[z],u[1]=X[z+1],u[2]=X[z+2],p[0]=X[K],p[1]=X[K+1],p[2]=X[K+2],A[0]=X[Y],A[1]=X[Y+1],A[2]=X[Y+2];const e=h.addVec3(h.addVec3(h.mulVec3Scalar(u,c[0],w),h.mulVec3Scalar(p,c[1],g),T),h.mulVec3Scalar(A,c[2],E),b);L.worldNormal=h.normalizeVec3(h.transformVec3(S.worldNormalMatrix,e,D))}const q=G.uv;if(q){if(d[0]=q[2*F],d[1]=q[2*F+1],f[0]=q[2*H],f[1]=q[2*H+1],I[0]=q[2*U],I[1]=q[2*U+1],G.compressGeometry){const e=G.uvDecodeMatrix;e&&(wt.decompressUV(d,e,d),wt.decompressUV(f,e,f),wt.decompressUV(I,e,I))}L.uv=h.addVec3(h.addVec3(h.mulVec2Scalar(d,c[0],P),h.mulVec2Scalar(f,c[1],R),C),h.mulVec2Scalar(I,c[2],_),O)}}}}}();function sn(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let s=e.radiusBottom||1;s<0&&(console.error("negative radiusBottom not allowed - will invert"),s*=-1);let n=e.height||1;n<0&&(console.error("negative height not allowed - will invert"),n*=-1);let i=e.radialSegments||32;i<0&&(console.error("negative radialSegments not allowed - will invert"),i*=-1),i<3&&(i=3);let a=e.heightSegments||1;a<0&&(console.error("negative heightSegments not allowed - will invert"),a*=-1),a<1&&(a=1);const r=!!e.openEnded;let l=e.center;const o=l?l[0]:0,c=l?l[1]:0,u=l?l[2]:0,h=n/2,p=n/a,A=2*Math.PI/i,d=1/i,f=(t-s)/a,I=[],m=[],v=[],w=[];let g,T,E,b,D,P,R,C,_,B,O;const S=(90-180*Math.atan(n/(s-t))/Math.PI)/90;for(g=0;g<=a;g++)for(D=t-g*f,P=h-g*p,T=0;T<=i;T++)E=Math.sin(T*A),b=Math.cos(T*A),m.push(D*E),m.push(S),m.push(D*b),v.push(T*d),v.push(1*g/a),I.push(D*E+o),I.push(P+c),I.push(D*b+u);for(g=0;g<a;g++)for(T=0;T<=i;T++)R=g*(i+1)+T,C=R+i,w.push(R),w.push(C),w.push(C+1),w.push(R),w.push(C+1),w.push(R+1);if(!r&&t>0){for(_=I.length/3,m.push(0),m.push(1),m.push(0),v.push(.5),v.push(.5),I.push(0+o),I.push(h+c),I.push(0+u),T=0;T<=i;T++)E=Math.sin(T*A),b=Math.cos(T*A),B=.5*Math.sin(T*A)+.5,O=.5*Math.cos(T*A)+.5,m.push(t*E),m.push(1),m.push(t*b),v.push(B),v.push(O),I.push(t*E+o),I.push(h+c),I.push(t*b+u);for(T=0;T<i;T++)l=_,R=_+1+T,w.push(R),w.push(R+1),w.push(l)}if(!r&&s>0){for(_=I.length/3,m.push(0),m.push(-1),m.push(0),v.push(.5),v.push(.5),I.push(0+o),I.push(0-h+c),I.push(0+u),T=0;T<=i;T++)E=Math.sin(T*A),b=Math.cos(T*A),B=.5*Math.sin(T*A)+.5,O=.5*Math.cos(T*A)+.5,m.push(s*E),m.push(-1),m.push(s*b),v.push(B),v.push(O),I.push(s*E+o),I.push(0-h+c),I.push(s*b+u);for(T=0;T<i;T++)l=_,R=_+1+T,w.push(l),w.push(R+1),w.push(R)}return y.apply(e,{positions:I,normals:m,uv:v,indices:w})}function nn(e={}){const t=e.lod||1,s=e.center?e.center[0]:0,n=e.center?e.center[1]:0,i=e.center?e.center[2]:0;let a=e.radius||1;a<0&&(console.error("negative radius not allowed - will invert"),a*=-1);let r=e.heightSegments||18;r<0&&(console.error("negative heightSegments not allowed - will invert"),r*=-1),r=Math.floor(t*r),r<18&&(r=18);let l=e.widthSegments||18;l<0&&(console.error("negative widthSegments not allowed - will invert"),l*=-1),l=Math.floor(t*l),l<18&&(l=18);const o=[],c=[],u=[],h=[];let p,A,d,f,I,m,v,w,g,T,E,b,D,P,R;for(p=0;p<=r;p++)for(d=p*Math.PI/r,f=Math.sin(d),I=Math.cos(d),A=0;A<=l;A++)m=2*A*Math.PI/l,v=Math.sin(m),w=Math.cos(m),g=w*f,T=I,E=v*f,b=1-A/l,D=p/r,c.push(g),c.push(T),c.push(E),u.push(b),u.push(D),o.push(s+a*g),o.push(n+a*T),o.push(i+a*E);for(p=0;p<r;p++)for(A=0;A<l;A++)P=p*(l+1)+A,R=P+l+1,h.push(P+1),h.push(R+1),h.push(R),h.push(P+1),h.push(R),h.push(P);return y.apply(e,{positions:o,normals:c,uv:u,indices:h})}const an={" ":{width:16,points:[]},"!":{width:10,points:[[5,21],[5,7],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]]},'"':{width:16,points:[[4,21],[4,14],[-1,-1],[12,21],[12,14]]},"#":{width:21,points:[[11,25],[4,-7],[-1,-1],[17,25],[10,-7],[-1,-1],[4,12],[18,12],[-1,-1],[3,6],[17,6]]},$:{width:20,points:[[8,25],[8,-4],[-1,-1],[12,25],[12,-4],[-1,-1],[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},"%":{width:24,points:[[21,21],[3,0],[-1,-1],[8,21],[10,19],[10,17],[9,15],[7,14],[5,14],[3,16],[3,18],[4,20],[6,21],[8,21],[10,20],[13,19],[16,19],[19,20],[21,21],[-1,-1],[17,7],[15,6],[14,4],[14,2],[16,0],[18,0],[20,1],[21,3],[21,5],[19,7],[17,7]]},"&":{width:26,points:[[23,12],[23,13],[22,14],[21,14],[20,13],[19,11],[17,6],[15,3],[13,1],[11,0],[7,0],[5,1],[4,2],[3,4],[3,6],[4,8],[5,9],[12,13],[13,14],[14,16],[14,18],[13,20],[11,21],[9,20],[8,18],[8,16],[9,13],[11,10],[16,3],[18,1],[20,0],[22,0],[23,1],[23,2]]},"'":{width:10,points:[[5,19],[4,20],[5,21],[6,20],[6,18],[5,16],[4,15]]},"(":{width:14,points:[[11,25],[9,23],[7,20],[5,16],[4,11],[4,7],[5,2],[7,-2],[9,-5],[11,-7]]},")":{width:14,points:[[3,25],[5,23],[7,20],[9,16],[10,11],[10,7],[9,2],[7,-2],[5,-5],[3,-7]]},"*":{width:16,points:[[8,21],[8,9],[-1,-1],[3,18],[13,12],[-1,-1],[13,18],[3,12]]},"+":{width:26,points:[[13,18],[13,0],[-1,-1],[4,9],[22,9]]},",":{width:10,points:[[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"-":{width:26,points:[[4,9],[22,9]]},".":{width:10,points:[[5,2],[4,1],[5,0],[6,1],[5,2]]},"/":{width:22,points:[[20,25],[2,-7]]},0:{width:20,points:[[9,21],[6,20],[4,17],[3,12],[3,9],[4,4],[6,1],[9,0],[11,0],[14,1],[16,4],[17,9],[17,12],[16,17],[14,20],[11,21],[9,21]]},1:{width:20,points:[[6,17],[8,18],[11,21],[11,0]]},2:{width:20,points:[[4,16],[4,17],[5,19],[6,20],[8,21],[12,21],[14,20],[15,19],[16,17],[16,15],[15,13],[13,10],[3,0],[17,0]]},3:{width:20,points:[[5,21],[16,21],[10,13],[13,13],[15,12],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},4:{width:20,points:[[13,21],[3,7],[18,7],[-1,-1],[13,21],[13,0]]},5:{width:20,points:[[15,21],[5,21],[4,12],[5,13],[8,14],[11,14],[14,13],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},6:{width:20,points:[[16,18],[15,20],[12,21],[10,21],[7,20],[5,17],[4,12],[4,7],[5,3],[7,1],[10,0],[11,0],[14,1],[16,3],[17,6],[17,7],[16,10],[14,12],[11,13],[10,13],[7,12],[5,10],[4,7]]},7:{width:20,points:[[17,21],[7,0],[-1,-1],[3,21],[17,21]]},8:{width:20,points:[[8,21],[5,20],[4,18],[4,16],[5,14],[7,13],[11,12],[14,11],[16,9],[17,7],[17,4],[16,2],[15,1],[12,0],[8,0],[5,1],[4,2],[3,4],[3,7],[4,9],[6,11],[9,12],[13,13],[15,14],[16,16],[16,18],[15,20],[12,21],[8,21]]},9:{width:20,points:[[16,14],[15,11],[13,9],[10,8],[9,8],[6,9],[4,11],[3,14],[3,15],[4,18],[6,20],[9,21],[10,21],[13,20],[15,18],[16,14],[16,9],[15,4],[13,1],[10,0],[8,0],[5,1],[4,3]]},":":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]]},";":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"<":{width:24,points:[[20,18],[4,9],[20,0]]},"=":{width:26,points:[[4,12],[22,12],[-1,-1],[4,6],[22,6]]},">":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function rn(e={}){var t=e.origin||[0,0,0],s=t[0],n=t[1],i=t[2],a=e.size||1,r=[],l=[],o=e.text;y.isNumeric(o)&&(o=""+o);for(var c,u,h,p,A,d,f,I,m,v=(o||"").split("\n"),w=0,g=0,T=.04,E=0;E<v.length;E++){c=0,h=(u=v[E]).length;for(var b=0;b<h;b++)if(p=an[u.charAt(b)]){A=1,d=-1,f=-1,I=p.points.length;for(var D=0;D<I;D++)-1!==(m=p.points[D])[0]||-1!==m[1]?(r.push(c+m[0]*a*T+s),r.push(g+m[1]*a*T+n),r.push(0+i),-1===d?d=w:(-1===f||(d=f),f=w),w++,A?A=!1:(l.push(d),l.push(f))):A=1;c+=p.width*T*a}g-=35*T*a}return y.apply(e,{primitive:"lines",positions:r,indices:l})}class ln extends C{get type(){return"SectionPlane"}constructor(e,t={}){super(e,t),this._state=new Ve({active:!0,pos:h.vec3(),dir:h.vec3(),dist:0}),this.active=t.active,this.pos=t.pos,this.dir=t.dir,this.scene._sectionPlaneCreated(this)}set active(e){this._state.active=!1!==e,this.glRedraw(),this.fire("active",this._state.active)}get active(){return this._state.active}set pos(e){this._state.pos.set(e||[0,0,0]),this._state.dist=-h.dotVec3(this._state.pos,this._state.dir),this.fire("pos",this._state.pos)}get pos(){return this._state.pos}set dir(e){this._state.dir.set(e||[0,0,-1]),this._state.dist=-h.dotVec3(this._state.pos,this._state.dir),this.glRedraw(),this.fire("dir",this._state.dir)}get dir(){return this._state.dir}get dist(){return this._state.dist}flipDir(){const e=this._state.dir;e[0]*=-1,e[1]*=-1,e[2]*=-1,this._state.dist=-h.dotVec3(this._state.pos,this._state.dir),this.fire("dir",this._state.dir),this.glRedraw()}destroy(){this._state.destroy(),this.scene._sectionPlaneDestroyed(this),super.destroy()}}const on=h.vec4(4),cn=h.vec4(),un=h.vec4(),hn=h.vec3([1,0,0]),pn=h.vec3([0,1,0]),An=h.vec3([0,0,1]),dn=h.vec3(3),fn=h.vec3(3),In=h.identityMat4();class yn extends C{constructor(e,t={}){if(super(e,t),this._parentNode=null,this._children=[],this._aabb=null,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._numTriangles=0,this._scale=h.vec3(),this._quaternion=h.identityQuaternion(),this._rotation=h.vec3(),this._position=h.vec3(),this._offset=h.vec3(),this._localMatrix=h.identityMat4(),this._worldMatrix=h.identityMat4(),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._isObject=t.isObject,this._isObject&&this.scene._registerObject(this),this.origin=t.origin,this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.offset=t.offset,t.children){const e=t.children;for(let s=0,n=e.length;s<n;s++)this.addChild(e[s],t.inheritStates)}if(t.parentId){const e=this.scene.components[t.parentId];e?e.isNode?e.addChild(this):this.error("Parent is not a Node: '"+t.parentId+"'"):this.error("Parent not found: '"+t.parentId+"'")}else t.parent&&(t.parent.isNode||this.error("Parent is not a Node"),t.parent.addChild(this))}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return this._isObject}get aabb(){return this._aabbDirty&&this._updateAABB(),this._aabb}set origin(e){e?(this._origin||(this._origin=h.vec3()),this._origin.set(e)):this._origin&&(this._origin=null);for(let t=0,s=this._children.length;t<s;t++)this._children[t].origin=e;this.glRedraw()}get origin(){return this._origin}set rtcCenter(e){this.origin=e}get rtcCenter(){return this.origin}get numTriangles(){return this._numTriangles}set visible(e){e=!1!==e,this._visible=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].visible=e;this._isObject&&this.scene._objectVisibilityUpdated(this,e)}get visible(){return this._visible}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].xrayed=e;this._isObject&&this.scene._objectXRayedUpdated(this,e)}get xrayed(){return this._xrayed}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].highlighted=e;this._isObject&&this.scene._objectHighlightedUpdated(this,e)}get highlighted(){return this._highlighted}set selected(e){e=!!e,this._selected=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].selected=e;this._isObject&&this.scene._objectSelectedUpdated(this,e)}get selected(){return this._selected}set edges(e){e=!!e,this._edges=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].edges=e}get edges(){return this._edges}set culled(e){e=!!e,this._culled=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].culled=e}get culled(){return this._culled}set clippable(e){e=!1!==e,this._clippable=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].clippable=e}get clippable(){return this._clippable}set collidable(e){e=!1!==e,this._collidable=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].collidable=e}get collidable(){return this._collidable}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].pickable=e}get pickable(){return this._pickable}set colorize(e){let t=this._colorize;t||(t=this._colorize=new Float32Array(4),t[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);for(let e=0,s=this._children.length;e<s;e++)this._children[e].colorize=t;if(this._isObject){const t=!!e;this.scene._objectColorizeUpdated(this,t)}}get colorize(){return this._colorize.slice(0,3)}set opacity(e){let t=this._colorize;t||(t=this._colorize=new Float32Array(4),t[0]=1,t[1]=1,t[2]=1),t[3]=null!=e?e:1;for(let t=0,s=this._children.length;t<s;t++)this._children[t].opacity=e;if(this._isObject){const t=null!=e;this.scene._objectOpacityUpdated(this,t)}}get opacity(){return this._colorize[3]}set castsShadow(e){e=!!e,this._castsShadow=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].castsShadow=e}get castsShadow(){return this._castsShadow}set receivesShadow(e){e=!!e,this._receivesShadow=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].receivesShadow=e}get receivesShadow(){return this._receivesShadow}get saoEnabled(){return!1}set offset(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(let e=0,t=this._children.length;e<t;e++)this._children[e].offset=this._offset;this._isObject&&this.scene._objectOffsetUpdated(this,e)}get offset(){return this._offset}get isNode(){return!0}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}_setWorldMatrixDirty(){this._worldMatrixDirty=!0;for(let e=0,t=this._children.length;e<t;e++)this._children[e]._setWorldMatrixDirty()}_buildWorldMatrix(){const e=this.matrix;if(this._parentNode)h.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(let t=0,s=e.length;t<s;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_setSubtreeAABBsDirty(e){if(e._aabbDirty=!0,e._children)for(let t=0,s=e._children.length;t<s;t++)this._setSubtreeAABBsDirty(e._children[t])}_setAABBDirty(){if(this._setSubtreeAABBsDirty(this),this.collidable)for(let e=this;e;e=e._parentNode)e._aabbDirty=!0}_updateAABB(){if(this.scene._aabbDirty=!0,this._aabb||(this._aabb=h.AABB3()),this._buildAABB)this._buildAABB(this.worldMatrix,this._aabb);else{let e;h.collapseAABB3(this._aabb);for(let t=0,s=this._children.length;t<s;t++)e=this._children[t],e.collidable&&h.expandAABB3(this._aabb,e.aabb)}this._aabbDirty=!1}addChild(e,t){if(y.isNumeric(e)||y.isString(e)){const t=e;if(!(e=this.scene.component[t]))return void this.warn("Component not found: "+y.inQuotes(t));if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+t)}else{if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+e.id);if(e._parentNode){if(e._parentNode.id===this.id)return void this.warn("Already a child: "+e.id);e._parentNode.removeChild(e)}}if(e.id,e.scene.id===this.scene.id)return this._children.push(e),e._parentNode=this,t&&(e.visible=this.visible,e.culled=this.culled,e.xrayed=this.xrayed,e.highlited=this.highlighted,e.selected=this.selected,e.edges=this.edges,e.clippable=this.clippable,e.pickable=this.pickable,e.collidable=this.collidable,e.castsShadow=this.castsShadow,e.receivesShadow=this.receivesShadow,e.colorize=this.colorize,e.opacity=this.opacity,e.offset=this.offset),e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles+=e.numTriangles,e;this.error("Child not in same Scene: "+e.id)}removeChild(e){for(let t=0,s=this._children.length;t<s;t++)if(this._children[t].id===e.id)return e._parentNode=null,this._children=this._children.splice(t,1),e._setWorldMatrixDirty(),e._setAABBDirty(),this._setAABBDirty(),void(this._numTriangles-=e.numTriangles)}removeChildren(){let e;for(let t=0,s=this._children.length;t<s;t++)e=this._children[t],e._parentNode=null,e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles-=e.numTriangles;this._children=[],this._setAABBDirty()}get numChildren(){return this._children.length}get children(){return this._children}set parent(e){if(y.isNumeric(e)||y.isString(e)){const t=e;if(!(e=this.scene.components[t]))return void this.warn("Node not found: "+y.inQuotes(t));if(!e.isNode)return void this.error("Not a Node: "+e.id)}e.scene.id===this.scene.id?this._parentNode&&this._parentNode.id===e.id?this.warn("Already a child of Node: "+e.id):e.addChild(this):this.error("Node not in same Scene: "+e.id)}get parent(){return this._parentNode}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),h.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),h.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get scale(){return this._scale}set matrix(e){this._localMatrix||(this._localMatrix=h.identityMat4()),this._localMatrix.set(e||In),h.decomposeMat4(this._localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get matrix(){return this._localMatrixDirty&&(this._localMatrix||(this._localMatrix=h.identityMat4()),h.composeMat4(this._position,this._quaternion,this._scale,this._localMatrix),this._localMatrixDirty=!1),this._localMatrix}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}rotate(e,t){return on[0]=e[0],on[1]=e[1],on[2]=e[2],on[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(on,cn),h.mulQuaternions(this.quaternion,cn,un),this.quaternion=un,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return on[0]=e[0],on[1]=e[1],on[2]=e[2],on[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(on,cn),h.mulQuaternions(cn,this.quaternion,cn),this}rotateX(e){return this.rotate(hn,e)}rotateY(e){return this.rotate(pn,e)}rotateZ(e){return this.rotate(An,e)}translate(e,t){return h.vec3ApplyQuaternion(this.quaternion,e,dn),h.mulVec3Scalar(dn,t,fn),h.addVec3(this.position,fn,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(hn,e)}translateY(e){return this.translate(pn,e)}translateZ(e){return this.translate(An,e)}get type(){return"Node"}destroy(){if(super.destroy(),this._parentNode&&this._parentNode.removeChild(this),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let s=0,n=e.length;s<n;s++)t=e[s],t.destroy()}this._children=[],this._setAABBDirty(),this.scene._aabbDirty=!0}}class mn extends Dt{get type(){return"LambertMaterial"}constructor(e,t={}){super(e,t),this._state=new Ve({type:"LambertMaterial",ambient:h.vec3([1,1,1]),color:h.vec3([1,1,1]),emissive:h.vec3([0,0,0]),alpha:null,alphaMode:0,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:"/lam;"}),this.ambient=t.ambient,this.color=t.color,this.emissive=t.emissive,this.alpha=t.alpha,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this.backfaces=t.backfaces,this.frontface=t.frontface}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set color(e){let t=this._state.color;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.color=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get color(){return this._state.color}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this._state.alphaMode=e<1?2:0,this.glRedraw())}get alpha(){return this._state.alpha}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}const vn={opaque:0,mask:1,blend:2},wn=["opaque","mask","blend"];class gn extends Dt{get type(){return"MetallicMaterial"}constructor(e,t={}){super(e,t),this._state=new Ve({type:"MetallicMaterial",baseColor:h.vec4([1,1,1]),emissive:h.vec4([0,0,0]),metallic:null,roughness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.baseColor=t.baseColor,this.metallic=t.metallic,this.roughness=t.roughness,this.specularF0=t.specularF0,this.emissive=t.emissive,this.alpha=t.alpha,t.baseColorMap&&(this._baseColorMap=this._checkComponent("Texture",t.baseColorMap)),t.metallicMap&&(this._metallicMap=this._checkComponent("Texture",t.metallicMap)),t.roughnessMap&&(this._roughnessMap=this._checkComponent("Texture",t.roughnessMap)),t.metallicRoughnessMap&&(this._metallicRoughnessMap=this._checkComponent("Texture",t.metallicRoughnessMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this._makeHash()}_makeHash(){const e=this._state,t=["/met"];this._baseColorMap&&(t.push("/bm"),this._baseColorMap._state.hasMatrix&&t.push("/mat"),t.push("/"+this._baseColorMap._state.encoding)),this._metallicMap&&(t.push("/mm"),this._metallicMap._state.hasMatrix&&t.push("/mat")),this._roughnessMap&&(t.push("/rm"),this._roughnessMap._state.hasMatrix&&t.push("/mat")),this._metallicRoughnessMap&&(t.push("/mrm"),this._metallicRoughnessMap._state.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap._state.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap._state.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/am"),this._alphaMap._state.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap._state.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}set baseColor(e){let t=this._state.baseColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.baseColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get baseColor(){return this._state.baseColor}get baseColorMap(){return this._baseColorMap}set metallic(e){e=null!=e?e:1,this._state.metallic!==e&&(this._state.metallic=e,this.glRedraw())}get metallic(){return this._state.metallic}get metallicMap(){return this._attached.metallicMap}set roughness(e){e=null!=e?e:1,this._state.roughness!==e&&(this._state.roughness=e,this.glRedraw())}get roughness(){return this._state.roughness}get roughnessMap(){return this._attached.roughnessMap}get metallicRoughnessMap(){return this._attached.metallicRoughnessMap}set specularF0(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}get specularF0(){return this._state.specularF0}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}get emissiveMap(){return this._attached.emissiveMap}get occlusionMap(){return this._attached.occlusionMap}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}get alphaMap(){return this._attached.alphaMap}get normalMap(){return this._attached.normalMap}set alphaMode(e){let t=vn[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 wn[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}destroy(){super.destroy(),this._state.destroy()}}const Tn={opaque:0,mask:1,blend:2},En=["opaque","mask","blend"];class bn extends Dt{get type(){return"SpecularMaterial"}constructor(e,t={}){super(e,t),this._state=new Ve({type:"SpecularMaterial",diffuse:h.vec3([1,1,1]),emissive:h.vec3([0,0,0]),specular:h.vec3([1,1,1]),glossiness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.diffuse=t.diffuse,this.specular=t.specular,this.glossiness=t.glossiness,this.specularF0=t.specularF0,this.emissive=t.emissive,this.alpha=t.alpha,t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.glossinessMap&&(this._glossinessMap=this._checkComponent("Texture",t.glossinessMap)),t.specularGlossinessMap&&(this._specularGlossinessMap=this._checkComponent("Texture",t.specularGlossinessMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this._makeHash()}_makeHash(){const e=this._state,t=["/spe"];this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat")),this._glossinessMap&&(t.push("/gm"),this._glossinessMap.hasMatrix&&t.push("/mat")),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._specularGlossinessMap&&(t.push("/sgm"),this._specularGlossinessMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}get diffuseMap(){return this._diffuseMap}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}get specularMap(){return this._specularMap}get specularGlossinessMap(){return this._specularGlossinessMap}set glossiness(e){e=null!=e?e:1,this._state.glossiness!==e&&(this._state.glossiness=e,this.glRedraw())}get glossiness(){return this._state.glossiness}get glossinessMap(){return this._glossinessMap}set specularF0(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}get specularF0(){return this._state.specularF0}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}get emissiveMap(){return this._emissiveMap}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}get alphaMap(){return this._alphaMap}get normalMap(){return this._normalMap}get occlusionMap(){return this._occlusionMap}set alphaMode(e){let t=Tn[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 En[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}destroy(){super.destroy(),this._state.destroy()}}function Dn(e,t,s=null){let n;const i=t;if(1009===i)return e.UNSIGNED_BYTE;if(1017===i)return e.UNSIGNED_SHORT_4_4_4_4;if(1018===i)return e.UNSIGNED_SHORT_5_5_5_1;if(1010===i)return e.BYTE;if(1011===i)return e.SHORT;if(1012===i)return e.UNSIGNED_SHORT;if(1013===i)return e.INT;if(1014===i)return e.UNSIGNED_INT;if(1015===i)return e.FLOAT;if(1016===i)return e.HALF_FLOAT;if(1021===i)return e.ALPHA;if(1023===i)return e.RGBA;if(1024===i)return e.LUMINANCE;if(1025===i)return e.LUMINANCE_ALPHA;if(1026===i)return e.DEPTH_COMPONENT;if(1027===i)return e.DEPTH_STENCIL;if(1028===i)return e.RED;if(1022===i)return e.RGBA;if(1029===i)return e.RED_INTEGER;if(1030===i)return e.RG;if(1031===i)return e.RG_INTEGER;if(1033===i)return e.RGBA_INTEGER;if(33776===i||33777===i||33778===i||33779===i)if(3001===s){const t=Fe(e,"WEBGL_compressed_texture_s3tc_srgb");if(null===t)return null;if(33776===i)return t.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(33777===i)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(33778===i)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(33779===i)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(n=Fe(e,"WEBGL_compressed_texture_s3tc"),null===n)return null;if(33776===i)return n.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===i)return n.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===i)return n.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===i)return n.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===i||35841===i||35842===i||35843===i){const t=Fe(e,"WEBGL_compressed_texture_pvrtc");if(null===t)return null;if(35840===i)return t.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===i)return t.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===i)return t.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===i)return t.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===i){const t=Fe(e,"WEBGL_compressed_texture_etc1");return null!==t?t.COMPRESSED_RGB_ETC1_WEBGL:null}if(37492===i||37496===i){const t=Fe(e,"WEBGL_compressed_texture_etc");if(null===t)return null;if(37492===i)return 3001===s?t.COMPRESSED_SRGB8_ETC2:t.COMPRESSED_RGB8_ETC2;if(37496===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:t.COMPRESSED_RGBA8_ETC2_EAC}if(37808===i||37809===i||37810===i||37811===i||37812===i||37813===i||37814===i||37815===i||37816===i||37817===i||37818===i||37819===i||37820===i||37821===i){const t=Fe(e,"WEBGL_compressed_texture_astc");if(null===t)return null;if(37808===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:t.COMPRESSED_RGBA_ASTC_4x4_KHR;if(37809===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:t.COMPRESSED_RGBA_ASTC_5x4_KHR;if(37810===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:t.COMPRESSED_RGBA_ASTC_5x5_KHR;if(37811===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:t.COMPRESSED_RGBA_ASTC_6x5_KHR;if(37812===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:t.COMPRESSED_RGBA_ASTC_6x6_KHR;if(37813===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:t.COMPRESSED_RGBA_ASTC_8x5_KHR;if(37814===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:t.COMPRESSED_RGBA_ASTC_8x6_KHR;if(37815===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:t.COMPRESSED_RGBA_ASTC_8x8_KHR;if(37816===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:t.COMPRESSED_RGBA_ASTC_10x5_KHR;if(37817===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:t.COMPRESSED_RGBA_ASTC_10x6_KHR;if(37818===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:t.COMPRESSED_RGBA_ASTC_10x8_KHR;if(37819===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:t.COMPRESSED_RGBA_ASTC_10x10_KHR;if(37820===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:t.COMPRESSED_RGBA_ASTC_12x10_KHR;if(37821===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:t.COMPRESSED_RGBA_ASTC_12x12_KHR}if(36492===i){const t=Fe(e,"EXT_texture_compression_bptc");if(null===t)return null;if(36492===i)return 3001===s?t.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:t.COMPRESSED_RGBA_BPTC_UNORM_EXT}return 1020===i?e.UNSIGNED_INT_24_8:1e3===i?e.REPEAT:1001===i?e.CLAMP_TO_EDGE:1004===i||1005===i?e.NEAREST_MIPMAP_LINEAR:1007===i?e.LINEAR_MIPMAP_NEAREST:1008===i?e.LINEAR_MIPMAP_LINEAR:1003===i?e.NEAREST:1006===i?e.LINEAR:null}const Pn=new Uint8Array([0,0,0,1]);class Rn{constructor({gl:e,target:t,format:s,type:n,wrapS:i,wrapT:a,wrapR:r,encoding:l,preloadColor:o,premultiplyAlpha:c,flipY:u}){this.gl=e,this.target=t||e.TEXTURE_2D,this.format=s||1023,this.type=n||1009,this.internalFormat=null,this.premultiplyAlpha=!!c,this.flipY=!!u,this.unpackAlignment=4,this.wrapS=i||1e3,this.wrapT=a||1e3,this.wrapR=r||1e3,this.encoding=l||3001,this.texture=e.createTexture(),o&&this.setPreloadColor(o),this.allocated=!0}setPreloadColor(e){e?(Pn[0]=Math.floor(255*e[0]),Pn[1]=Math.floor(255*e[1]),Pn[2]=Math.floor(255*e[2]),Pn[3]=Math.floor(255*(void 0!==e[3]?e[3]:1))):(Pn[0]=0,Pn[1]=0,Pn[2]=0,Pn[3]=255);const t=this.gl;if(t.bindTexture(this.target,this.texture),this.target===t.TEXTURE_CUBE_MAP){const e=[t.TEXTURE_CUBE_MAP_POSITIVE_X,t.TEXTURE_CUBE_MAP_NEGATIVE_X,t.TEXTURE_CUBE_MAP_POSITIVE_Y,t.TEXTURE_CUBE_MAP_NEGATIVE_Y,t.TEXTURE_CUBE_MAP_POSITIVE_Z,t.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(let s=0,n=e.length;s<n;s++)t.texImage2D(e[s],0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Pn)}else t.texImage2D(this.target,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Pn);t.bindTexture(this.target,null)}setTarget(e){this.target=e||this.gl.TEXTURE_2D}setImage(e,t={}){const s=this.gl;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR);let n=!1;s.bindTexture(this.target,this.texture);const i=s.getParameter(s.UNPACK_FLIP_Y_WEBGL);s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,this.flipY);const a=s.getParameter(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL);s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);const r=s.getParameter(s.UNPACK_ALIGNMENT);s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment);const l=s.getParameter(s.UNPACK_COLORSPACE_CONVERSION_WEBGL);s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE);const o=Dn(s,this.minFilter);s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,o),o!==s.NEAREST_MIPMAP_NEAREST&&o!==s.LINEAR_MIPMAP_NEAREST&&o!==s.NEAREST_MIPMAP_LINEAR&&o!==s.LINEAR_MIPMAP_LINEAR||(n=!0);const c=Dn(s,this.magFilter);c&&s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,c);const u=Dn(s,this.wrapS);u&&s.texParameteri(this.target,s.TEXTURE_WRAP_S,u);const h=Dn(s,this.wrapT);h&&s.texParameteri(this.target,s.TEXTURE_WRAP_T,h);const p=Dn(s,this.format,this.encoding),A=Dn(s,this.type),d=Cn(s,this.internalFormat,p,A,this.encoding,!1);if(this.target===s.TEXTURE_CUBE_MAP){if(y.isArray(e)){const t=e,n=[s.TEXTURE_CUBE_MAP_POSITIVE_X,s.TEXTURE_CUBE_MAP_NEGATIVE_X,s.TEXTURE_CUBE_MAP_POSITIVE_Y,s.TEXTURE_CUBE_MAP_NEGATIVE_Y,s.TEXTURE_CUBE_MAP_POSITIVE_Z,s.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(let e=0,i=n.length;e<i;e++)s.texImage2D(n[e],0,d,p,A,t[e])}}else s.texImage2D(s.TEXTURE_2D,0,d,p,A,e);n&&s.generateMipmap(this.target),s.bindTexture(this.target,null),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,i),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a),s.pixelStorei(s.UNPACK_ALIGNMENT,r),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,l)}setCompressedData({mipmaps:e,props:t={}}){const s=this.gl,n=e.length;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR),s.activeTexture(s.TEXTURE0+0),s.bindTexture(this.target,this.texture);let i=e.length>1;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,this.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE);const a=Dn(s,this.wrapS);a&&s.texParameteri(this.target,s.TEXTURE_WRAP_S,a);const r=Dn(s,this.wrapT);if(r&&s.texParameteri(this.target,s.TEXTURE_WRAP_T,r),this.type===s.TEXTURE_3D||this.type===s.TEXTURE_2D_ARRAY){const e=Dn(s,this.wrapR);e&&s.texParameteri(this.target,s.TEXTURE_WRAP_R,e),s.texParameteri(this.type,s.TEXTURE_WRAP_R,e)}i?(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,_n(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,_n(s,this.magFilter))):(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,Dn(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,Dn(s,this.magFilter)));const l=Dn(s,this.format,this.encoding),o=Dn(s,this.type),c=Cn(s,this.internalFormat,l,o,this.encoding,!1);s.texStorage2D(s.TEXTURE_2D,n,c,e[0].width,e[0].height);for(let t=0,n=e.length;t<n;t++){const n=e[t];1023!==this.format?null!==l?s.compressedTexSubImage2D(s.TEXTURE_2D,t,0,0,n.width,n.height,l,n.data):console.warn("Attempt to load unsupported compressed texture format in .setCompressedData()"):s.texSubImage2D(s.TEXTURE_2D,t,0,0,n.width,n.height,l,o,n.data)}s.bindTexture(this.target,null)}setProps(e){const t=this.gl;t.bindTexture(this.target,this.texture),this._uploadProps(e),t.bindTexture(this.target,null)}_uploadProps(e){const t=this.gl;if(void 0!==e.format&&(this.format=e.format),void 0!==e.internalFormat&&(this.internalFormat=e.internalFormat),void 0!==e.encoding&&(this.encoding=e.encoding),void 0!==e.type&&(this.type=e.type),void 0!==e.minFilter){const s=Dn(t,e.minFilter);s&&(this.minFilter=e.minFilter,t.texParameteri(this.target,t.TEXTURE_MIN_FILTER,s),s!==t.NEAREST_MIPMAP_NEAREST&&s!==t.LINEAR_MIPMAP_NEAREST&&s!==t.NEAREST_MIPMAP_LINEAR&&s!==t.LINEAR_MIPMAP_LINEAR||t.generateMipmap(this.target))}if(void 0!==e.magFilter){const s=Dn(t,e.magFilter);s&&(this.magFilter=e.magFilter,t.texParameteri(this.target,t.TEXTURE_MAG_FILTER,s))}if(void 0!==e.wrapS){const s=Dn(t,e.wrapS);s&&(this.wrapS=e.wrapS,t.texParameteri(this.target,t.TEXTURE_WRAP_S,s))}if(void 0!==e.wrapT){const s=Dn(t,e.wrapT);s&&(this.wrapT=e.wrapT,t.texParameteri(this.target,t.TEXTURE_WRAP_T,s))}}bind(e){if(this.allocated){if(this.texture){const t=this.gl;return t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,this.texture),!0}return!1}}unbind(e){if(this.allocated&&this.texture){const t=this.gl;t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,null)}}destroy(){this.allocated&&this.texture&&(this.gl.deleteTexture(this.texture),this.texture=null)}}function Cn(e,t,s,n,i,a=!1){if(null!==t){if(void 0!==e[t])return e[t];console.warn("Attempt to use non-existing WebGL internal format '"+t+"'")}let r=s;return s===e.RED&&(n===e.FLOAT&&(r=e.R32F),n===e.HALF_FLOAT&&(r=e.R16F),n===e.UNSIGNED_BYTE&&(r=e.R8)),s===e.RG&&(n===e.FLOAT&&(r=e.RG32F),n===e.HALF_FLOAT&&(r=e.RG16F),n===e.UNSIGNED_BYTE&&(r=e.RG8)),s===e.RGBA&&(n===e.FLOAT&&(r=e.RGBA32F),n===e.HALF_FLOAT&&(r=e.RGBA16F),n===e.UNSIGNED_BYTE&&(r=3001===i&&!1===a?e.SRGB8_ALPHA8:e.RGBA8),n===e.UNSIGNED_SHORT_4_4_4_4&&(r=e.RGBA4),n===e.UNSIGNED_SHORT_5_5_5_1&&(r=e.RGB5_A1)),r!==e.R16F&&r!==e.R32F&&r!==e.RG16F&&r!==e.RG32F&&r!==e.RGBA16F&&r!==e.RGBA32F||Fe(e,"EXT_color_buffer_float"),r}function _n(e,t){return 1003===t||1004===t||1005===t?e.NEAREST:e.LINEAR}function Bn(e){if(!On(e.width)||!On(e.height)){const t=document.createElement("canvas");t.width=Sn(e.width),t.height=Sn(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function On(e){return 0==(e&e-1)}function Sn(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class Nn extends C{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new Ve({texture:new Rn({gl:this.scene.canvas.gl}),matrix:h.identityMat4(),hasMatrix:t.translate&&(0!==t.translate[0]||0!==t.translate[1])||!!t.rotate||t.scale&&(0!==t.scale[0]||0!==t.scale[1]),minFilter:this._checkMinFilter(t.minFilter),magFilter:this._checkMagFilter(t.magFilter),wrapS:this._checkWrapS(t.wrapS),wrapT:this._checkWrapT(t.wrapT),flipY:this._checkFlipY(t.flipY),encoding:this._checkEncoding(t.encoding)}),this._src=null,this._image=null,this._translate=h.vec2([0,0]),this._scale=h.vec2([1,1]),this._rotate=h.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),A.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 Rn({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,s;0===this._translate[0]&&0===this._translate[1]||(t=h.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(s=h.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?h.mulMat4(t,s):s),0!==this._rotate&&(s=h.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?h.mulMat4(t,s):s),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=Bn(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let s=new Image;s.onload=function(){s=Bn(s),t._state.texture.setImage(s,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},s.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),A.memory.textures--}}const xn=A.memory,Ln=h.AABB3();class Mn extends pt{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new Ve({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._aabb=null,this._obb=h.OBB3();const s=this._state,n=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=n.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=n.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=n.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=n.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=n.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=n.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=n.TRIANGLE_FAN,s.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),s.primitive=n.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(t.indices){var i;if(t.positionsDecodeMatrix);else{const e=wt.getPositionsBounds(t.positions),a=wt.compressPositions(t.positions,e.min,e.max);i=a.quantized,s.positionsDecodeMatrix=a.decodeMatrix,s.positionsBuf=new ge(n,n.ARRAY_BUFFER,i,i.length,3,n.STATIC_DRAW),xn.positions+=s.positionsBuf.numItems,h.positions3ToAABB3(t.positions,this._aabb),h.positions3ToAABB3(i,Ln,s.positionsDecodeMatrix),h.AABB3ToOBB3(Ln,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);s.colorsBuf=new ge(n,n.ARRAY_BUFFER,e,e.length,4,n.STATIC_DRAW),xn.colors+=s.colorsBuf.numItems}if(t.uv){const e=wt.getUVBounds(t.uv),i=wt.compressUVs(t.uv,e.min,e.max),a=i.quantized;s.uvDecodeMatrix=i.decodeMatrix,s.uvBuf=new ge(n,n.ARRAY_BUFFER,a,a.length,2,n.STATIC_DRAW),xn.uvs+=s.uvBuf.numItems}if(t.normals){const e=wt.compressNormals(t.normals);let i=s.compressGeometry;s.normalsBuf=new ge(n,n.ARRAY_BUFFER,e,e.length,3,n.STATIC_DRAW,i),xn.normals+=s.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);s.indicesBuf=new ge(n,n.ELEMENT_ARRAY_BUFFER,e,e.length,1,n.STATIC_DRAW),xn.indices+=s.indicesBuf.numItems;const a=At(i,e,s.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new ge(n,n.ELEMENT_ARRAY_BUFFER,a,a.length,1,n.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),xn.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(),xn.meshes--}}var Fn={};function Hn(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let s=e.divisions||1;s<0&&(console.error("negative divisions not allowed - will invert"),s*=-1),s<1&&(s=1),t=t||10,s=s||10;const n=t/s,i=t/2,a=[],r=[];let l=0;for(let e=0,t=-i;e<=s;e++,t+=n)a.push(-i),a.push(0),a.push(t),a.push(i),a.push(0),a.push(t),a.push(t),a.push(0),a.push(-i),a.push(t),a.push(0),a.push(i),r.push(l++),r.push(l++),r.push(l++),r.push(l++);return y.apply(e,{primitive:"lines",positions:a,indices:r})}function Un(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);let n=e.xSegments||1;n<0&&(console.error("negative xSegments not allowed - will invert"),n*=-1),n<1&&(n=1);let i=e.xSegments||1;i<0&&(console.error("negative zSegments not allowed - will invert"),i*=-1),i<1&&(i=1);const a=e.center,r=a?a[0]:0,l=a?a[1]:0,o=a?a[2]:0,c=t/2,u=s/2,h=Math.floor(n)||1,p=Math.floor(i)||1,A=h+1,d=p+1,f=t/h,I=s/p,m=new Float32Array(A*d*3),v=new Float32Array(A*d*3),w=new Float32Array(A*d*2);let g,T,E,b,D,P,R,C=0,_=0;for(g=0;g<d;g++){const e=g*I-u;for(T=0;T<A;T++)E=T*f-c,m[C]=E+r,m[C+1]=l,m[C+2]=-e+o,v[C+2]=-1,w[_]=T/h,w[_+1]=(p-g)/p,C+=3,_+=2}C=0;const B=new(m.length/3>65535?Uint32Array:Uint16Array)(h*p*6);for(g=0;g<p;g++)for(T=0;T<h;T++)b=T+A*g,D=T+A*(g+1),P=T+1+A*(g+1),R=T+1+A*g,B[C]=R,B[C+1]=D,B[C+2]=b,B[C+3]=R,B[C+4]=P,B[C+5]=D,C+=6;return y.apply(e,{positions:m,normals:v,uv:w,indices:B})}function Gn(e={}){let t=e.radius||1;t<0&&(console.error("negative radius not allowed - will invert"),t*=-1),t*=.5;let s=e.tube||.3;s<0&&(console.error("negative tube not allowed - will invert"),s*=-1);let n=e.radialSegments||32;n<0&&(console.error("negative radialSegments not allowed - will invert"),n*=-1),n<4&&(n=4);let i=e.tubeSegments||24;i<0&&(console.error("negative tubeSegments not allowed - will invert"),i*=-1),i<4&&(i=4);let a=e.arc||2*Math.PI;a<0&&(console.warn("negative arc not allowed - will invert"),a*=-1),a>360&&(a=360);const r=e.center;let l=r?r[0]:0,o=r?r[1]:0;const c=r?r[2]:0,u=[],p=[],A=[],d=[];let f,I,m,v,w,g,T,E,b,D,P,R;for(E=0;E<=i;E++)for(T=0;T<=n;T++)f=T/n*a,I=.785398+E/i*Math.PI*2,l=t*Math.cos(f),o=t*Math.sin(f),m=(t+s*Math.cos(I))*Math.cos(f),v=(t+s*Math.cos(I))*Math.sin(f),w=s*Math.sin(I),u.push(m+l),u.push(v+o),u.push(w+c),A.push(1-T/n),A.push(E/i),g=h.normalizeVec3(h.subVec3([m,v,w],[l,o,c],[]),[]),p.push(g[0]),p.push(g[1]),p.push(g[2]);for(E=1;E<=i;E++)for(T=1;T<=n;T++)b=(n+1)*E+T-1,D=(n+1)*(E-1)+T-1,P=(n+1)*(E-1)+T,R=(n+1)*E+T,d.push(b),d.push(D),d.push(P),d.push(P),d.push(R),d.push(b);return y.apply(e,{positions:u,normals:p,uv:A,indices:d})}Fn.load=function(e,t){var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=function(e){t(e.target.response)},s.send()},Fn.save=function(e,t){var s="data:application/octet-stream;base64,"+btoa(Fn.parse._buffToStr(e));window.location.href=s},Fn.clone=function(e){return JSON.parse(JSON.stringify(e))},Fn.bin={},Fn.bin.f=new Float32Array(1),Fn.bin.fb=new Uint8Array(Fn.bin.f.buffer),Fn.bin.rf=function(e,t){for(var s=Fn.bin.f,n=Fn.bin.fb,i=0;i<4;i++)n[i]=e[t+i];return s[0]},Fn.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},Fn.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},Fn.bin.rASCII0=function(e,t){for(var s="";0!=e[t];)s+=String.fromCharCode(e[t++]);return s},Fn.bin.wf=function(e,t,s){new Float32Array(e.buffer,t,1)[0]=s},Fn.bin.wsl=function(e,t,s){e[t]=s,e[t+1]=s>>8},Fn.bin.wil=function(e,t,s){e[t]=s,e[t+1]=s>>8,e[t+2]=s>>16,e[t+3]},Fn.parse={},Fn.parse._buffToStr=function(e){for(var t=new Uint8Array(e),s="",n=0;n<t.length;n++)s=s.concat(String.fromCharCode(t[n]));return s},Fn.parse._strToBuff=function(e){for(var t=new ArrayBuffer(e.length),s=new Uint8Array(t),n=0;n<e.length;n++)s[n]=e.charCodeAt(n);return t},Fn.parse._readLine=function(e,t){for(var s="";10!=e[t];)s+=String.fromCharCode(e[t++]);return s},Fn.parse.fromJSON=function(e){return JSON.parse(Fn.parse._buffToStr(e))},Fn.parse.toJSON=function(e){var t=JSON.stringify(e);return Fn.parse._strToBuff(t)},Fn.parse.fromOBJ=function(e){for(var t={groups:{},c_verts:[],c_uvt:[],c_norms:[],i_verts:[],i_uvt:[],i_norms:[]},s={from:0,to:0},n=0,i=new Uint8Array(e);n<i.length;){var a=Fn.parse._readLine(i,n);n+=a.length+1;var r=(a=(a=a.replace(/ +(?= )/g,"")).replace(/(^\s+|\s+$)/g,"")).split(" ");if("g"==r[0]&&(s.to=t.i_verts.length,null==t.groups[r[1]]&&(t.groups[r[1]]={from:t.i_verts.length,to:0}),s=t.groups[r[1]]),"v"==r[0]){var l=parseFloat(r[1]),o=parseFloat(r[2]),c=parseFloat(r[3]);t.c_verts.push(l,o,c)}if("vt"==r[0]){l=parseFloat(r[1]),o=1-parseFloat(r[2]);t.c_uvt.push(l,o)}if("vn"==r[0]){l=parseFloat(r[1]),o=parseFloat(r[2]),c=parseFloat(r[3]);t.c_norms.push(l,o,c)}if("f"==r[0]){var u=r[1].split("/"),h=r[2].split("/"),p=r[3].split("/"),A=parseInt(u[0])-1,d=parseInt(h[0])-1,f=parseInt(p[0])-1,I=parseInt(u[1])-1,y=parseInt(h[1])-1,m=parseInt(p[1])-1,v=parseInt(u[2])-1,w=parseInt(h[2])-1,g=parseInt(p[2])-1,T=t.c_verts.length/3,E=t.c_uvt.length/2,b=t.c_norms.length/3;if(A<0&&(A=T+A+1),d<0&&(d=T+d+1),f<0&&(f=T+f+1),I<0&&(I=E+I+1),y<0&&(y=E+y+1),m<0&&(m=E+m+1),v<0&&(v=b+v+1),w<0&&(w=b+w+1),g<0&&(g=b+g+1),t.i_verts.push(A,d,f),t.i_uvt.push(I,y,m),t.i_norms.push(v,w,g),5==r.length){var D=r[4].split("/"),P=parseInt(D[0])-1,R=parseInt(D[1])-1,C=parseInt(D[2])-1;P<0&&(P=T+P+1),R<0&&(R=E+R+1),C<0&&(C=b+C+1),t.i_verts.push(A,f,P),t.i_uvt.push(I,m,R),t.i_norms.push(v,g,C)}}}return s.to=t.i_verts.length,t},Fn.parse.fromMD2=function(e){e=new Uint8Array(e);var t={},s={};s.ident=Fn.bin.ril(e,0),s.version=Fn.bin.ril(e,4),s.skinwidth=Fn.bin.ril(e,8),s.skinheight=Fn.bin.ril(e,12),s.framesize=Fn.bin.ril(e,16),s.num_skins=Fn.bin.ril(e,20),s.num_vertices=Fn.bin.ril(e,24),s.num_st=Fn.bin.ril(e,28),s.num_tris=Fn.bin.ril(e,32),s.num_glcmds=Fn.bin.ril(e,36),s.num_frames=Fn.bin.ril(e,40),s.offset_skins=Fn.bin.ril(e,44),s.offset_st=Fn.bin.ril(e,48),s.offset_tris=Fn.bin.ril(e,52),s.offset_frames=Fn.bin.ril(e,56),s.offset_glcmds=Fn.bin.ril(e,60),s.offset_end=Fn.bin.ril(e,64);var n=s.offset_st;t.c_uvt=[];for(var i=0;i<s.num_st;i++){var a=Fn.bin.rsl(e,n)/s.skinwidth,r=Fn.bin.rsl(e,n+2)/s.skinheight;t.c_uvt.push(a,r),n+=4}n=s.offset_tris;var l=[],o=[];t.i_verts=l,t.i_uvt=o;for(i=0;i<s.num_tris;i++)l.push(Fn.bin.rsl(e,n),Fn.bin.rsl(e,n+2),Fn.bin.rsl(e,n+4)),o.push(Fn.bin.rsl(e,n+6),Fn.bin.rsl(e,n+8),Fn.bin.rsl(e,n+10)),n+=12;n=s.offset_skins;t.skins=[];for(i=0;i<s.num_skins;i++)t.skins.push(Fn.bin.rASCII0(e,n)),n+=64;n=s.offset_frames;t.frames=[];var c=Fn.parse.fromMD2._normals;for(i=0;i<s.num_frames;i++){var u={},h=Fn.bin.rf(e,n),p=Fn.bin.rf(e,n+4),A=Fn.bin.rf(e,n+8);n+=12;var d=Fn.bin.rf(e,n),f=Fn.bin.rf(e,n+4),I=Fn.bin.rf(e,n+8);n+=12,u.name=Fn.bin.rASCII0(e,n),n+=16,u.verts=[],u.norms=[];for(var y=0;y<s.num_vertices;y++)u.verts.push(e[n]*h+d,e[n+1]*p+f,e[n+2]*A+I),u.norms.push(c[3*e[n+3]],c[3*e[n+3]+1],c[3*e[n+3]+2]),n+=4;t.frames.push(u)}return t},Fn.parse.fromMD2._normals=[-.525731,0,.850651,-.442863,.238856,.864188,-.295242,0,.955423,-.309017,.5,.809017,-.16246,.262866,.951056,0,0,1,0,.850651,.525731,-.147621,.716567,.681718,.147621,.716567,.681718,0,.525731,.850651,.309017,.5,.809017,.525731,0,.850651,.295242,0,.955423,.442863,.238856,.864188,.16246,.262866,.951056,-.681718,.147621,.716567,-.809017,.309017,.5,-.587785,.425325,.688191,-.850651,.525731,0,-.864188,.442863,.238856,-.716567,.681718,.147621,-.688191,.587785,.425325,-.5,.809017,.309017,-.238856,.864188,.442863,-.425325,.688191,.587785,-.716567,.681718,-.147621,-.5,.809017,-.309017,-.525731,.850651,0,0,.850651,-.525731,-.238856,.864188,-.442863,0,.955423,-.295242,-.262866,.951056,-.16246,0,1,0,0,.955423,.295242,-.262866,.951056,.16246,.238856,.864188,.442863,.262866,.951056,.16246,.5,.809017,.309017,.238856,.864188,-.442863,.262866,.951056,-.16246,.5,.809017,-.309017,.850651,.525731,0,.716567,.681718,.147621,.716567,.681718,-.147621,.525731,.850651,0,.425325,.688191,.587785,.864188,.442863,.238856,.688191,.587785,.425325,.809017,.309017,.5,.681718,.147621,.716567,.587785,.425325,.688191,.955423,.295242,0,1,0,0,.951056,.16246,.262866,.850651,-.525731,0,.955423,-.295242,0,.864188,-.442863,.238856,.951056,-.16246,.262866,.809017,-.309017,.5,.681718,-.147621,.716567,.850651,0,.525731,.864188,.442863,-.238856,.809017,.309017,-.5,.951056,.16246,-.262866,.525731,0,-.850651,.681718,.147621,-.716567,.681718,-.147621,-.716567,.850651,0,-.525731,.809017,-.309017,-.5,.864188,-.442863,-.238856,.951056,-.16246,-.262866,.147621,.716567,-.681718,.309017,.5,-.809017,.425325,.688191,-.587785,.442863,.238856,-.864188,.587785,.425325,-.688191,.688191,.587785,-.425325,-.147621,.716567,-.681718,-.309017,.5,-.809017,0,.525731,-.850651,-.525731,0,-.850651,-.442863,.238856,-.864188,-.295242,0,-.955423,-.16246,.262866,-.951056,0,0,-1,.295242,0,-.955423,.16246,.262866,-.951056,-.442863,-.238856,-.864188,-.309017,-.5,-.809017,-.16246,-.262866,-.951056,0,-.850651,-.525731,-.147621,-.716567,-.681718,.147621,-.716567,-.681718,0,-.525731,-.850651,.309017,-.5,-.809017,.442863,-.238856,-.864188,.16246,-.262866,-.951056,.238856,-.864188,-.442863,.5,-.809017,-.309017,.425325,-.688191,-.587785,.716567,-.681718,-.147621,.688191,-.587785,-.425325,.587785,-.425325,-.688191,0,-.955423,-.295242,0,-1,0,.262866,-.951056,-.16246,0,-.850651,.525731,0,-.955423,.295242,.238856,-.864188,.442863,.262866,-.951056,.16246,.5,-.809017,.309017,.716567,-.681718,.147621,.525731,-.850651,0,-.238856,-.864188,-.442863,-.5,-.809017,-.309017,-.262866,-.951056,-.16246,-.850651,-.525731,0,-.716567,-.681718,-.147621,-.716567,-.681718,.147621,-.525731,-.850651,0,-.5,-.809017,.309017,-.238856,-.864188,.442863,-.262866,-.951056,.16246,-.864188,-.442863,.238856,-.809017,-.309017,.5,-.688191,-.587785,.425325,-.681718,-.147621,.716567,-.442863,-.238856,.864188,-.587785,-.425325,.688191,-.309017,-.5,.809017,-.147621,-.716567,.681718,-.425325,-.688191,.587785,-.16246,-.262866,.951056,.442863,-.238856,.864188,.16246,-.262866,.951056,.309017,-.5,.809017,.147621,-.716567,.681718,0,-.525731,.850651,.425325,-.688191,.587785,.587785,-.425325,.688191,.688191,-.587785,.425325,-.955423,.295242,0,-.951056,.16246,.262866,-1,0,0,-.850651,0,.525731,-.955423,-.295242,0,-.951056,-.16246,.262866,-.864188,.442863,-.238856,-.951056,.16246,-.262866,-.809017,.309017,-.5,-.864188,-.442863,-.238856,-.951056,-.16246,-.262866,-.809017,-.309017,-.5,-.681718,.147621,-.716567,-.681718,-.147621,-.716567,-.850651,0,-.525731,-.688191,.587785,-.425325,-.587785,.425325,-.688191,-.425325,.688191,-.587785,-.425325,-.688191,-.587785,-.587785,-.425325,-.688191,-.688191,-.587785,-.425325],Fn.parse.fromCollada=function(e){var t=Fn.parse._buffToStr(e),s=(new DOMParser).parseFromString(t,"text/xml"),n={},i=(s=s.childNodes[0]).getElementsByTagName("asset")[0],a=s.getElementsByTagName("library_geometries")[0],r=s.getElementsByTagName("library_images")[0],l=s.getElementsByTagName("library_materials")[0],o=s.getElementsByTagName("library_effects")[0];return i&&(n.asset=Fn.parse.fromCollada._asset(i)),a&&(n.geometries=Fn.parse.fromCollada._libGeometries(a)),r&&(n.images=Fn.parse.fromCollada._libImages(r)),l&&(n.materials=Fn.parse.fromCollada._libMaterials(l)),o&&(n.effects=Fn.parse.fromCollada._libEffects(o)),n},Fn.parse.fromCollada._asset=function(e){return{created:e.getElementsByTagName("created")[0].textContent,modified:e.getElementsByTagName("modified")[0].textContent,up_axis:e.getElementsByTagName("up_axis")[0].textContent}},Fn.parse.fromCollada._libGeometries=function(e){e=e.getElementsByTagName("geometry");for(var t=[],s=0;s<e.length;s++){var n=e[s],i=Fn.parse.fromCollada._getMesh(n.getElementsByTagName("mesh")[0]);t.push(i)}return t},Fn.parse.fromCollada._getMesh=function(e){for(var t={},s=e.getElementsByTagName("source"),n=t.sources={},i=0;i<s.length;i++){for(var a=s[i].getElementsByTagName("float_array")[0].textContent.split(" "),r=a.length-(""==a[a.length-1]?1:0),l=new Array(r),o=0;o<r;o++)l[o]=parseFloat(a[o]);n[s[i].getAttribute("id")]=l}t.triangles=[];var c=e.getElementsByTagName("triangles");if(null==c)return t;for(i=0;i<c.length;i++){var u={},h=c[i];u.material=h.getAttribute("material");var p=h.getElementsByTagName("input"),A=[];for(o=0;o<p.length;o++){var d=p[o];l=[];A[parseInt(d.getAttribute("offset"))]=l;var f=d.getAttribute("semantic");u["s_"+f]="VERTEX"==f?e.getElementsByTagName("vertices")[0].getElementsByTagName("input")[0].getAttribute("source").substring(1):d.getAttribute("source").substring(1),u["i_"+f]=l,n[u["s_"+f]]}var I=h.getElementsByTagName("p")[0].textContent.split(" "),y=3*Math.floor(I.length/3);for(o=0;o<y;o++)A[o%p.length].push(parseInt(I[o]));t.triangles.push(u)}return t},Fn.parse.fromCollada._libImages=function(e){e=e.getElementsByTagName("image");for(var t={},s=0;s<e.length;s++)t[e[s].getAttribute("id")]=e[s].getElementsByTagName("init_from")[0].textContent;return t},Fn.parse.fromCollada._libMaterials=function(e){e=e.getElementsByTagName("material");for(var t={},s=0;s<e.length;s++)t[e[s].getAttribute("name")]=e[s].getElementsByTagName("instance_effect")[0].getAttribute("url").substring(1);return t},Fn.parse.fromCollada._libEffects=function(e){e=e.getElementsByTagName("effect");for(var t={},s=0;s<e.length;s++){for(var n={},i=e[s].getElementsByTagName("newparam"),a=0;a<i.length;a++){var r=i[a].getElementsByTagName("surface")[0];r&&(n.surface=r.getElementsByTagName("init_from")[0].textContent)}t[e[s].getAttribute("id")]=n}return t},Fn.parse.from3DS=function(e){e=new Uint8Array(e);var t={};if(19789!=Fn.bin.rsl(e,0))return null;for(var s=Fn.bin.ril(e,2),n=6;n<s;){var i=Fn.bin.rsl(e,n),a=Fn.bin.ril(e,n+2);15677==i&&(t.edit=Fn.parse.from3DS._edit3ds(e,n,a)),45056==i&&(t.keyf=Fn.parse.from3DS._keyf3ds(e,n,a)),n+=a}return t},Fn.parse.from3DS._edit3ds=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=Fn.bin.rsl(e,i),r=Fn.bin.ril(e,i+2);16384==a&&(null==n.objects&&(n.objects=[]),n.objects.push(Fn.parse.from3DS._edit_object(e,i,r))),i+=r}return n},Fn.parse.from3DS._keyf3ds=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=Fn.bin.rsl(e,i),r=Fn.bin.ril(e,i+2);45058==a&&(null==n.desc&&(n.desc=[]),n.desc.push(Fn.parse.from3DS._keyf_objdes(e,i,r))),i+=r}return n},Fn.parse.from3DS._keyf_objdes=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=Fn.bin.rsl(e,i),r=Fn.bin.ril(e,i+2);45072==a&&(n.hierarchy=Fn.parse.from3DS._keyf_objhierarch(e,i,r)),45073==a&&(n.dummy_name=Fn.bin.rASCII0(e,i+6)),i+=r}return n},Fn.parse.from3DS._keyf_objhierarch=function(e,t,s){var n={},i=t+6;return n.name=Fn.bin.rASCII0(e,i),i+=n.name.length+1,n.hierarchy=Fn.bin.rsl(e,i+4),n},Fn.parse.from3DS._edit_object=function(e,t,s){var n={},i=t+6;for(n.name=Fn.bin.rASCII0(e,i),i+=n.name.length+1;i<t+s;){var a=Fn.bin.rsl(e,i),r=Fn.bin.ril(e,i+2);16640==a&&(n.mesh=Fn.parse.from3DS._obj_trimesh(e,i,r)),i+=r}return n},Fn.parse.from3DS._obj_trimesh=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=Fn.bin.rsl(e,i),r=Fn.bin.ril(e,i+2);16656==a&&(n.vertices=Fn.parse.from3DS._tri_vertexl(e,i,r)),16672==a&&(n.indices=Fn.parse.from3DS._tri_facel1(e,i,r)),16704==a&&(n.uvt=Fn.parse.from3DS._tri_mappingcoors(e,i,r)),16736==a&&(n.local=Fn.parse.from3DS._tri_local(e,i,r)),i+=r}return n},Fn.parse.from3DS._tri_vertexl=function(e,t,s){var n=[],i=t+6,a=Fn.bin.rsl(e,i);i+=2;for(var r=0;r<a;r++)n.push(Fn.bin.rf(e,i)),n.push(Fn.bin.rf(e,i+4)),n.push(Fn.bin.rf(e,i+8)),i+=12;return n},Fn.parse.from3DS._tri_facel1=function(e,t,s){var n=[],i=t+6,a=Fn.bin.rsl(e,i);i+=2;for(var r=0;r<a;r++)n.push(Fn.bin.rsl(e,i)),n.push(Fn.bin.rsl(e,i+2)),n.push(Fn.bin.rsl(e,i+4)),i+=8;return n},Fn.parse.from3DS._tri_mappingcoors=function(e,t,s){var n=[],i=t+6,a=Fn.bin.rsl(e,i);i+=2;for(var r=0;r<a;r++)n.push(Fn.bin.rf(e,i)),n.push(1-Fn.bin.rf(e,i+4)),i+=8;return n},Fn.parse.from3DS._tri_local=function(e,t,s){var n={},i=t+6;return n.X=[Fn.bin.rf(e,i),Fn.bin.rf(e,i+4),Fn.bin.rf(e,i+8)],i+=12,n.Y=[Fn.bin.rf(e,i),Fn.bin.rf(e,i+4),Fn.bin.rf(e,i+8)],i+=12,n.Z=[Fn.bin.rf(e,i),Fn.bin.rf(e,i+4),Fn.bin.rf(e,i+8)],i+=12,n.C=[Fn.bin.rf(e,i),Fn.bin.rf(e,i+4),Fn.bin.rf(e,i+8)],i+=12,n},Fn.parse.fromBIV=function(e){e=new Uint8Array(e);var t={},s={};return s.id=Fn.bin.ril(e,0),s.verS=Fn.bin.ril(e,4),s.texS=Fn.bin.ril(e,8),s.indS=Fn.bin.ril(e,12),s.verO=Fn.bin.ril(e,16),s.verL=Fn.bin.ril(e,20),s.texO=Fn.bin.ril(e,24),s.texL=Fn.bin.ril(e,28),s.indO=Fn.bin.ril(e,32),s.indL=Fn.bin.ril(e,36),0!=s.verO&&(t.vertices=Fn.parse.fromBIV._readFloats(e,s.verO,s.verL)),0!=s.texO&&(t.uvt=Fn.parse.fromBIV._readFloats(e,s.texO,s.texL)),0!=s.indO&&(t.indices=Fn.parse.fromBIV._readInts(e,s.indO,s.indL,s.indS)),t},Fn.parse.toBIV=function(e){for(var t=0,s=0;s<e.indices.length;s++)t=Math.max(t,e.indices[s]);var n=32;t<=65535&&(n=16);var i=40;e.vertices&&(i+=4*e.vertices.length),e.uvt&&(i+=4*e.uvt.length),e.indices&&(i+=e.indices.length*n/8);var a=new Uint8Array(i);Fn.bin.wil(a,0,1769365870),Fn.bin.wil(a,4,32),Fn.bin.wil(a,8,32),Fn.bin.wil(a,12,n);var r=40;return e.vertices&&(Fn.bin.wil(a,16,r),Fn.bin.wil(a,20,4*e.vertices.length),Fn.parse.fromBIV._writeFloats(a,r,e.vertices),r+=4*e.vertices.length),e.uvt&&(Fn.bin.wil(a,24,r),Fn.bin.wil(a,28,4*e.uvt.length),Fn.parse.fromBIV._writeFloats(a,r,e.uvt),r+=4*e.uvt.length),e.indices&&(Fn.bin.wil(a,32,r),Fn.bin.wil(a,36,4*e.indices.length),Fn.parse.fromBIV._writeInts(a,r,e.indices,n)),a.buffer},Fn.parse.fromBIV._readFloats=function(e,t,s){for(var n=[],i=0;i<s/4;i++)n.push(Fn.bin.rf(e,t+4*i));return n},Fn.parse.fromBIV._writeFloats=function(e,t,s){for(var n=0;n<s.length;n++)Fn.bin.wf(e,t+4*n,s[n])},Fn.parse.fromBIV._readInts=function(e,t,s,n){for(var i=[],a=0;a<s/4;a++)16==n&&i.push(Fn.bin.rsl(e,t+2*a)),32==n&&i.push(Fn.bin.ril(e,t+4*a));return i},Fn.parse.fromBIV._writeInts=function(e,t,s,n){for(var i=0;i<s.length;i++)16==n&&Fn.bin.wsl(e,t+2*i,s[i]),32==n&&Fn.bin.wil(e,t+4*i,s[i])},Fn.gen={},Fn.gen.Plane=function(e,t,s,n){s||(s=1),n||(n=1);for(var i={verts:[],inds:[],uvt:[]},a=e+1,r=t+1,l=0;l<r;l++)for(var o=0;o<a;o++){var c=o*(2/e)-1,u=l*(2/t)-1;i.verts.push(c,u,0),i.uvt.push(s*o/e,n*l/t),l<t&&o<e&&i.inds.push(l*a+o,l*a+o+1,(l+1)*a+o,l*a+o+1,(l+1)*a+o,(l+1)*a+o+1)}return i},Fn.gen.Cube=function(){return{verts:[-1,1,-1,1,1,-1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,1,-1,1,1,-1,-1,-1,1,-1,1,1,-1,-1,1,1,1,1,1,-1,-1,-1,1,-1,-1,-1,-1,1,1,-1,1],inds:[0,1,2,1,2,3,4,5,6,5,6,7,8,9,10,9,10,11,12,13,14,13,14,15,16,17,18,17,18,19,20,21,22,21,22,23],uvt:[1/4,1/4,.5,1/4,1/4,.5,.5,.5,1,1/4,3/4,1/4,1,.5,3/4,.5,0,1/4,1/4,1/4,0,.5,1/4,.5,3/4,1/4,.5,1/4,3/4,.5,.5,.5,1/4,1/4,.5,1/4,1/4,0,.5,0,1/4,.5,.5,.5,1/4,3/4,.5,3/4]}},Fn.gen.Sphere=function(e,t){for(var s={verts:[],inds:[],uvt:[]},n=e+1,i=t+1,a=0;a<i;a++)for(var r=0;r<n;r++){var l=-Math.PI/2+a*Math.PI/t,o=2*r*Math.PI/e,c=Math.cos(l)*Math.cos(o),u=Math.sin(l),h=Math.cos(l)*Math.sin(o);s.verts.push(c,u,h),s.uvt.push(r/e,a/t),a<t&&r<e&&s.inds.push(n*a+r,n*a+r+1,n*(a+1)+r,n*a+r+1,n*(a+1)+r,n*(a+1)+r+1)}return s},Fn.mat={},Fn.mat.scale=function(e,t,s){return[e,0,0,0,0,t,0,0,0,0,s,0,0,0,0,1]},Fn.mat.translate=function(e,t,s){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,s,1]},Fn.mat.rotateDeg=function(e,t,s){var n=Math.PI/180;return Fn.mat.rotate(e*n,t*n,s*n)},Fn.mat.rotate=function(e,t,s){var n=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],i=e,a=t,r=s,l=Math.cos(i),o=Math.cos(a),c=Math.cos(r),u=Math.sin(i),h=Math.sin(a),p=Math.sin(r);return n[0]=o*c,n[1]=-o*p,n[2]=h,n[4]=l*p+u*h*c,n[5]=l*c-u*h*p,n[6]=-u*o,n[8]=u*p-l*h*c,n[9]=u*c+l*h*p,n[10]=l*o,n},Fn.edit={},Fn.edit.interpolate=function(e,t,s,n){for(var i=0;i<e.length;i++)s[i]=e[i]+n*(t[i]-e[i])},Fn.edit.transform=function(e,t){for(var s=0;s<e.length;s+=3){var n=e[s],i=e[s+1],a=e[s+2];e[s+0]=t[0]*n+t[4]*i+t[8]*a+t[12],e[s+1]=t[1]*n+t[5]*i+t[9]*a+t[13],e[s+2]=t[2]*n+t[6]*i+t[10]*a+t[14]}},Fn.edit.unwrap=function(e,t,s){for(var n=new Array(Math.floor(e.length/3)*s),i=0;i<e.length;i++)for(var a=0;a<s;a++)n[i*s+a]=t[e[i]*s+a];return n},Fn.edit.remap=function(e,t,s,n){for(var i=new Array(s.length),a=0;a<e.length;a++)for(var r=0;r<n;r++)i[t[a]*n+r]=s[e[a]*n+r];return i},Fn.utils={},Fn.utils.getAABB=function(e){var t,s,n,i,a,r;i=a=r=-(t=s=n=999999999);for(var l=0;l<e.length;l+=3){var o=e[l+0],c=e[l+1],u=e[l+2];o<t&&(t=o),o>i&&(i=o),c<s&&(s=c),c>a&&(a=c),u<n&&(n=u),c>r&&(r=u)}return{min:{x:t,y:s,z:n},max:{x:i,y:a,z:r}}};class Vn extends C{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=h.vec3(t.pos||[0,0,0]),this._up=h.vec3(t.up||[0,1,0]),this._normal=h.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=h.vec3(),this._rtcPos=h.vec3(),this._imageSize=h.vec2(),this._texture=new Nn(this),this._image=new Image,"jpg"!==this._type&&"png"!==this._type&&(this.error('Unsupported type - defaulting to "jpg"'),this._type="jpg"),this._node=new yn(this,{matrix:h.inverseMat4(h.lookAtMat4v(this._pos,h.subVec3(this._pos,this._normal,h.mat4()),this._up,h.mat4())),children:[this._bitmapMesh=new en(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new Et(this,Un({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Ct(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0})})]}),t.image?this.image=t.image:t.src?this.src=t.src:t.imageData&&(this.imageData=t.imageData),this.scene._bitmapCreated(this)}set visible(e){this._bitmapMesh.visible=e}get visible(){return this._bitmapMesh.visible}set image(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}get image(){return this._image}set src(e){if(e){this._image.onload=()=>{this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale()},this._image.src=e;switch(e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}}get src(){return this._image.src}set imageData(e){this._image.onload=()=>{this._texture.image=image,this._imageSize[0]=image.width,this._imageSize[1]=image.height,this._updateBitmapMeshScale()},this._image.src=e}get imageData(){const e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")}set type(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}get type(){return this._type}get pos(){return this._pos}get normal(){return this._normal}get up(){return this._up}set height(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}get height(){return this._height}set collidable(e){this._bitmapMesh.collidable=!1!==e}get collidable(){return this._bitmapMesh.collidable}set clippable(e){this._bitmapMesh.clippable=!1!==e}get clippable(){return this._bitmapMesh.clippable}set pickable(e){this._bitmapMesh.pickable=!1!==e}get pickable(){return this._bitmapMesh.pickable}set opacity(e){this._bitmapMesh.opacity=e}get opacity(){return this._bitmapMesh.opacity}destroy(){super.destroy(),this.scene._bitmapDestroyed(this)}_updateBitmapMeshScale(){const e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height*e,1,this._height]}}class jn extends C{constructor(e,t={}){if(super(e,t),this._positions=t.positions||[],this._origin=h.vec3(t.origin||[0,0,0]),t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;e<t;e+=2)this._indices.push(e),this._indices.push(e+1)}this._mesh=new en(this,{visible:t.visible,clippable:t.clippable,collidable:t.collidable,geometry:new Mn(this,{primitive:"lines",positions:this._positions,indices:this._indices,origin:t.origin}),material:new Ct(this,{diffuse:t.color||[0,0,0],emissive:t.color||[0,0,0]})}),this.scene._lineSetCreated(this)}set visible(e){this._mesh.visible=e}get visible(){return this._mesh.visible}get positions(){return this._positions}get indices(){return this._indices}destroy(){super.destroy(),this.scene._lineSetDestroyed(this)}}const kn=h.vec3(),Qn=h.vec3(),Wn=h.vec3(),zn=h.vec3();function Kn(e){return{x:e[0],y:e[1],z:e[2]}}function Yn(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function Xn(e){return new Float64Array([e[0],-e[2],e[1]])}function qn(e){return new Float64Array([e[0],e[2],-e[1]])}var Jn=h.vec3();const Zn=(e,t,s,n)=>{var i=e-s,a=t-n;return Math.sqrt(i*i+a*a)};class $n extends C{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var s=this.plugin.viewer.scene;this._originMarker=new Y(s,t.origin),this._targetMarker=new Y(s,t.target),this._originWorld=h.vec3(),this._targetWorld=h.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 n=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,i=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,a=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,r=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new q(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._targetDot=new q(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._lengthWire=new X(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._xAxisWire=new X(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._yAxisWire=new X(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._zAxisWire=new X(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._lengthLabel=new J(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._xAxisLabel=new J(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._yAxisLabel=new J(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._zAxisLabel=new J(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=s.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=s.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=s.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(h.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);const t=this._originMarker.viewPos[2],s=this._targetMarker.viewPos[2];if(t>-.3||s>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){h.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var n=this._pp,i=this._cp,a=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var r=a.top-t.top,l=a.left-t.left,o=e.canvas.boundary,c=o[2],u=o[3],p=0;const s=this.plugin.viewer.scene.metrics,f=s.scale,I=s.units,y=s.unitsInfo[I].abbrev;for(var A=0,d=n.length;A<d;A+=4)i[p]=l+Math.floor((1+n[A+0]/n[A+3])*c/2),i[p+1]=r+Math.floor((1-n[A+1]/n[A+3])*u/2),p+=2;if(this._originDot.setPos(i[0],i[1]),this._targetDot.setPos(i[6],i[7]),this._lengthWire.setStartAndEnd(i[0],i[1],i[6],i[7]),this._xAxisWire.setStartAndEnd(i[0],i[1],i[2],i[3]),this._yAxisWire.setStartAndEnd(i[2],i[3],i[4],i[5]),this._zAxisWire.setStartAndEnd(i[4],i[5],i[6],i[7]),this.labelsVisible){this._lengthLabel.setPosOnWire(i[0],i[1],i[6],i[7]),this._xAxisLabel.setPosOnWire(i[0],i[1],i[2],i[3]),this._yAxisLabel.setPosOnWire(i[2],i[3],i[4],i[5]),this._zAxisLabel.setPosOnWire(i[4],i[5],i[6],i[7]);const e=this._approximate?" ~ ":" = ";this._length=Math.abs(h.lenVec3(h.subVec3(this._targetWorld,this._originWorld,Jn))),this._lengthLabel.setText(e+(this._length*f).toFixed(2)+y);const t=Math.abs(Zn(i[0],i[1],i[2],i[3])),s=Math.abs(Zn(i[2],i[3],i[4],i[5])),n=Math.abs(Zn(i[4],i[5],i[6],i[7])),a=this.plugin.labelMinAxisLength;this._xAxisLabelCulled=t<a,this._yAxisLabelCulled=s<a,this._zAxisLabelCulled=n<a,this._xAxisLabelCulled?this._xAxisLabel.setCulled(!0):(this._xAxisLabel.setText(e+Math.abs((this._targetWorld[0]-this._originWorld[0])*f).toFixed(2)+y),this._xAxisLabel.setCulled(!this.axisVisible)),this._yAxisLabelCulled?this._yAxisLabel.setCulled(!0):(this._yAxisLabel.setText(e+Math.abs((this._targetWorld[1]-this._originWorld[1])*f).toFixed(2)+y),this._yAxisLabel.setCulled(!this.axisVisible)),this._zAxisLabelCulled?this._zAxisLabel.setCulled(!0):(this._zAxisLabel.setText(e+Math.abs((this._targetWorld[2]-this._originWorld[2])*f).toFixed(2)+y),this._zAxisLabel.setCulled(!this.axisVisible))}else this._lengthLabel.setCulled(!0),this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0);this._originDot.setVisible(this._visible&&this._originVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._xAxisWire.setVisible(this.axisVisible&&this.xAxisVisible),this._yAxisWire.setVisible(this.axisVisible&&this.yAxisVisible),this._zAxisWire.setVisible(this.axisVisible&&this.zAxisVisible),this._lengthWire.setVisible(this.wireVisible),this._lengthLabel.setCulled(!this.wireVisible),this._cpDirty=!1}}set approximate(e){e=!1!==e,this._approximate!==e&&(this._approximate=e,this._cpDirty=!0,this._needUpdate(0))}get approximate(){return this._approximate}get origin(){return this._originMarker}get target(){return this._targetMarker}get length(){this._update();const e=this.plugin.viewer.scene.metrics.scale;return this._length*e}get color(){return this._color}set color(e){this._color=e,this._originDot.setFillColor(e),this._targetDot.setFillColor(e),this._lengthWire.setColor(e),this._lengthLabel.setFillColor(e)}set visible(e){e=void 0!==e?Boolean(e):this.plugin.defaultVisible,this._visible=e,this._originDot.setVisible(this._visible&&this._originVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._lengthWire.setVisible(this._visible&&this._wireVisible),this._lengthLabel.setVisible(this._visible&&this._wireVisible);const t=this._visible&&this._axisVisible&&this._xAxisVisible,s=this._visible&&this._axisVisible&&this._yAxisVisible,n=this._visible&&this._axisVisible&&this._zAxisVisible;this._xAxisWire.setVisible(t),this._yAxisWire.setVisible(s),this._zAxisWire.setVisible(n),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled),this._yAxisLabel.setVisible(s&&!this._yAxisLabelCulled),this._zAxisLabel.setVisible(n&&!this._zAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get visible(){return this._visible}set originVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultOriginVisible,this._originVisible=e,this._originDot.setVisible(this._visible&&this._originVisible)}get originVisible(){return this._originVisible}set targetVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultTargetVisible,this._targetVisible=e,this._targetDot.setVisible(this._visible&&this._targetVisible)}get targetVisible(){return this._targetVisible}set axisEnabled(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._axisEnabled=e;var t=this._visible&&this._axisVisible&&this._axisEnabled;this._xAxisWire.setVisible(t&&this._xAxisVisible),this._yAxisWire.setVisible(t&&this._yAxisVisible),this._zAxisWire.setVisible(t&&this._zAxisVisible),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled&&this._xAxisVisible),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled&&this._xAxisVisible),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled&&this._xAxisVisible),this._cpDirty=!0,this._needUpdate()}get axisEnabled(){return this._axisEnabled}set axisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._axisVisible=e;var t=this._visible&&this._axisVisible&&this._axisEnabled;this._xAxisWire.setVisible(t&&this._xAxisVisible),this._yAxisWire.setVisible(t&&this._yAxisVisible),this._zAxisWire.setVisible(t&&this._zAxisVisible),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled&&this._xAxisVisible),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled&&this._yAxisVisible),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled&&this._zAxisVisible),this._cpDirty=!0,this._needUpdate()}get axisVisible(){return this._axisVisible}set xAxisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._xAxisVisible=e;const t=this._visible&&this._axisVisible&&this._xAxisVisible&&this._axisEnabled;this._xAxisWire.setVisible(t),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get xAxisVisible(){return this._xAxisVisible}set yAxisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._yAxisVisible=e;const t=this._visible&&this._axisVisible&&this._yAxisVisible&&this._axisEnabled;this._yAxisWire.setVisible(t),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get yAxisVisible(){return this._yAxisVisible}set zAxisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._zAxisVisible=e;const t=this._visible&&this._axisVisible&&this._zAxisVisible&&this._axisEnabled;this._zAxisWire.setVisible(t),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get zAxisVisible(){return this._zAxisVisible}set wireVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultWireVisible,this._wireVisible=e;var t=this._visible&&this._wireVisible;this._lengthLabel.setVisible(t),this._lengthWire.setVisible(t)}get wireVisible(){return this._wireVisible}set labelsVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultLabelsVisible,this._labelsVisible=e;var t=this._visible&&this._labelsVisible;this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled&&this._clickable&&this._axisEnabled),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled&&this._clickable&&this._axisEnabled),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled&&this._clickable&&this._axisEnabled),this._lengthLabel.setVisible(t),this._cpDirty=!0,this._needUpdate()}get labelsVisible(){return this._labelsVisible}setHighlighted(e){this._originDot.setHighlighted(e),this._targetDot.setHighlighted(e),this._xAxisWire.setHighlighted(e),this._yAxisWire.setHighlighted(e),this._zAxisWire.setHighlighted(e),this._xAxisLabel.setHighlighted(e),this._yAxisLabel.setHighlighted(e),this._zAxisLabel.setHighlighted(e),this._lengthWire.setHighlighted(e),this._lengthLabel.setHighlighted(e)}set clickable(e){e=!!e,this._clickable=e,this._originDot.setClickable(this._clickable),this._targetDot.setClickable(this._clickable),this._xAxisWire.setClickable(this._clickable),this._yAxisWire.setClickable(this._clickable),this._zAxisWire.setClickable(this._clickable),this._lengthWire.setClickable(this._clickable),this._xAxisLabel.setClickable(this._clickable),this._yAxisLabel.setClickable(this._clickable),this._zAxisLabel.setClickable(this._clickable),this._lengthLabel.setClickable(this._clickable)}get clickable(){return this._clickable}destroy(){const e=this.plugin.viewer.scene,t=e.metrics;this._onViewMatrix&&e.camera.off(this._onViewMatrix),this._onProjMatrix&&e.camera.off(this._onProjMatrix),this._onCanvasBoundary&&e.canvas.off(this._onCanvasBoundary),this._onMetricsUnits&&t.off(this._onMetricsUnits),this._onMetricsScale&&t.off(this._onMetricsScale),this._onMetricsOrigin&&t.off(this._onMetricsOrigin),this._originDot.destroy(),this._targetDot.destroy(),this._xAxisWire.destroy(),this._yAxisWire.destroy(),this._zAxisWire.destroy(),this._lengthLabel.destroy(),this._xAxisLabel.destroy(),this._yAxisLabel.destroy(),this._zAxisLabel.destroy(),this._lengthWire.destroy(),super.destroy()}}class ei{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const s=this._messages[this._locale];if(!s)return null;const n=ti(e,s);return n?t?si(n,t):n:null}translatePlurals(e,t,s){const n=this._messages[this._locale];if(!n)return null;let i=ti(e,n);return i=0===(t=parseInt(""+t,10))?i.zero:t>1?i.other:i.one,i?(i=si(i,[t]),s&&(i=si(i,s)),i):null}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==s&&(this._events[e]=t||!0);const n=this._eventSubs[e];if(n)for(const e in n)if(n.hasOwnProperty(e)){n[e].callback(t)}}on(t,s){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let n=this._eventSubs[t];n||(n={},this._eventSubs[t]=n);const i=this._eventSubIDMap.addItem();n[i]={callback:s},this._eventSubEvents[i]=t;const a=this._events[t];return void 0!==a&&s(a),i}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const s=this._eventSubs[t];s&&delete s[e],this._eventSubIDMap.removeItem(e)}}}function ti(e,t){if(t[e])return t[e];const s=e.split(".");let n=t;for(let e=0,t=s.length;n&&e<t;e++){n=n[s[e]]}return n}function si(e,t=[]){return e.replace(/\{\{|\}\}|\{(\d+)\}/g,(function(e,s){return"{{"===e?"{":"}}"===e?"}":t[s]}))}class ni extends C{constructor(e,t={}){super(e,t),this.t=t.t}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get tangent(){return this.getTangent(this._t)}get length(){var e=this._getLengths();return e[e.length-1]}getTangent(e){var t=1e-4;void 0===e&&(e=this._t);var s=e-t,n=e+t;s<0&&(s=0),n>1&&(n=1);var i=this.getPoint(s),a=this.getPoint(n),r=h.subVec3(a,i,[]);return h.normalizeVec3(r,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,s=[];for(t=0;t<=e;t++)s.push(this.getPoint(t/e));return s}_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,s,n=[],i=this.getPoint(0),a=0;for(n.push(0),s=1;s<=e;s++)t=this.getPoint(s/e),a+=h.lenVec3(h.subVec3(t,i,[])),n.push(a),i=t;return this.cacheArcLengths=n,n}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var s,n=this._getLengths(),i=0,a=n.length;s=t||e*n[a-1];for(var r,l=0,o=a-1;l<=o;)if((r=n[i=Math.floor(l+(o-l)/2)]-s)<0)l=i+1;else{if(!(r>0)){o=i;break}o=i-1}if(n[i=o]===s)return i/(a-1);var c=n[i];return(i+(s-c)/(n[i+1]-c))/(a-1)}}class ii extends ni{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 s=(t.length-1)*e,n=Math.floor(s),i=s-n,a=t[0===n?n:n-1],r=t[n],l=t[n>t.length-2?t.length-1:n+1],o=t[n>t.length-3?t.length-1:n+2],c=h.vec3();return c[0]=h.catmullRomInterpolate(a[0],r[0],l[0],o[0],i),c[1]=h.catmullRomInterpolate(a[1],r[1],l[1],o[1],i),c[2]=h.catmullRomInterpolate(a[2],r[2],l[2],o[2],i),c}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 ai=h.vec3();const ri=h.vec3(),li=h.vec3(),oi=h.vec3(),ci=h.vec3(),ui=h.vec3();class hi extends C{get type(){return"CameraFlightAnimation"}constructor(e,t={}){super(e,t),this._look1=h.vec3(),this._eye1=h.vec3(),this._up1=h.vec3(),this._look2=h.vec3(),this._eye2=h.vec3(),this._up2=h.vec3(),this._orthoScale1=1,this._orthoScale2=1,this._flying=!1,this._flyEyeLookUp=!1,this._flyingEye=!1,this._flyingLook=!1,this._callback=null,this._callbackScope=null,this._time1=null,this._time2=null,this.easing=!1!==t.easing,this.duration=t.duration,this.fit=t.fit,this.fitFOV=t.fitFOV,this.trail=t.trail}flyTo(e,t,s){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=s;const n=this.scene.camera,i=!!e.projection&&e.projection!==n.projection;let a,r,l,o,c;if(this._eye1[0]=n.eye[0],this._eye1[1]=n.eye[1],this._eye1[2]=n.eye[2],this._look1[0]=n.look[0],this._look1[1]=n.look[1],this._look1[2]=n.look[2],this._up1[0]=n.up[0],this._up1[1]=n.up[1],this._up1[2]=n.up[2],this._orthoScale1=n.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)a=e.aabb;else if(6===e.length)a=e;else if(e.eye&&e.look||e.up)r=e.eye,l=e.look,o=e.up;else if(e.eye)r=e.eye;else if(e.look)l=e.look;else{let n=e;if((y.isNumeric(n)||y.isString(n))&&(c=n,n=this.scene.components[c],!n))return this.error("Component not found: "+y.inQuotes(c)),void(t&&(s?t.call(s):t()));i||(a=n.aabb||this.scene.aabb)}const u=e.poi;if(a){if(a[3]<a[0]||a[4]<a[1]||a[5]<a[2])return;if(a[3]===a[0]&&a[4]===a[1]&&a[5]===a[2])return;a=a.slice();const t=h.getAABB3Center(a);this._look2=u||t;const s=h.subVec3(this._eye1,this._look1,ri),n=h.normalizeVec3(s),i=u?h.getAABB3DiagPoint(a,u):h.getAABB3Diag(a),r=e.fitFOV||this._fitFOV,l=Math.abs(i/Math.tan(r*h.DEGTORAD));this._orthoScale2=1.1*i,this._eye2[0]=this._look2[0]+n[0]*l,this._eye2[1]=this._look2[1]+n[1]*l,this._eye2[2]=this._look2[2]+n[2]*l,this._up2[0]=this._up1[0],this._up2[1]=this._up1[1],this._up2[2]=this._up1[2],this._flyingEyeLookUp=!0}else(r||l||o)&&(this._flyingEyeLookUp=!!r&&!!l&&!!o,this._flyingEye=!!r&&!l,this._flyingLook=!!l&&!r,r&&(this._eye2[0]=r[0],this._eye2[1]=r[1],this._eye2[2]=r[2]),l&&(this._look2[0]=l[0],this._look2[1]=l[1],this._look2[2]=l[2]),o&&(this._up2[0]=o[0],this._up2[1]=o[1],this._up2[2]=o[2]));i?("ortho"===e.projection&&"ortho"!==n.projection&&(this._projection2="ortho",this._projMatrix1=n.projMatrix.slice(),this._projMatrix2=n.ortho.matrix.slice(),n.projection="customProjection"),"perspective"===e.projection&&"perspective"!==n.projection&&(this._projection2="perspective",this._projMatrix1=n.projMatrix.slice(),this._projMatrix2=n.perspective.matrix.slice(),n.projection="customProjection")):this._projection2=null,this.fire("started",e,!0),this._time1=Date.now(),this._time2=this._time1+(e.duration?1e3*e.duration:this._duration),this._flying=!0,P.scheduleTask(this._update,this)}jumpTo(e){this._jumpTo(e)}_jumpTo(e){this._flying&&this.stop();const t=this.scene.camera;var s,n,i,a,r;if(e.aabb)s=e.aabb;else if(6===e.length)s=e;else if(e.eye||e.look||e.up)i=e.eye,a=e.look,r=e.up;else{let t=e;if((y.isNumeric(t)||y.isString(t))&&(n=t,t=this.scene.components[n],!t))return void this.error("Component not found: "+y.inQuotes(n));s=t.aabb||this.scene.aabb}const l=e.poi;if(s){if(s[3]<=s[0]||s[4]<=s[1]||s[5]<=s[2])return;var o=l?h.getAABB3DiagPoint(s,l):h.getAABB3Diag(s);let n;a=l||h.getAABB3Center(s,a),this._trail?h.subVec3(t.look,a,ui):h.subVec3(t.eye,t.look,ui),h.normalizeVec3(ui);n=(void 0!==e.fit?e.fit:this._fit)?Math.abs(o/Math.tan((e.fitFOV||this._fitFOV)*h.DEGTORAD)):h.lenVec3(h.subVec3(t.eye,t.look,ri)),h.mulVec3Scalar(ui,n),t.eye=h.addVec3(a,ui,ri),t.look=a,this.scene.camera.ortho.scale=1.1*o}else(i||a||r)&&(i&&(t.eye=i),a&&(t.look=a),r&&(t.up=r));e.projection&&(t.projection=e.projection)}_update(){if(!this._flying)return;let e=(Date.now()-this._time1)/(this._time2-this._time1);const t=e>=1;e>1&&(e=1);const s=this.easing?hi._ease(e,0,1,1):e,n=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(h.subVec3(n.eye,n.look,ui),n.eye=h.lerpVec3(s,0,1,this._eye1,this._eye2,oi),n.look=h.subVec3(oi,ui,li)):this._flyingLook&&(n.look=h.lerpVec3(s,0,1,this._look1,this._look2,li),n.up=h.lerpVec3(s,0,1,this._up1,this._up2,ci)):this._flyingEyeLookUp&&(n.eye=h.lerpVec3(s,0,1,this._eye1,this._eye2,oi),n.look=h.lerpVec3(s,0,1,this._look1,this._look2,li),n.up=h.lerpVec3(s,0,1,this._up1,this._up2,ci)),this._projection2){const t="ortho"===this._projection2?hi._easeOutExpo(e,0,1,1):hi._easeInCubic(e,0,1,1);n.customProjection.matrix=h.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else n.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return n.ortho.scale=this._orthoScale2,void this.stop();P.scheduleTask(this._update,this)}static _ease(e,t,s,n){return-s*(e/=n)*(e-2)+t}static _easeInCubic(e,t,s,n){return s*(e/=n)*e*e+t}static _easeOutExpo(e,t,s,n){return s*(1-Math.pow(2,-10*e/n))+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 pi extends C{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new hi(this),this._t=0,this.state=pi.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,s;const n=performance.now(),i=this._lastTime?.001*(n-this._lastTime):0;if(this._lastTime=n,0!==i)switch(this.state){case pi.SCRUBBING:return;case pi.PLAYING:if(this._t+=this._playingRate*i,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=pi.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case pi.PLAYING_TO:s=this._t+this._playingRate*i*this._playingDir,(this._playingDir<0&&s<=this._playingToT||this._playingDir>0&&s>=this._playingToT)&&(s=this._playingToT,this.state=pi.SCRUBBING,this.fire("stopped")),this._t=s,e.loadFrame(this._t)}}_ease(e,t,s,n){return-s*(e/=n)*(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=pi.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=pi.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const s=t.frames[e];s?this.playToT(s.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const s=this._cameraPath;if(!s)return;const n=s.frames[e];n?(this.state=pi.SCRUBBING,this._cameraFlightAnimation.flyTo(n,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=pi.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=pi.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=pi.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}pi.STOPPED=0,pi.SCRUBBING=1,pi.PLAYING=2,pi.PLAYING_TO=3;const Ai=h.vec3(),di=h.vec3();h.vec3();const fi=h.vec3([0,-1,0]),Ii=h.vec4([0,0,0,1]);function yi(e){if(!mi(e.width)||!mi(e.height)){const t=document.createElement("canvas");t.width=vi(e.width),t.height=vi(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function mi(e){return 0==(e&e-1)}function vi(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class wi extends C{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const s=this.scene.canvas.gl;this._state=new Ve({texture:new Rn({gl:s,target:s.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),A.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,s=this.scene.canvas.gl;this._images=[];let n=!1,i=0;for(let a=0;a<e.length;a++){const r=new Image;r.onload=function(){let e=r;const l=a;return function(){if(!n&&(e=yi(e),t._images[l]=e,i++,6===i)){let e=t._state.texture;e||(e=new Rn({gl:s,target:s.TEXTURE_CUBE_MAP}),t._state.texture=e),e.setImage(t._images,t._state),t.fire("loaded",t._src,!1),t.glRedraw()}}}(),r.onerror=function(){n=!0},r.src=e[a]}}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),A.memory.textures--,this._state.destroy()}}const gi=h.vec3();const Ti=h.vec3();class Ei{constructor(e,t,s,n,i=null,a=0){this.model=e,this.object=null,this.parent=null,this.id=t,this.aabb=null,this.layer=i,this.portionId=a,this._color=[s[0],s[1],s[2],n],this._colorize=[s[0],s[1],s[2],n],this._colorizing=!1,this._transparent=n<255,this.numTriangles=0,this.origin=null}_finalize(e){this.layer.initFlags(this.portionId,e,this._transparent)}_finalize2(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}_setVisible(e){this.layer.setVisible(this.portionId,e,this._transparent)}_setColor(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this.layer.setColor(this.portionId,this._color,!1)}_setColorize(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this.layer.setColor(this.portionId,this._colorize,false),this._colorizing=!0):(this.layer.setColor(this.portionId,this._color,false),this._colorizing=!1)}_setOpacity(e,t){const s=e<255,n=this._transparent!==s;this._color[3]=e,this._colorize[3]=e,this._transparent=s,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),n&&this.layer.setTransparent(this.portionId,t,s)}_setOffset(e){this.layer.setOffset(this.portionId,e)}_setHighlighted(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}_setXRayed(e){this.layer.setXRayed(this.portionId,e,this._transparent)}_setSelected(e){this.layer.setSelected(this.portionId,e,this._transparent)}_setEdges(e){this.layer.setEdges(this.portionId,e,this._transparent)}_setClippable(e){this.layer.setClippable(this.portionId,e,this._transparent)}_setCollidable(e){this.layer.setCollidable(this.portionId,e)}_setPickable(e){this.layer.setPickable(this.portionId,e,this._transparent)}_setCulled(e){this.layer.setCulled(this.portionId,e,this._transparent)}canPickTriangle(){return!1}drawPickTriangles(e,t){}pickTriangleSurface(e){}precisionRayPickSurface(e,t,s,n){return!!this.layer.precisionRayPickSurface&&this.layer.precisionRayPickSurface(this.portionId,e,t,s,n)}canPickWorldPos(){return!0}drawPickDepths(e){this.model.drawPickDepths(e)}drawPickNormals(e){this.model.drawPickNormals(e)}delegatePickedEntity(){return this.parent}getEachVertex(e){this.layer.getEachVertex(this.portionId,e)}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const bi=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 Di=0;const Pi={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},Ri=new Float32Array([1,1,1,1]),Ci=new Float32Array([0,0,0,1]),_i=h.vec4(),Bi=h.vec3();class Oi{constructor(e,t=!1,{instancing:s=!1,edges:n=!1}={}){this._scene=e,this._withSAO=t,this._instancing=s,this._edges=n,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}getValid(){return this._hash===this._getHash()}setSectionPlanesStateUniforms(e){const t=this._scene,{gl:s}=t.canvas,{model:n,layerIndex:i}=e,a=t._sectionPlanesState.sectionPlanes.length;if(a>0){const r=t._sectionPlanesState.sectionPlanes,l=i*a,o=n.renderFlags;for(let t=0;t<a;t++){const n=this._uSectionPlanes[t];if(n){const i=o.sectionPlanesActivePerLayer[l+t];if(s.uniform1i(n.active,i?1:0),i){const i=r[t],a=e._state.origin;if(a){const e=N(i.dist,i.dir,a,Bi);s.uniform3fv(n.pos,e)}else s.uniform3fv(n.pos,i.pos);s.uniform3fv(n.dir,i.dir)}}}}}_allocate(){const e=this._scene,t=e.canvas.gl,s=e._lightsState;if(this._program=new we(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uColor=n.getLocation("color"),this._uColor||(this._uColor=n.getLocation("silhouetteColor")),this._uUVDecodeMatrix=n.getLocation("uvDecodeMatrix"),this._uPickInvisible=n.getLocation("pickInvisible"),this._uGammaFactor=n.getLocation("gammaFactor"),t.uniformBlockBinding(n.handle,t.getUniformBlockIndex(n.handle,"Matrices"),this._matricesUniformBlockBufferBindingPoint),this._uShadowViewMatrix=n.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=n.getLocation("shadowProjMatrix"),e.logarithmicDepthBufferEnabled&&(this._uZFar=n.getLocation("zFar")),this._uLightAmbient=n.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const i=s.lights;let a;for(let e=0,t=i.length;e<t;e++)switch(a=i[e],a.type){case"dir":this._uLightColor[e]=n.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=n.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=n.getLocation("lightColor"+e),this._uLightPos[e]=n.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=n.getLocation("lightAttenuation"+e);break;case"spot":this._uLightColor[e]=n.getLocation("lightColor"+e),this._uLightPos[e]=n.getLocation("lightPos"+e),this._uLightDir[e]=n.getLocation("lightDir"+e),this._uLightAttenuation[e]=n.getLocation("lightAttenuation"+e)}s.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),s.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+t),pos:n.getLocation("sectionPlanePos"+t),dir:n.getLocation("sectionPlaneDir"+t)});this._aPosition=n.getAttribute("position"),this._aOffset=n.getAttribute("offset"),this._aNormal=n.getAttribute("normal"),this._aUV=n.getAttribute("uv"),this._aColor=n.getAttribute("color"),this._aMetallicRoughness=n.getAttribute("metallicRoughness"),this._aFlags=n.getAttribute("flags"),this._aPickColor=n.getAttribute("pickColor"),this._uPickZNear=n.getLocation("pickZNear"),this._uPickZFar=n.getLocation("pickZFar"),this._uColorMap="uColorMap",this._uMetallicRoughMap="uMetallicRoughMap",this._uEmissiveMap="uEmissiveMap",this._uNormalMap="uNormalMap",this._uAOMap="uAOMap",this._instancing&&(this._aModelMatrixCol0=n.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=n.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=n.getAttribute("modelMatrixCol2"),this._aModelNormalMatrixCol0=n.getAttribute("modelNormalMatrixCol0"),this._aModelNormalMatrixCol1=n.getAttribute("modelNormalMatrixCol1"),this._aModelNormalMatrixCol2=n.getAttribute("modelNormalMatrixCol2")),this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=n.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),e.pointsMaterial._state.filterIntensity&&(this._uIntensityRange=n.getLocation("intensityRange")),this._uPointSize=n.getLocation("pointSize"),this._uNearPlaneHeight=n.getLocation("nearPlaneHeight")}_bindProgram(e){const t=this._scene,s=t.canvas.gl,n=this._program,i=t._lightsState,a=i.lights,r=t.camera.project;n.bind(),e.textureUnit=0,this._uLightAmbient&&s.uniform4fv(this._uLightAmbient,i.getAmbientColorAndIntensity());for(let e=0,t=a.length;e<t;e++){const t=a[e];this._uLightColor[e]&&s.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(s.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&s.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&s.uniform3fv(this._uLightDir[e],t.dir)}if(this._withSAO){const n=t.sao;if(n.possible){const t=s.drawingBufferWidth,i=s.drawingBufferHeight;_i[0]=t,_i[1]=i,_i[2]=n.blendCutoff,_i[3]=n.blendFactor,s.uniform4fv(this._uSAOParams,_i),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,0)}}if(t.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}this._uGammaFactor&&s.uniform1f(this._uGammaFactor,t.gammaFactor),this._uPickInvisible&&s.uniform1i(this._uPickInvisible,e.pickInvisible),this._uShadowViewMatrix&&s.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),this._uShadowProjMatrix&&s.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix)}_makeVAO(e){const t=this._scene.canvas.gl,s=t.createVertexArray();return t.bindVertexArray(s),this._instancing&&(this._aModelMatrixCol0.bindArrayBuffer(e.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(e.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(e.modelMatrixCol2Buf),t.vertexAttribDivisor(this._aModelMatrixCol0.location,1),t.vertexAttribDivisor(this._aModelMatrixCol1.location,1),t.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aModelNormalMatrixCol0&&(this._aModelNormalMatrixCol0.bindArrayBuffer(e.modelNormalMatrixCol0Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol0.location,1)),this._aModelNormalMatrixCol1&&(this._aModelNormalMatrixCol1.bindArrayBuffer(e.modelNormalMatrixCol1Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol1.location,1)),this._aModelNormalMatrixCol2&&(this._aModelNormalMatrixCol2.bindArrayBuffer(e.modelNormalMatrixCol2Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol2.location,1))),this._aPosition.bindArrayBuffer((this._instancing,e.positionsBuf)),this._aUV&&this._aUV.bindArrayBuffer((this._instancing,e.uvBuf)),this._aNormal&&this._aNormal.bindArrayBuffer((this._instancing,e.normalsBuf)),this._aMetallicRoughness&&(this._aMetallicRoughness.bindArrayBuffer(e.metallicRoughnessBuf),this._instancing&&t.vertexAttribDivisor(this._aMetallicRoughness.location,1)),this._aColor&&(this._aColor.bindArrayBuffer((e.colorsBuf,e.colorsBuf)),this._instancing&&e.colorsBuf&&t.vertexAttribDivisor(this._aColor.location,1)),this._aFlags&&(this._aFlags.bindArrayBuffer(e.flagsBuf),this._instancing&&t.vertexAttribDivisor(this._aFlags.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(e.offsetsBuf),this._instancing&&t.vertexAttribDivisor(this._aOffset.location,1)),this._aPickColor&&(this._aPickColor.bindArrayBuffer(e.pickColorsBuf),this._instancing&&t.vertexAttribDivisor(this._aPickColor.location,1)),this._instancing,this._edges?e.edgeIndicesBuf.bind():e.indicesBuf&&e.indicesBuf.bind(),s}drawLayer(e,t,s,{colorUniform:n=!1,incrementDrawState:i=!1}={}){const a=oe.MAX_TEXTURE_IMAGE_UNITS,r=this._scene,l=r.canvas.gl,{_state:o,model:c}=t,{textureSet:u,origin:h,positionsDecodeMatrix:p}=o,A=r._lightsState,d=r.pointsMaterial,{camera:f}=c.scene,{viewNormalMatrix:I,project:y}=f,m=e.pickViewMatrix||f.viewMatrix,{worldMatrix:v,worldNormalMatrix:w}=c;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),this._vaoCache.has(t)?l.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(o));let g=0;if(this._matricesUniformBlockBufferData.set(v,0),this._matricesUniformBlockBufferData.set(h?B(m,h):m,g+=16),this._matricesUniformBlockBufferData.set(e.pickProjMatrix||y.matrix,g+=16),this._matricesUniformBlockBufferData.set(p,g+=16),this._matricesUniformBlockBufferData.set(w,g+=16),this._matricesUniformBlockBufferData.set(I,g+=16),l.bindBuffer(l.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),l.bufferData(l.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,l.DYNAMIC_DRAW),l.bindBufferBase(l.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer),l.uniform1i(this._uRenderPass,s),this.setSectionPlanesStateUniforms(t),r.logarithmicDepthBufferEnabled){if(this._uLogDepthBufFC){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,t)}this._uZFar&&l.uniform1f(this._uZFar,r.camera.project.far)}if(this._uPickInvisible&&l.uniform1i(this._uPickInvisible,e.pickInvisible),this._uPickZNear&&l.uniform1f(this._uPickZNear,e.pickZNear),this._uPickZFar&&l.uniform1f(this._uPickZFar,e.pickZFar),this._uPositionsDecodeMatrix&&l.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,o.positionsDecodeMatrix),this._uUVDecodeMatrix&&l.uniformMatrix3fv(this._uUVDecodeMatrix,!1,(this._instancing,o.uvDecodeMatrix)),this._uIntensityRange&&d.filterIntensity&&l.uniform2f(this._uIntensityRange,d.minIntensity,d.maxIntensity),this._uPointSize&&l.uniform1f(this._uPointSize,d.pointSize),this._uNearPlaneHeight){const e="ortho"===r.camera.projection?1:l.drawingBufferHeight/(2*Math.tan(.5*r.camera.perspective.fov*Math.PI/180));l.uniform1f(this._uNearPlaneHeight,e)}if(u){const{colorTexture:t,metallicRoughnessTexture:s,emissiveTexture:n,normalsTexture:i,occlusionTexture:r}=u;this._uColorMap&&t&&(this._program.bindTexture(this._uColorMap,t.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uMetallicRoughMap&&s&&(this._program.bindTexture(this._uMetallicRoughMap,s.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uEmissiveMap&&n&&(this._program.bindTexture(this._uEmissiveMap,n.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uNormalMap&&i&&(this._program.bindTexture(this._uNormalMap,i.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uAOMap&&r&&(this._program.bindTexture(this._uAOMap,r.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a)}if(A.reflectionMaps.length>0&&A.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,A.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a,e.bindTexture++),A.lightMaps.length>0&&A.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,A.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a,e.bindTexture++),this._withSAO){const t=r.sao;if(t.possible){const s=l.drawingBufferWidth,n=l.drawingBufferHeight;_i[0]=s,_i[1]=n,_i[2]=t.blendCutoff,_i[3]=t.blendFactor,l.uniform4fv(this._uSAOParams,_i),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a,e.bindTexture++}}if(n){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(s===Pi[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const s=r.xrayMaterial._state,n=s[e],i=s[t];l.uniform4f(this._uColor,n[0],n[1],n[2],i)}else if(s===Pi[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const s=r.highlightMaterial._state,n=s[e],i=s[t];l.uniform4f(this._uColor,n[0],n[1],n[2],i)}else if(s===Pi[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const s=r.selectedMaterial._state,n=s[e],i=s[t];l.uniform4f(this._uColor,n[0],n[1],n[2],i)}else l.uniform4fv(this._uColor,this._edges?Ci:Ri)}this._draw({state:o,frameCtx:e,incrementDrawState:i}),l.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,A.memory.programs--}}class Si extends Oi{constructor(e,t,{instancing:s=!1,edges:n=!1}={}){super(e,t,{instancing:s,edges:n})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;if(this._edges)t.drawElements(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0);else{const e=n.pickElementsCount||s.indicesBuf.numItems,a=n.pickElementsOffset?n.pickElementsOffset*s.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,s.indicesBuf.itemType,a),i&&n.drawElements++}}}class Ni extends Si{constructor(e,t){super(e,t,{instancing:!1,edges:!0})}}class xi extends Oi{constructor(e,t,{edges:s=!1}={}){super(e,t,{instancing:!0,edges:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;this._edges?t.drawElementsInstanced(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0,s.numInstances):(t.drawElementsInstanced(t.TRIANGLES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),i&&n.drawElements++)}}class Li extends xi{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class Mi extends Oi{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawArrays(t.POINTS,0,s.positionsBuf.numItems),i&&n.drawArrays++}}class Fi extends Oi{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawArraysInstanced(t.POINTS,0,s.positionsBuf.numItems,s.numInstances),i&&n.drawArrays++}}class Hi extends Oi{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawElements(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0),i&&n.drawElements++}}class Ui extends Oi{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawElementsInstanced(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),i&&n.drawElements++}}class Gi extends Si{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0;let i;const a=[];a.push("#version 300 es"),a.push("// Triangles batching draw vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec3 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),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;");for(let e=0,t=s.lights.length;e<t;e++)i=s.lights[e],"ambient"!==i.type&&(a.push("uniform vec4 lightColor"+e+";"),"dir"===i.type&&a.push("uniform vec3 lightDir"+e+";"),"point"===i.type&&a.push("uniform vec3 lightPos"+e+";"),"spot"===i.type&&(a.push("uniform vec3 lightPos"+e+";"),a.push("uniform vec3 lightDir"+e+";")));a.push("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),n&&(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 = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),a.push("vec3 viewNormal = normalize((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;");for(let e=0,t=s.lights.length;e<t;e++)if(i=s.lights[e],"ambient"!==i.type){if("dir"===i.type)"view"===i.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===i.type)"view"===i.space?a.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):a.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==i.type)continue;"view"===i.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}a.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),a.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}return a.push("vec3 rgb = (vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0));"),a.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),a.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(a.push("vFragDepth = 1.0 + clipPos.w;"),a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags = flags;")),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching 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;")),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){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):n.push(" outColor = vColor;"),n.push("}"),n}}class Vi extends Si{_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.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching flat-shading draw vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._lightsState,s=e._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),n){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}this._addMatricesUniformBlockLines(i),i.push("uniform vec4 lightAmbient;");for(let e=0,s=t.lights.length;e<s;e++){const s=t.lights[e];"ambient"!==s.type&&(i.push("uniform vec4 lightColor"+e+";"),"dir"===s.type&&i.push("uniform vec3 lightDir"+e+";"),"point"===s.type&&i.push("uniform vec3 lightPos"+e+";"),"spot"===s.type&&(i.push("uniform vec3 lightPos"+e+";"),i.push("uniform vec3 lightDir"+e+";")))}if(i.push("in vec4 vViewPosition;"),i.push("in vec4 vColor;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}i.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),i.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),i.push("float lambertian = 1.0;"),i.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),i.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),i.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,s=t.lights.length;e<s;e++){const s=t.lights[e];if("ambient"!==s.type){if("dir"===s.type)"view"===s.space?i.push("viewLightDir = normalize(lightDir"+e+");"):i.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===s.type)"view"===s.space?i.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):i.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==s.type)continue;"view"===s.space?i.push("viewLightDir = normalize(lightDir"+e+");"):i.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}i.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),i.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return i.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(fragColor.rgb * ambient, 1.0);")):i.push(" outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class ji extends Si{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Triangles batching silhouette fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}return e.logarithmicDepthBufferEnabled&&a.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("outColor = vColor;"),a.push("}"),a}}class ki extends Ni{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class Qi extends Ni{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class Wi extends Si{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry picking 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("in vec4 vPickColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vPickColor; "),n.push("}"),n}}class zi extends Si{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching pick depth 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 float pickZNear;"),n.push("uniform float pickZFar;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("in vec4 vViewPosition;"),n.push("vec4 packDepth(const in float depth) {"),n.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),n.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),n.push(" vec4 res = fract(depth * bitShift);"),n.push(" res -= res.xxyz * bitMask;"),n.push(" return res;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class Ki extends Si{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec3 worldNormal = octDecode(normal.xy); "),s.push(" vWorldNormal = worldNormal;"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching pick normals 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("in vec3 vWorldNormal;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),n.push("}"),n}}class Yi extends Si{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching occlusion 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),n.push("}"),n}}class Xi extends Si{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching depth fragment shader"),n.push("precision highp float;"),n.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(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("const float shiftRight8 = 1.0 / 256.;"),n.push("vec4 packDepthToRGBA( const in float v ) {"),n.push(" vec4 r = vec4( fract( v * packFactors ), v );"),n.push(" r.yzw -= r.xyz * shiftRight8;"),n.push(" return r * packUpScale;"),n.push("}"),n.push("in vec2 vHighPrecisionZW;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),n.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),n.push("}"),n}}class qi extends Si{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry normals 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}class Ji extends Si{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry shadow vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" int colorFlag = int(flags) & 0xF;"),s.push(" bool visible = (colorFlag > 0);"),s.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push(" if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry shadow fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("in vec4 vViewPosition;"),s.push("vec4 encodeFloat( const in float v ) {"),s.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),s.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),s.push(" vec4 comp = fract(v * bitShift);"),s.push(" comp -= comp.xxyz * bitMask;"),s.push(" return comp;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),t){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n<e.sectionPlanes.length;n++)s.push(" if (sectionPlaneActive"+n+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = encodeFloat( gl_FragCoord.z); "),s.push("}"),s}}class Zi extends Si{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0,i=t.clippingCaps,a=[];return a.push("#version 300 es"),a.push("// Triangles batching quality draw vertex shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("precision highp usampler2D;"),a.push("precision highp isampler2D;"),a.push("precision highp sampler2D;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("precision mediump usampler2D;"),a.push("precision mediump isampler2D;"),a.push("precision mediump sampler2D;"),a.push("#endif"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec3 normal;"),a.push("in vec4 color;"),a.push("in vec2 uv;"),a.push("in vec2 metallicRoughness;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),this._addMatricesUniformBlockLines(a,!0),a.push("uniform mat3 uvDecodeMatrix;"),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("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),a.push("out vec4 vViewPosition;"),a.push("out vec3 vViewNormal;"),a.push("out vec4 vColor;"),a.push("out vec2 vUV;"),a.push("out vec2 vMetallicRoughness;"),s.lightMaps.length>0&&a.push("out vec3 vWorldNormal;"),n&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;"),i&&a.push("out vec4 vClipPosition;")),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 = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),a.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),a.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),a.push("vFragDepth = 1.0 + clipPos.w;")),n&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags = flags;"),i&&a.push("vClipPosition = clipPos;")),a.push("vViewPosition = viewPosition;"),a.push("vViewNormal = viewNormal;"),a.push("vColor = color;"),a.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),a.push("vMetallicRoughness = metallicRoughness;"),s.lightMaps.length>0&&a.push("vWorldNormal = worldNormal.xyz;"),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,n=e._lightsState,i=s.sectionPlanes.length>0,a=s.clippingCaps,r=[];r.push("#version 300 es"),r.push("// Triangles batching quality 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;")),r.push("uniform sampler2D uColorMap;"),r.push("uniform sampler2D uMetallicRoughMap;"),r.push("uniform sampler2D uEmissiveMap;"),r.push("uniform sampler2D uNormalMap;"),r.push("uniform sampler2D uAOMap;"),r.push("in vec4 vViewPosition;"),r.push("in vec3 vViewNormal;"),r.push("in vec4 vColor;"),r.push("in vec2 vUV;"),r.push("in vec2 vMetallicRoughness;"),n.lightMaps.length>0&&r.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(r,!0),n.reflectionMaps.length>0&&r.push("uniform samplerCube reflectionMap;"),n.lightMaps.length>0&&r.push("uniform samplerCube lightMap;"),r.push("uniform vec4 lightAmbient;");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];"ambient"!==t.type&&(r.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&r.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&r.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(r.push("uniform vec3 lightPos"+e+";"),r.push("uniform vec3 lightDir"+e+";")))}if(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("}")),r.push("uniform float gammaFactor;"),r.push("vec4 linearToLinear( in vec4 value ) {"),r.push(" return value;"),r.push("}"),r.push("vec4 sRGBToLinear( in vec4 value ) {"),r.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 );"),r.push("}"),r.push("vec4 gammaToLinear( in vec4 value) {"),r.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),r.push("}"),t&&(r.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),r.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),r.push("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;"),a&&r.push("in vec4 vClipPosition;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}if(r.push("#define PI 3.14159265359"),r.push("#define RECIPROCAL_PI 0.31830988618"),r.push("#define RECIPROCAL_PI2 0.15915494"),r.push("#define EPSILON 1e-6"),r.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),r.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),r.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),r.push(" if (texel.x == 0.0 && texel.y == 0.0 && texel.z == 0.0) {"),r.push(" return surf_norm;"),r.push(" }"),r.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),r.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),r.push(" vec2 st0 = dFdx( uv.st );"),r.push(" vec2 st1 = dFdy( uv.st );"),r.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),r.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),r.push(" vec3 N = normalize( surf_norm );"),r.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),r.push(" mat3 tsn = mat3( S, T, N );"),r.push(" return normalize( tsn * mapN );"),r.push("}"),r.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),r.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),r.push("}"),r.push("struct IncidentLight {"),r.push(" vec3 color;"),r.push(" vec3 direction;"),r.push("};"),r.push("struct ReflectedLight {"),r.push(" vec3 diffuse;"),r.push(" vec3 specular;"),r.push("};"),r.push("struct Geometry {"),r.push(" vec3 position;"),r.push(" vec3 viewNormal;"),r.push(" vec3 worldNormal;"),r.push(" vec3 viewEyeDir;"),r.push("};"),r.push("struct Material {"),r.push(" vec3 diffuseColor;"),r.push(" float specularRoughness;"),r.push(" vec3 specularColor;"),r.push(" float shine;"),r.push("};"),r.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),r.push(" float r = ggxRoughness + 0.0001;"),r.push(" return (2.0 / (r * r) - 2.0);"),r.push("}"),r.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),r.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),r.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),r.push("}"),n.reflectionMaps.length>0&&(r.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),r.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),r.push(" return envMapColor;"),r.push("}")),r.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),r.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),r.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),r.push("}"),r.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" return 1.0 / ( gl * gv );"),r.push("}"),r.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" return 0.5 / max( gv + gl, EPSILON );"),r.push("}"),r.push("float D_GGX(const in float alpha, const in float dotNH) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),r.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float alpha = ( roughness * roughness );"),r.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),r.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),r.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),r.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),r.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),r.push(" vec3 F = F_Schlick( specularColor, dotLH );"),r.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),r.push(" float D = D_GGX( alpha, dotNH );"),r.push(" return F * (G * D);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),r.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),r.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),r.push(" vec4 r = roughness * c0 + c1;"),r.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),r.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),r.push(" return specularColor * AB.x + AB.y;"),r.push("}"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&(r.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.lightMaps.length>0&&(r.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),r.push(" irradiance *= PI;"),r.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),n.reflectionMaps.length>0&&(r.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),r.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),r.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),r.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),r.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),r.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),r.push("}")),r.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),r.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),r.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),r.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");a?(r.push(" if (dist > (0.002 * vClipPosition.w)) {"),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" return;"),r.push("}")):(r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }")),r.push("}")}r.push("IncidentLight light;"),r.push("Material material;"),r.push("Geometry geometry;"),r.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),r.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),r.push("float opacity = float(vColor.a) / 255.0;"),r.push("vec3 baseColor = rgb;"),r.push("float specularF0 = 1.0;"),r.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),r.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),r.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),r.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),r.push("baseColor *= colorTexel.rgb;"),r.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),r.push("metallic *= metalRoughTexel.b;"),r.push("roughness *= metalRoughTexel.g;"),r.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),r.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),r.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),r.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),r.push("geometry.position = vViewPosition.xyz;"),r.push("geometry.viewNormal = -normalize(viewNormal);"),r.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),n.lightMaps.length>0&&r.push("geometry.worldNormal = normalize(vWorldNormal);"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&r.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?r.push("light.direction = normalize(lightPos"+e+" - vViewPosition.xyz);"):r.push("light.direction = normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}r.push("light.color = lightColor"+e+".rgb * lightColor"+e+".a;"),r.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return r.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;"),r.push("float aoFactor = texture(uAOMap, vUV).r;"),r.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;"),r.push("vec4 fragColor;"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" fragColor = vec4(outgoingLight.rgb * ambient * aoFactor, opacity);")):r.push(" fragColor = vec4(outgoingLight.rgb * aoFactor, opacity);"),t&&r.push("fragColor = linearToGamma(fragColor, gammaFactor);"),r.push("outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}class $i extends Si{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick flat normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching pick flat normals 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("in vec4 vWorldPosition;"),s){n.push("in float vFlags;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),n.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),n.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),n.push(" outColor = vec4((worldNormal * 0.5) + 0.5, 1.0);"),n.push("}"),n}}class ea extends Si{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching color texture vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._lightsState,n=e._sectionPlanesState,i=n.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Triangles batching color texture fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),i){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(let e=0,t=n.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}this._addMatricesUniformBlockLines(a),a.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(a.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&a.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&a.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(a.push("uniform vec3 lightPos"+e+";"),a.push("uniform vec3 lightDir"+e+";")))}if(a.push("in vec4 vViewPosition;"),a.push("in vec4 vColor;"),a.push("in vec2 vUV;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=n.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { "),a.push(" discard;"),a.push(" }"),a.push("}")}a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?a.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):a.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}a.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),a.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return a.push("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),t?a.push("vec4 colorTexel = color * sRGBToLinear(texture(uColorMap, vUV));"):a.push("vec4 colorTexel = color * texture(uColorMap, vUV);"),a.push("float opacity = color.a;"),this._withSAO?(a.push(" float viewportWidth = uSAOParams[0];"),a.push(" float viewportHeight = uSAOParams[1];"),a.push(" float blendCutoff = uSAOParams[2];"),a.push(" float blendFactor = uSAOParams[3];"),a.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),a.push(" outColor = vec4(colorTexel.rgb * ambient, opacity);")):a.push(" outColor = vec4(colorTexel.rgb, opacity);"),t&&a.push("outColor = linearToGamma(outColor, gammaFactor);"),e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}}class ta{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._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)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Gi(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Gi(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Vi(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Vi(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new ea(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new ea(this._scene,!0)),this._colorTextureRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new Zi(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Zi(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new ji(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Xi(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new qi(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new ki(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Qi(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Wi(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Ki(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new $i(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new zi(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Yi(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Ji(this._scene)),this._shadowRenderer}_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._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()}}const sa={};class na{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const ia=h.mat4(),aa=h.mat4();function ra(e,t,s){const n=e.length,i=new Uint16Array(n),a=t[0],r=t[1],l=t[2],o=t[3]-a,c=t[4]-r,u=t[5]-l,p=65525,A=p/o,d=p/c,f=p/u,I=e=>e>=0?e:0;for(let t=0;t<n;t+=3)i[t+0]=Math.floor(I(e[t+0]-a)*A),i[t+1]=Math.floor(I(e[t+1]-r)*d),i[t+2]=Math.floor(I(e[t+2]-l)*f);return h.identityMat4(ia),h.translationMat4v(t,ia),h.identityMat4(aa),h.scalingMat4v([o/p,c/p,u/p],aa),h.mulMat4(ia,aa,s),i}function la(e,t){const s=e[0],n=e[1],i=e[2],a=e[3]-s,r=e[4]-n,l=e[5]-i,o=65525;return h.identityMat4(ia),h.translationMat4v(e,ia),h.identityMat4(aa),h.scalingMat4v([a/o,r/o,l/o],aa),h.mulMat4(ia,aa,t),t}function oa(e,t,s){let n=e[0]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2])),i=e[1]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2]));if(e[2]<0){let e=n,t=i;e=(1-Math.abs(i))*(n>=0?1:-1),t=(1-Math.abs(n))*(i>=0?1:-1),n=e,i=t}return new Int8Array([Math[t](127.5*n+(n<0?-1:0)),Math[s](127.5*i+(i<0?-1:0))])}function ca(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const n=1-Math.abs(t)-Math.abs(s);n<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const i=Math.sqrt(t*t+s*s+n*n);return[t/i,s/i,n/i]}const ua=h.vec3();class ha{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,s){const n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=t._state.origin;let c=a.eye;e.snapPickOrigin[0]=o[0],e.snapPickOrigin[1]=o[1],e.snapPickOrigin[2]=o[2];const u=t.aabb,p=[h.safeInv(u[3]-u[0])*h.MAX_INT,h.safeInv(u[4]-u[1])*h.MAX_INT,h.safeInv(u[5]-u[2])*h.MAX_INT];if(e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),e.pickViewMatrix&&(c=e.pickOrigin||c);const A=[c[0]-o[0],c[1]-o[1],c[2]-o[2]];r.uniform3fv(this._uCameraEyeRtc,A),r.uniform2fv(this.uVectorA,e.snapVectorA),r.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),r.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),r.uniform3fv(this._uCoordinateScaler,p),r.uniform1i(this._uRenderPass,s),r.uniform1i(this._uPickInvisible,e.pickInvisible),r.uniform1i(this._uSolid,t.solid);const d=e.pickViewMatrix||a.viewMatrix,f=o?B(d,o):d;if(r.uniformMatrix4fv(this._uWorldMatrix,!1,n.worldMatrix),r.uniformMatrix4fv(this._uViewMatrix,!1,f),r.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}const I=i._sectionPlanesState.sectionPlanes.length;if(I>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,a=n.renderFlags;for(let t=0;t<I;t++){const n=this._uSectionPlanes[t];if(n){const i=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,i?1:0),i){const s=e[t];if(o){const e=N(s.dist,s.dir,o,ua);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}r.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(l.positionsBuf),this._aOffset&&this._aOffset.bindArrayBuffer(l.offsetsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(l.flagsBuf),l.indicesBuf.bind(),r.drawElements(r.TRIANGLES,l.indicesBuf.numItems,l.indicesBuf.itemType,0),l.indicesBuf.unbind()}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new we(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uSolid=s.getLocation("solid"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aFlags=s.getAttribute("flags"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this.uVectorA=s.getLocation("snapVectorA"),this.uInverseVectorAB=s.getLocation("snapInvVectorAB"),this._uLayerNumber=s.getLocation("layerNumber"),this._uCoordinateScaler=s.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),s.push("uniform bool solid;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.z += 0.0001;"),s.push("clipPos.xyzw *= tmp;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// VBO SnapBatchingDepthBufInitRenderer 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 int layerNumber;"),n.push("uniform vec3 coordinateScaler;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in highp vec3 relativeToOriginPosition;"),n.push("out highp ivec4 outCoords;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const pa=h.vec3();class Aa{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){const n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=t._state.origin;e.snapPickOrigin[0]=o[0],e.snapPickOrigin[1]=o[1],e.snapPickOrigin[2]=o[2];const c=t.aabb,u=[h.safeInv(c[3]-c[0])*h.MAX_INT,h.safeInv(c[4]-c[1])*h.MAX_INT,h.safeInv(c[5]-c[2])*h.MAX_INT];if(e.snapPickCoordinateScale[0]=h.safeInv(u[0]),e.snapPickCoordinateScale[1]=h.safeInv(u[1]),e.snapPickCoordinateScale[2]=h.safeInv(u[2]),!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());let p=a.eye;e.pickViewMatrix&&(p=e.pickOrigin||p);const A=[p[0]-o[0],p[1]-o[1],p[2]-o[2]];r.uniform3fv(this._uCameraEyeRtc,A),r.uniform2fv(this.uVectorA,e.snapVectorA),r.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),r.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),r.uniform3fv(this._uCoordinateScaler,u),r.uniform1i(this._uRenderPass,s),r.uniform1i(this._uPickInvisible,e.pickInvisible);const d=e.pickViewMatrix||a.viewMatrix,f=o?B(d,o):d;if(r.uniformMatrix4fv(this._uWorldMatrix,!1,n.worldMatrix),r.uniformMatrix4fv(this._uViewMatrix,!1,f),r.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}const I=i._sectionPlanesState.sectionPlanes.length;if(I>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,a=n.renderFlags;for(let t=0;t<I;t++){const n=this._uSectionPlanes[t];if(n){const i=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,i?1:0),i){const s=e[t];if(o){const e=N(s.dist,s.dir,o,pa);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}r.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(l.positionsBuf),this._aOffset&&this._aOffset.bindArrayBuffer(l.offsetsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(l.flagsBuf),"edge"===e.snapMode?(l.edgeIndicesBuf.bind(),r.drawElements(r.LINES,l.edgeIndicesBuf.numItems,l.edgeIndicesBuf.itemType,0),l.edgeIndicesBuf.unbind()):r.drawArrays(r.POINTS,0,l.positionsBuf.numItems)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new we(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aFlags=s.getAttribute("flags"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this.uVectorA=s.getLocation("snapVectorA"),this.uInverseVectorAB=s.getLocation("snapInvVectorAB"),this._uLayerNumber=s.getLocation("layerNumber"),this._uCoordinateScaler=s.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0;e.pointsMaterial._state;const s=[];return s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// SnapBatchingDepthRenderer 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 int layerNumber;"),n.push("uniform vec3 coordinateScaler;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in highp vec3 relativeToOriginPosition;"),n.push("out highp ivec4 outCoords;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class da{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new ha(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new Aa(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const fa={};const Ia=h.mat4(),ya=h.mat4(),ma=h.vec4([0,0,0,1]),va=h.vec4([0,0,0,1]),wa=h.vec4([0,0,0,1]),ga=h.OBB3(),Ta=h.vec3(),Ea=h.vec3(),ba=h.vec3(),Da=h.vec3(),Pa=h.vec3(),Ra=h.vec3(),Ca=h.vec3();class _a{constructor(e){console.log("Creating TrianglesBatchingLayer"),this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=sa[t];return s||(s=new ta(e),sa[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete sa[t],s._destroy()}))),s}(e.model.scene),this._snapBatchingRenderers=function(e){const t=e.id;let s=fa[t];return s||(s=new da(e),fa[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete fa[t],s._destroy()}))),s}(e.model.scene),this._buffer=new na(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ve({origin:h.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:e.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=h.collapseAABB3(),this._portions=[],this._numVerts=0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=h.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=h.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.aabb=h.collapseAABB3(),this.solid=!!e.solid}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t<this._buffer.maxIndices}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,n=e.normals,i=e.normalsCompressed,a=e.uv,r=e.uvCompressed,l=e.colors,o=e.colorsCompressed,c=e.indices,u=e.edgeIndices,p=e.color,A=e.metallic,d=e.roughness,f=e.opacity,I=e.meshMatrix,y=e.sceneModelMatrix,m=e.worldAABB,v=e.pickColor,w=this.model.scene,g=this._buffer,T=g.positions.length/3;let E;if(this._state.positionsDecodeMatrix){if(!s)throw"positionsCompressed expected";E=s.length/3;for(let e=0,t=s.length;e<t;e++)g.positions.push(s[e]);const e=wt.getPositionsBounds(s),t=wt.decompressPosition(e.min,this._state.positionsDecodeMatrix,[]),n=wt.decompressPosition(e.max,this._state.positionsDecodeMatrix,[]);m[0]=t[0],m[1]=t[1],m[2]=t[2],m[3]=n[0],m[4]=n[1],m[5]=n[2],y&&(h.AABB3ToOBB3(m,ga),h.transformOBB3(y,ga),h.OBB3ToAABB3(ga,m))}else{if(!t)throw"positions expected";E=t.length/3;const e=t.length,s=g.positions.length;for(let e=0,s=t.length;e<s;e++)g.positions.push(t[e]);if(I)for(let t=s,n=s+e;t<n;t+=3)ma[0]=g.positions[t+0],ma[1]=g.positions[t+1],ma[2]=g.positions[t+2],h.transformPoint4(I,ma,va),g.positions[t+0]=va[0],g.positions[t+1]=va[1],g.positions[t+2]=va[2],h.expandAABB3Point3(this._modelAABB,va),y?(h.transformPoint4(y,va,wa),h.expandAABB3Point3(m,wa)):h.expandAABB3Point3(m,va);else for(let t=s,n=s+e;t<n;t+=3)ma[0]=g.positions[t+0],ma[1]=g.positions[t+1],ma[2]=g.positions[t+2],h.expandAABB3Point3(this._modelAABB,ma),y?(h.transformPoint4(y,ma,va),h.expandAABB3Point3(m,va)):h.expandAABB3Point3(m,ma)}if(this._state.origin){const e=this._state.origin;m[0]+=e[0],m[1]+=e[1],m[2]+=e[2],m[3]+=e[0],m[4]+=e[1],m[5]+=e[2]}if(h.expandAABB3(this.aabb,m),i&&i.length>0)for(let e=0,t=i.length;e<t;e++)g.normals.push(i[e]);else if(n&&n.length>0){const e=Ia;I?h.inverseMat4(h.transposeMat4(I,ya),e):h.identityMat4(e,e),function(e,t,s,n,i){function a(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let r,l,o,c,u,p,A=new Float32Array([0,0,0,0]),d=new Float32Array([0,0,0,0]);for(p=0;p<s;p+=3)A[0]=t[p],A[1]=t[p+1],A[2]=t[p+2],h.transformVec3(e,A,d),h.normalizeVec3(d,d),o=r=oa(d,"floor","floor"),l=ca(r),c=u=a(d,l),r=oa(d,"ceil","floor"),l=ca(r),c=a(d,l),c>u&&(o=r,u=c),r=oa(d,"floor","ceil"),l=ca(r),c=a(d,l),c>u&&(o=r,u=c),r=oa(d,"ceil","ceil"),l=ca(r),c=a(d,l),c>u&&(o=r,u=c),n[i+p+0]=o[0],n[i+p+1]=o[1],n[i+p+2]=0}(e,n,n.length,g.normals,g.normals.length)}if(l)for(let e=0,t=l.length;e<t;e+=3)g.colors.push(255*l[e]),g.colors.push(255*l[e+1]),g.colors.push(255*l[e+2]),g.colors.push(255);else if(o)for(let e=0,t=l.length;e<t;e+=3)g.colors.push(l[e]),g.colors.push(l[e+1]),g.colors.push(l[e+2]),g.colors.push(255);else if(p){const e=p[0],t=p[1],s=p[2],n=f;for(let i=0;i<E;i++)g.colors.push(e),g.colors.push(t),g.colors.push(s),g.colors.push(n)}const b=null!=A?A:0,D=null!=d?d:255;for(let e=0;e<E;e++)g.metallicRoughness.push(b),g.metallicRoughness.push(D);if(a&&a.length>0)for(let e=0,t=a.length;e<t;e++)g.uv.push(a[e]);else if(r&&r.length>0)for(let e=0,t=r.length;e<t;e++)g.uv.push(r[e]);for(let e=0,t=c.length;e<t;e++)g.indices.push(T+c[e]);if(u)for(let e=0,t=u.length;e<t;e++)g.edgeIndices.push(T+u[e]);{const e=g.pickColors.length;for(let t=e,s=e+4*E;t<s;t+=4)g.pickColors.push(v[0]),g.pickColors.push(v[1]),g.pickColors.push(v[2]),g.pickColors.push(v[3])}if(w.entityOffsetsEnabled)for(let e=0;e<E;e++)g.offsets.push(0),g.offsets.push(0),g.offsets.push(0);const P=this._portions.length,R={vertsBaseIndex:T,numVerts:E,indicesBaseIndex:g.indices.length-c.length,numIndices:c.length};return w.pickSurfacePrecisionEnabled&&(R.indices=c,w.entityOffsetsEnabled&&(R.offset=new Float32Array(3))),this._portions.push(R),this._numPortions++,this.model.numPortions++,this._numVerts+=R.numVerts,P}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,s=this._buffer;if(s.positions.length>0){const n=this._state.positionsDecodeMatrix?new Uint16Array(s.positions):ra(s.positions,this._modelAABB,this._state.positionsDecodeMatrix=h.mat4());if(e.positionsBuf=new ge(t,t.ARRAY_BUFFER,n,n.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e<t;e++){const t=this._portions[e],s=3*t.vertsBaseIndex,i=s+3*t.numVerts;t.quantizedPositions=n.slice(s,i)}}if(s.normals.length>0){const n=new Int8Array(s.normals);let i=!0;e.normalsBuf=new ge(t,t.ARRAY_BUFFER,n,s.normals.length,3,t.STATIC_DRAW,i)}if(s.colors.length>0){const n=new Uint8Array(s.colors);let i=!1;e.colorsBuf=new ge(t,t.ARRAY_BUFFER,n,s.colors.length,4,t.DYNAMIC_DRAW,i)}if(s.uv.length>0)if(e.uvDecodeMatrix){let n=!1;e.uvBuf=new ge(t,t.ARRAY_BUFFER,s.uv,s.uv.length,2,t.STATIC_DRAW,n)}else{const n=wt.getUVBounds(s.uv),i=wt.compressUVs(s.uv,n.min,n.max),a=i.quantized;let r=!1;e.uvDecodeMatrix=h.mat3(i.decodeMatrix),e.uvBuf=new ge(t,t.ARRAY_BUFFER,a,a.length,2,t.STATIC_DRAW,r)}if(s.metallicRoughness.length>0){const n=new Uint8Array(s.metallicRoughness);let i=!1;e.metallicRoughnessBuf=new ge(t,t.ARRAY_BUFFER,n,s.metallicRoughness.length,2,t.STATIC_DRAW,i)}if(s.positions.length>0){const n=s.positions.length/3,i=new Float32Array(n),a=!1;e.flagsBuf=new ge(t,t.ARRAY_BUFFER,i,i.length,1,t.DYNAMIC_DRAW,a)}if(s.pickColors.length>0){const n=new Uint8Array(s.pickColors);let i=!1;e.pickColorsBuf=new ge(t,t.ARRAY_BUFFER,n,s.pickColors.length,4,t.STATIC_DRAW,i)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const n=new Float32Array(s.offsets);e.offsetsBuf=new ge(t,t.ARRAY_BUFFER,n,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const n=new Uint32Array(s.indices);e.indicesBuf=new ge(t,t.ELEMENT_ARRAY_BUFFER,n,s.indices.length,1,t.STATIC_DRAW)}if(s.edgeIndices.length>0){const n=new Uint32Array(s.edgeIndices);e.edgeIndicesBuf=new ge(t,t.ELEMENT_ARRAY_BUFFER,n,s.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,s){t&x&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&U&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&F&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&M&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&L&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&x?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&U?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&F?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=e,n=this._portions[s],i=4*n.vertsBaseIndex,a=4*n.numVerts,r=this._scratchMemory.getUInt8Array(a),l=t[0],o=t[1],c=t[2],u=t[3];for(let e=0;e<a;e+=4)r[e+0]=l,r[e+1]=o,r[e+2]=c,r[e+3]=u;this._state.colorsBuf&&this._state.colorsBuf.setData(r,i,a)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s,n=!1){if(!this._finalized)throw"Not finalized";const i=e,a=this._portions[i],r=a.vertsBaseIndex,l=a.numVerts,o=!!(t&x),c=!!(t&U),u=!!(t&G),h=!!(t&V),p=!!(t&j),A=!!(t&M),d=!!(t&L);let f,I;f=!o||d||c||u&&!this.model.scene.highlightMaterial.glowThrough||h&&!this.model.scene.selectedMaterial.glowThrough?Pi.NOT_RENDERED:s?Pi.COLOR_TRANSPARENT:Pi.COLOR_OPAQUE,I=!o||d?Pi.NOT_RENDERED:h?Pi.SILHOUETTE_SELECTED:u?Pi.SILHOUETTE_HIGHLIGHTED:c?Pi.SILHOUETTE_XRAYED:Pi.NOT_RENDERED;let y=0;y=!o||d?Pi.NOT_RENDERED:h?Pi.EDGES_SELECTED:u?Pi.EDGES_HIGHLIGHTED:c?Pi.EDGES_XRAYED:p?s?Pi.EDGES_COLOR_TRANSPARENT:Pi.EDGES_COLOR_OPAQUE:Pi.NOT_RENDERED;let m=o&&!d&&A?Pi.PICK:Pi.NOT_RENDERED;const v=t&F?1:0;if(n){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(let e=r,t=r+l;e<t;e++){let t=0;t|=f,t|=I<<4,t|=y<<8,t|=m<<12,t|=v<<16,this._deferredFlagValues[e]=t}}else if(this._state.flagsBuf){const e=this._scratchMemory.getFloat32Array(l);for(let t=0;t<l;t++){let s=0;s|=f,s|=I<<4,s|=y<<8,s|=m<<12,s|=v<<16,e[t]=s}this._state.flagsBuf.setData(e,r,l)}}_setDeferredFlags(){this._deferredFlagValues&&(this._state.flagsBuf.setData(this._deferredFlagValues),this._deferredFlagValues=null)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const s=e,n=this._portions[s],i=3*n.vertsBaseIndex,a=3*n.numVerts,r=this._scratchMemory.getFloat32Array(a),l=t[0],o=t[1],c=t[2];for(let e=0;e<a;e+=3)r[e+0]=l,r[e+1]=o,r[e+2]=c;this._state.offsetsBuf&&this._state.offsetsBuf.setData(r,i,a),this.model.scene.pickSurfacePrecisionEnabled&&(n.offset[0]=t[0],n.offset[1]=t[1],n.offset[2]=t[2])}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return;const s=this._state,n=this._portions[e];if(!n)return void this.model.error("portion not found: "+e);const i=n.quantizedPositions,a=s.origin,r=n.offset,l=a[0]+r[0],o=a[1]+r[1],c=a[2]+r[2],u=ma;for(let e=0,n=i.length;e<n;e+=3)u[0]=i[e],u[1]=i[e+1],u[2]=i[e+2],u[3]=1,h.decompressPosition(u,s.positionsDecodeMatrix),h.transformPoint4(this.model.worldMatrix,u),u[0]+=l,u[1]+=o,u[2]+=c,t(u)}getElementsCountAndOffset(e){let t=null,s=null;const n=this._portions[e];return n&&(t=n.numIndices,s=n.indicesBaseIndex),{count:t,offset:s}}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._batchingRenderers.pbrRendererWithSAO&&this._batchingRenderers.pbrRendererWithSAO.drawLayer(t,this,Pi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._batchingRenderers.colorTextureRendererWithSAO&&this._batchingRenderers.colorTextureRendererWithSAO.drawLayer(t,this,Pi.COLOR_OPAQUE):this._state.normalsBuf?this._batchingRenderers.colorRendererWithSAO&&this._batchingRenderers.colorRendererWithSAO.drawLayer(t,this,Pi.COLOR_OPAQUE):this._batchingRenderers.flatColorRendererWithSAO&&this._batchingRenderers.flatColorRendererWithSAO.drawLayer(t,this,Pi.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._batchingRenderers.pbrRenderer&&this._batchingRenderers.pbrRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._batchingRenderers.colorTextureRenderer&&this._batchingRenderers.colorTextureRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE):this._state.normalsBuf?this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE):this._batchingRenderers.flatColorRenderer&&this._batchingRenderers.flatColorRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const s=this.model.backfaces||!this.solid||e.sectioned;if(t.backfaces!==s){const e=t.gl;s?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=s}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._batchingRenderers.pbrRenderer&&this._batchingRenderers.pbrRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._batchingRenderers.colorTextureRenderer&&this._batchingRenderers.colorTextureRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT):this._state.normalsBuf?this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT):this._batchingRenderers.flatColorRenderer&&this._batchingRenderers.flatColorRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.depthRenderer&&this._batchingRenderers.depthRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.normalsRenderer&&this._batchingRenderers.normalsRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._batchingRenderers.edgesColorRenderer&&this._batchingRenderers.edgesColorRenderer.drawLayer(t,this,Pi.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._batchingRenderers.edgesColorRenderer&&this._batchingRenderers.edgesColorRenderer.drawLayer(t,this,Pi.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(t,this,Pi.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(t,this,Pi.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(t,this,Pi.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.occlusionRenderer&&this._batchingRenderers.occlusionRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.shadowRenderer&&this._batchingRenderers.shadowRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE))}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.pickMeshRenderer&&this._batchingRenderers.pickMeshRenderer.drawLayer(t,this,Pi.PICK))}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.pickDepthRenderer&&this._batchingRenderers.pickDepthRenderer.drawLayer(t,this,Pi.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.pickNormalsFlatRenderer&&this._batchingRenderers.pickNormalsFlatRenderer.drawLayer(t,this,Pi.PICK))}drawSnapInitDepthBuf(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapBatchingRenderers.snapDepthBufInitRenderer&&this._snapBatchingRenderers.snapDepthBufInitRenderer.drawLayer(t,this,Pi.PICK))}drawSnapDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapBatchingRenderers.snapDepthRenderer&&this._snapBatchingRenderers.snapDepthRenderer.drawLayer(t,this,Pi.PICK))}precisionRayPickSurface(e,t,s,n,i){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const a=this._state,r=this._portions[e];if(!r)return this.model.error("portion not found: "+e),!1;const l=r.quantizedPositions,o=r.indices,c=a.origin,u=r.offset,p=Ta,A=Ea;p.set(c?h.subVec3(t,c,ba):t),A.set(s),u&&h.subVec3(p,u),h.transformRay(this.model.worldNormalMatrix,p,A,p,A);const d=Da,f=Pa,I=Ra;let y=!1,m=0;const v=Ca;for(let e=0,s=o.length;e<s;e+=3){const s=3*o[e],r=3*o[e+1],w=3*o[e+2];if(d[0]=l[s],d[1]=l[s+1],d[2]=l[s+2],f[0]=l[r],f[1]=l[r+1],f[2]=l[r+2],I[0]=l[w],I[1]=l[w+1],I[2]=l[w+2],h.decompressPosition(d,a.positionsDecodeMatrix),h.decompressPosition(f,a.positionsDecodeMatrix),h.decompressPosition(I,a.positionsDecodeMatrix),h.rayTriangleIntersect(p,A,d,f,I,v)){h.transformPoint3(this.model.worldMatrix,v,v),u&&h.addVec3(v,u),c&&h.addVec3(v,c);const e=Math.abs(h.lenVec3(h.subVec3(v,t,[])));(!y||e>m)&&(m=e,n.set(v),i&&h.triangleNormal(d,f,I,i),y=!0)}}return y&&i&&(h.transformVec3(this.model.worldNormalMatrix,i,i),h.normalizeVec3(i)),y}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}class Ba extends xi{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0;let i,a,r;const l=[];for(l.push("#version 300 es"),l.push("// Instancing geometry drawing vertex shader"),l.push("uniform int renderPass;"),l.push("in vec3 position;"),l.push("in vec2 normal;"),l.push("in vec4 color;"),l.push("in float flags;"),e.entityOffsetsEnabled&&l.push("in vec3 offset;"),l.push("in vec4 modelMatrixCol0;"),l.push("in vec4 modelMatrixCol1;"),l.push("in vec4 modelMatrixCol2;"),l.push("in vec4 modelNormalMatrixCol0;"),l.push("in vec4 modelNormalMatrixCol1;"),l.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(l,!0),e.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;")),l.push("uniform vec4 lightAmbient;"),i=0,a=s.lights.length;i<a;i++)r=s.lights[i],"ambient"!==r.type&&(l.push("uniform vec4 lightColor"+i+";"),"dir"===r.type&&l.push("uniform vec3 lightDir"+i+";"),"point"===r.type&&l.push("uniform vec3 lightPos"+i+";"),"spot"===r.type&&(l.push("uniform vec3 lightPos"+i+";"),l.push("uniform vec3 lightDir"+i+";")));for(l.push("vec3 octDecode(vec2 oct) {"),l.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),l.push(" if (v.z < 0.0) {"),l.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"),n&&(l.push("out vec4 vWorldPosition;"),l.push("out float vFlags;")),l.push("out vec4 vColor;"),l.push("void main(void) {"),l.push("int colorFlag = int(flags) & 0xF;"),l.push("if (colorFlag != renderPass) {"),l.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),l.push("} else {"),l.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),l.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&l.push(" worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix * worldPosition; "),l.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),l.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),l.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),i=0,a=s.lights.length;i<a;i++)if(r=s.lights[i],"ambient"!==r.type){if("dir"===r.type)"view"===r.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);");else if("point"===r.type)"view"===r.space?l.push("viewLightDir = -normalize(lightPos"+i+" - viewPosition.xyz);"):l.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+i+", 0.0)).xyz);");else{if("spot"!==r.type)continue;"view"===r.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);")}l.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),l.push("reflectedColor += lambertian * (lightColor"+i+".rgb * lightColor"+i+".a);")}return l.push("vec3 rgb = (vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0));"),l.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),l.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(l.push("vFragDepth = 1.0 + clipPos.w;"),l.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n&&(l.push("vWorldPosition = worldPosition;"),l.push("vFlags = flags;")),l.push("gl_Position = clipPos;"),l.push("}"),l.push("}"),l}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,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;")),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){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):n.push(" outColor = vColor;"),n.push("}"),n}}class Oa extends xi{_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.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry flat-shading drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState;let n,i;const a=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Instancing geometry flat-shading drawing 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("}")),a){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}for(this._addMatricesUniformBlockLines(r),r.push("uniform vec4 lightAmbient;"),n=0,i=s.lights.length;n<i;n++){const e=s.lights[n];"ambient"!==e.type&&(r.push("uniform vec4 lightColor"+n+";"),"dir"===e.type&&r.push("uniform vec3 lightDir"+n+";"),"point"===e.type&&r.push("uniform vec3 lightPos"+n+";"),"spot"===e.type&&(r.push("uniform vec3 lightPos"+n+";"),r.push("uniform vec3 lightDir"+n+";")))}if(r.push("in vec4 vViewPosition;"),r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),a){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }"),r.push("}")}for(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 ) );"),n=0,i=s.lights.length;n<i;n++){const e=s.lights[n];if("ambient"!==e.type){if("dir"===e.type)"view"===e.space?r.push("viewLightDir = normalize(lightDir"+n+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+n+", 0.0)).xyz);");else if("point"===e.type)"view"===e.space?r.push("viewLightDir = -normalize(lightPos"+n+" - viewPosition.xyz);"):r.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+n+", 0.0)).xyz);");else{if("spot"!==e.type)continue;"view"===e.space?r.push("viewLightDir = normalize(lightDir"+n+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+n+", 0.0)).xyz);")}r.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),r.push("reflectedColor += lambertian * (lightColor"+n+".rgb * lightColor"+n+".a);")}}return r.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" outColor = vec4(fragColor.rgb * ambient, 1.0);")):r.push(" outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}class Sa extends xi{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing fill 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class Na extends Li{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class xa extends Li{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class La extends xi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry picking vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry picking 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vPickColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vPickColor; "),n.push("}"),n}}class Ma extends xi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry depth 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 float pickZNear;"),n.push("uniform float pickZFar;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vViewPosition;"),n.push("vec4 packDepth(const in float depth) {"),n.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),n.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),n.push(" vec4 res = fract(depth * bitShift);"),n.push(" res -= res.xxyz * bitMask;"),n.push(" return res;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class Fa extends xi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec2 normal;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("in vec4 modelNormalMatrixCol0;"),s.push("in vec4 modelNormalMatrixCol1;"),s.push("in vec4 modelNormalMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),s.push(" vWorldNormal = worldNormal;"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry normals 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vWorldNormal;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),n.push("}"),n}}class Ha extends xi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing occlusion 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return n.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class Ua extends xi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry depth drawing fragment shader"),a.push("precision highp float;"),a.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("in vec2 vHighPrecisionZW;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push("if (dist > 0.0) { discard; }"),a.push("}")}return e.logarithmicDepthBufferEnabled&&a.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),a.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),a.push("}"),a}}class Ga extends xi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}class Va extends xi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}const ja={3e3:"linearToLinear",3001:"sRGBToLinear"};class ka extends xi{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0,i=t.clippingCaps,a=[];return a.push("#version 300 es"),a.push("// Instancing geometry quality drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec3 normal;"),a.push("in vec4 color;"),a.push("in vec2 uv;"),a.push("in vec2 metallicRoughness;"),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),a.push("uniform mat3 uvDecodeMatrix;"),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("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),a.push("out vec4 vViewPosition;"),a.push("out vec3 vViewNormal;"),a.push("out vec4 vColor;"),a.push("out vec2 vUV;"),a.push("out vec2 vMetallicRoughness;"),s.lightMaps.length>0&&a.push("out vec3 vWorldNormal;"),n&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;"),i&&a.push("out vec4 vClipPosition;")),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), 1.0);"),a.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),a.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(a.push("vFragDepth = 1.0 + clipPos.w;"),a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags = flags;"),i&&a.push("vClipPosition = clipPos;")),a.push("vViewPosition = viewPosition;"),a.push("vViewNormal = viewNormal;"),a.push("vColor = color;"),a.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),a.push("vMetallicRoughness = metallicRoughness;"),s.lightMaps.length>0&&a.push("vWorldNormal = worldNormal.xyz;"),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,n=e._lightsState,i=s.sectionPlanes.length>0,a=s.clippingCaps,r=[];r.push("#version 300 es"),r.push("// Instancing geometry quality drawing 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;")),r.push("uniform sampler2D uColorMap;"),r.push("uniform sampler2D uMetallicRoughMap;"),r.push("uniform sampler2D uEmissiveMap;"),r.push("uniform sampler2D uNormalMap;"),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("}")),n.reflectionMaps.length>0&&r.push("uniform samplerCube reflectionMap;"),n.lightMaps.length>0&&r.push("uniform samplerCube lightMap;"),r.push("uniform vec4 lightAmbient;");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];"ambient"!==t.type&&(r.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&r.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&r.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(r.push("uniform vec3 lightPos"+e+";"),r.push("uniform vec3 lightDir"+e+";")))}if(r.push("uniform float gammaFactor;"),r.push("vec4 linearToLinear( in vec4 value ) {"),r.push(" return value;"),r.push("}"),r.push("vec4 sRGBToLinear( in vec4 value ) {"),r.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 );"),r.push("}"),r.push("vec4 gammaToLinear( in vec4 value) {"),r.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),r.push("}"),t&&(r.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),r.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),r.push("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;"),a&&r.push("in vec4 vClipPosition;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}if(r.push("in vec4 vViewPosition;"),r.push("in vec3 vViewNormal;"),r.push("in vec4 vColor;"),r.push("in vec2 vUV;"),r.push("in vec2 vMetallicRoughness;"),n.lightMaps.length>0&&r.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(r,!0),r.push("#define PI 3.14159265359"),r.push("#define RECIPROCAL_PI 0.31830988618"),r.push("#define RECIPROCAL_PI2 0.15915494"),r.push("#define EPSILON 1e-6"),r.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),r.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),r.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),r.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),r.push(" return normalize(surf_norm );"),r.push(" }"),r.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),r.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),r.push(" vec2 st0 = dFdx( uv.st );"),r.push(" vec2 st1 = dFdy( uv.st );"),r.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),r.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),r.push(" vec3 N = normalize( surf_norm );"),r.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),r.push(" mat3 tsn = mat3( S, T, N );"),r.push(" return normalize( tsn * mapN );"),r.push("}"),r.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),r.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),r.push("}"),r.push("struct IncidentLight {"),r.push(" vec3 color;"),r.push(" vec3 direction;"),r.push("};"),r.push("struct ReflectedLight {"),r.push(" vec3 diffuse;"),r.push(" vec3 specular;"),r.push("};"),r.push("struct Geometry {"),r.push(" vec3 position;"),r.push(" vec3 viewNormal;"),r.push(" vec3 worldNormal;"),r.push(" vec3 viewEyeDir;"),r.push("};"),r.push("struct Material {"),r.push(" vec3 diffuseColor;"),r.push(" float specularRoughness;"),r.push(" vec3 specularColor;"),r.push(" float shine;"),r.push("};"),r.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),r.push(" float r = ggxRoughness + 0.0001;"),r.push(" return (2.0 / (r * r) - 2.0);"),r.push("}"),r.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),r.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),r.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),r.push("}"),n.reflectionMaps.length>0&&(r.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),r.push(" vec3 envMapColor = "+ja[n.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),r.push(" return envMapColor;"),r.push("}")),r.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),r.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),r.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),r.push("}"),r.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" return 1.0 / ( gl * gv );"),r.push("}"),r.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" return 0.5 / max( gv + gl, EPSILON );"),r.push("}"),r.push("float D_GGX(const in float alpha, const in float dotNH) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),r.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float alpha = ( roughness * roughness );"),r.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),r.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),r.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),r.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),r.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),r.push(" vec3 F = F_Schlick( specularColor, dotLH );"),r.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),r.push(" float D = D_GGX( alpha, dotNH );"),r.push(" return F * (G * D);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),r.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),r.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),r.push(" vec4 r = roughness * c0 + c1;"),r.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),r.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),r.push(" return specularColor * AB.x + AB.y;"),r.push("}"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&(r.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.lightMaps.length>0&&(r.push(" vec3 irradiance = "+ja[n.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),r.push(" irradiance *= PI;"),r.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),n.reflectionMaps.length>0&&(r.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),r.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),r.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),r.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),r.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),r.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),r.push("}")),r.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),r.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),r.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),r.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");a?(r.push(" if (dist > (0.002 * vClipPosition.w)) {"),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" return;"),r.push("}")):(r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }")),r.push("}")}r.push("IncidentLight light;"),r.push("Material material;"),r.push("Geometry geometry;"),r.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),r.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),r.push("float opacity = float(vColor.a) / 255.0;"),r.push("vec3 baseColor = rgb;"),r.push("float specularF0 = 1.0;"),r.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),r.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),r.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),r.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),r.push("baseColor *= colorTexel.rgb;"),r.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),r.push("metallic *= metalRoughTexel.b;"),r.push("roughness *= metalRoughTexel.g;"),r.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),r.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),r.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),r.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),r.push("geometry.position = vViewPosition.xyz;"),r.push("geometry.viewNormal = -normalize(viewNormal);"),r.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),n.lightMaps.length>0&&r.push("geometry.worldNormal = normalize(vWorldNormal);"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&r.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?r.push("light.direction = normalize(lightPos"+e+" - vViewPosition.xyz);"):r.push("light.direction = normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}r.push("light.color = lightColor"+e+".rgb * lightColor"+e+".a;"),r.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return r.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;"),r.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;"),r.push("vec4 fragColor;"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" fragColor = vec4(outgoingLight.rgb * ambient, opacity);")):r.push(" fragColor = vec4(outgoingLight.rgb, opacity);"),t&&r.push("fragColor = linearToGamma(fragColor, gammaFactor);"),r.push("outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}class Qa extends xi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in 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),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&s.push("out float vFlags;"),s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&s.push("vFlags = flags;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry normals 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("in vec4 vWorldPosition;"),s){n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vWorldNormal;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),n.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),n.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),n.push(" outColor = vec4((worldNormal * 0.5) + 0.5, 1.0);"),n.push("}"),n}}class Wa extends xi{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,n=e._lightsState;let i,a;const r=s.sectionPlanes.length>0,l=[];if(l.push("#version 300 es"),l.push("// Instancing geometry drawing fragment shader"),l.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),l.push("precision highp float;"),l.push("precision highp int;"),l.push("#else"),l.push("precision mediump float;"),l.push("precision mediump int;"),l.push("#endif"),e.logarithmicDepthBufferEnabled&&(l.push("in float isPerspective;"),l.push("uniform float logDepthBufFC;"),l.push("in float vFragDepth;")),l.push("uniform sampler2D uColorMap;"),this._withSAO&&(l.push("uniform sampler2D uOcclusionTexture;"),l.push("uniform vec4 uSAOParams;"),l.push("const float packUpscale = 256. / 255.;"),l.push("const float unpackDownScale = 255. / 256.;"),l.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),l.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),l.push("float unpackRGBToFloat( const in vec4 v ) {"),l.push(" return dot( v, unPackFactors );"),l.push("}")),l.push("uniform float gammaFactor;"),l.push("vec4 linearToLinear( in vec4 value ) {"),l.push(" return value;"),l.push("}"),l.push("vec4 sRGBToLinear( in vec4 value ) {"),l.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 );"),l.push("}"),l.push("vec4 gammaToLinear( in vec4 value) {"),l.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),l.push("}"),t&&(l.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),l.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),l.push("}")),r){l.push("in vec4 vWorldPosition;"),l.push("in float vFlags;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)l.push("uniform bool sectionPlaneActive"+e+";"),l.push("uniform vec3 sectionPlanePos"+e+";"),l.push("uniform vec3 sectionPlaneDir"+e+";")}for(this._addMatricesUniformBlockLines(l),l.push("uniform vec4 lightAmbient;"),i=0,a=n.lights.length;i<a;i++){const e=n.lights[i];"ambient"!==e.type&&(l.push("uniform vec4 lightColor"+i+";"),"dir"===e.type&&l.push("uniform vec3 lightDir"+i+";"),"point"===e.type&&l.push("uniform vec3 lightPos"+i+";"),"spot"===e.type&&(l.push("uniform vec3 lightPos"+i+";"),l.push("uniform vec3 lightDir"+i+";")))}if(l.push("in vec4 vViewPosition;"),l.push("in vec4 vColor;"),l.push("in vec2 vUV;"),l.push("out vec4 outColor;"),l.push("void main(void) {"),r){l.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),l.push(" if (clippable) {"),l.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)l.push("if (sectionPlaneActive"+e+") {"),l.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),l.push("}");l.push(" if (dist > 0.0) { "),l.push(" discard;"),l.push(" }"),l.push("}")}for(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;"),l.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),l.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),l.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),i=0,a=n.lights.length;i<a;i++){const e=n.lights[i];if("ambient"!==e.type){if("dir"===e.type)"view"===e.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);");else if("point"===e.type)"view"===e.space?l.push("viewLightDir = -normalize(lightPos"+i+" - viewPosition.xyz);"):l.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+i+", 0.0)).xyz);");else{if("spot"!==e.type)continue;"view"===e.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);")}l.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),l.push("reflectedColor += lambertian * (lightColor"+i+".rgb * lightColor"+i+".a);")}}return l.push("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),t?l.push("vec4 colorTexel = color * sRGBToLinear(texture(uColorMap, vUV));"):l.push("vec4 colorTexel = color * texture(uColorMap, vUV);"),l.push("float opacity = color.a;"),this._withSAO?(l.push(" float viewportWidth = uSAOParams[0];"),l.push(" float viewportHeight = uSAOParams[1];"),l.push(" float blendCutoff = uSAOParams[2];"),l.push(" float blendFactor = uSAOParams[3];"),l.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),l.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),l.push(" outColor = vec4(vColor.rgb * colorTexel.rgb * ambient, opacity);")):l.push(" outColor = vec4(vColor.rgb * colorTexel.rgb, opacity);"),t&&l.push("outColor = linearToGamma(outColor, gammaFactor);"),e.logarithmicDepthBufferEnabled&&l.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),l.push("}"),l}}class za{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._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=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&&!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)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Ba(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Ba(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Oa(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Oa(this._scene,!0)),this._flatColorRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new ka(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new ka(this._scene,!0)),this._pbrRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Wa(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Wa(this._scene,!0)),this._colorTextureRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Sa(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Ua(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Ga(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Na(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new xa(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new La(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Fa(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Qa(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Ma(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Ha(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Va(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.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()}}const Ka={};const Ya=h.vec3();class Xa{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const n=t.model,i=n.scene,a=i.canvas.gl,r=t._state,l=t._state.origin;e.snapPickOrigin[0]=l[0],e.snapPickOrigin[1]=l[1],e.snapPickOrigin[2]=l[2];const o=t.aabb,c=[h.safeInv(o[3]-o[0])*h.MAX_INT,h.safeInv(o[4]-o[1])*h.MAX_INT,h.safeInv(o[5]-o[2])*h.MAX_INT];if(e.snapPickCoordinateScale[0]=h.safeInv(c[0]),e.snapPickCoordinateScale[1]=h.safeInv(c[1]),e.snapPickCoordinateScale[2]=h.safeInv(c[2]),!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const u=i.camera;let p=u.eye;e.pickViewMatrix&&(p=e.pickOrigin||p);const A=[p[0]-l[0],p[1]-l[1],p[2]-l[2]];a.uniform3fv(this._uCameraEyeRtc,A),a.uniform2fv(this.uVectorA,e.snapVectorA),a.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),a.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),a.uniform3fv(this._uCoordinateScaler,c),a.uniform1i(this._uRenderPass,s),a.uniform1i(this._uPickInvisible,e.pickInvisible);const d=e.pickViewMatrix||u.viewMatrix,f=l?B(d,l):d;if(a.uniformMatrix4fv(this._uViewMatrix,!1,f),a.uniformMatrix4fv(this._uWorldMatrix,!1,n.worldMatrix),a.uniformMatrix4fv(this._uProjMatrix,!1,u.projMatrix),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,t)}const I=i._sectionPlanesState.sectionPlanes.length;if(I>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,r=n.renderFlags;for(let t=0;t<I;t++){const n=this._uSectionPlanes[t];if(n){const i=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(n.active,i?1:0),i){const s=e[t];if(l){const e=N(s.dist,s.dir,l,Ya);a.uniform3fv(n.pos,e)}else a.uniform3fv(n.pos,s.pos);a.uniform3fv(n.dir,s.dir)}}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(r.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(r.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(r.modelMatrixCol2Buf),a.vertexAttribDivisor(this._aModelMatrixCol0.location,1),a.vertexAttribDivisor(this._aModelMatrixCol1.location,1),a.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(r.positionsBuf),this._aFlags&&(this._aFlags.bindArrayBuffer(r.flagsBuf),a.vertexAttribDivisor(this._aFlags.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(r.offsetsBuf),a.vertexAttribDivisor(this._aOffset.location,1)),r.indicesBuf.bind(),a.drawElementsInstanced(a.TRIANGLES,r.indicesBuf.numItems,r.indicesBuf.itemType,0,r.numInstances),r.indicesBuf.unbind(),a.vertexAttribDivisor(this._aModelMatrixCol0.location,0),a.vertexAttribDivisor(this._aModelMatrixCol1.location,0),a.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&a.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&a.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new we(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aFlags=s.getAttribute("flags"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this.uVectorA=s.getLocation("snapVectorA"),this.uInverseVectorAB=s.getLocation("snapInvVectorAB"),this._uLayerNumber=s.getLocation("layerNumber"),this._uCoordinateScaler=s.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in 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;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.z += 0.0001;"),s.push("clipPos.xyzw *= tmp;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing pick depth 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 int layerNumber;"),n.push("uniform vec3 coordinateScaler;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in highp vec3 relativeToOriginPosition;"),n.push("out highp ivec4 outCoords;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const qa=h.vec3();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,s){const n=t.model,i=n.scene,a=i.canvas.gl,r=t._state,l=t._state.origin;e.snapPickOrigin[0]=l[0],e.snapPickOrigin[1]=l[1],e.snapPickOrigin[2]=l[2];const o=t.aabb,c=[h.safeInv(o[3]-o[0])*h.MAX_INT,h.safeInv(o[4]-o[1])*h.MAX_INT,h.safeInv(o[5]-o[2])*h.MAX_INT];if(e.snapPickCoordinateScale[0]=h.safeInv(c[0]),e.snapPickCoordinateScale[1]=h.safeInv(c[1]),e.snapPickCoordinateScale[2]=h.safeInv(c[2]),!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const u=i.camera;let p=u.eye;e.pickViewMatrix&&(p=e.pickOrigin||p);const A=[p[0]-l[0],p[1]-l[1],p[2]-l[2]];a.uniform3fv(this._uCameraEyeRtc,A),a.uniform2fv(this.uVectorA,e.snapVectorA),a.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),a.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),a.uniform3fv(this._uCoordinateScaler,c),a.uniform1i(this._uRenderPass,s),a.uniform1i(this._uPickInvisible,e.pickInvisible);const d=e.pickViewMatrix||u.viewMatrix,f=l?B(d,l):d;if(a.uniformMatrix4fv(this._uViewMatrix,!1,f),a.uniformMatrix4fv(this._uWorldMatrix,!1,n.worldMatrix),a.uniformMatrix4fv(this._uProjMatrix,!1,u.projMatrix),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,t)}const I=i._sectionPlanesState.sectionPlanes.length;if(I>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,r=n.renderFlags;for(let t=0;t<I;t++){const n=this._uSectionPlanes[t];if(n){const i=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(n.active,i?1:0),i){const s=e[t];if(l){const e=N(s.dist,s.dir,l,qa);a.uniform3fv(n.pos,e)}else a.uniform3fv(n.pos,s.pos);a.uniform3fv(n.dir,s.dir)}}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(r.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(r.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(r.modelMatrixCol2Buf),a.vertexAttribDivisor(this._aModelMatrixCol0.location,1),a.vertexAttribDivisor(this._aModelMatrixCol1.location,1),a.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(r.positionsBuf),this._aFlags.bindArrayBuffer(r.flagsBuf),a.vertexAttribDivisor(this._aFlags.location,1),this._aOffset&&(this._aOffset.bindArrayBuffer(r.offsetsBuf),a.vertexAttribDivisor(this._aOffset.location,1)),"edge"===e.snapMode?(r.edgeIndicesBuf.bind(),a.drawElementsInstanced(a.LINES,r.edgeIndicesBuf.numItems,r.edgeIndicesBuf.itemType,0,r.numInstances),r.edgeIndicesBuf.unbind()):a.drawArraysInstanced(a.POINTS,0,r.positionsBuf.numItems,r.numInstances),a.vertexAttribDivisor(this._aModelMatrixCol0.location,0),a.vertexAttribDivisor(this._aModelMatrixCol1.location,0),a.vertexAttribDivisor(this._aModelMatrixCol2.location,0),a.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&a.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new we(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aFlags=s.getAttribute("flags"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this.uVectorA=s.getLocation("snapVectorA"),this.uInverseVectorAB=s.getLocation("snapInvVectorAB"),this._uLayerNumber=s.getLocation("layerNumber"),this._uCoordinateScaler=s.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// SnapInstancingDepthRenderer 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 int layerNumber;"),n.push("uniform vec3 coordinateScaler;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in highp vec3 relativeToOriginPosition;"),n.push("out highp ivec4 outCoords;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Za{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new Xa(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new Ja(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const $a={};const er=new Uint8Array(4),tr=new Float32Array(1),sr=h.vec4([0,0,0,1]),nr=h.vec4([0,0,0,1]),ir=h.vec4([0,0,0,1]),ar=new Float32Array(3),rr=h.vec3(),lr=h.vec3(),or=h.vec3(),cr=h.vec3(),ur=h.vec3(),hr=h.vec3(),pr=h.vec3();class Ar{constructor(e){console.log("Creating TrianglesInstancingLayer"),this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._instancingRenderers=function(e){const t=e.id;let s=Ka[t];return s||(s=new za(e),Ka[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Ka[t],s._destroy()}))),s}(e.model.scene),this._snapInstancingRenderers=function(e){const t=e.id;let s=$a[t];return s||(s=new Za(e),$a[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete $a[t],s._destroy()}))),s}(e.model.scene),this._aabb=h.collapseAABB3(),this._state=new Ve({numInstances:0,obb:h.OBB3(),origin:h.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,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._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.aabb=h.collapseAABB3(),this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}createPortion(e){const t=e.color,s=e.metallic,n=e.roughness,i=null!==e.opacity&&void 0!==e.opacity?e.opacity:255,a=e.meshMatrix,r=e.sceneModelMatrix,l=e.aabb,o=e.pickColor;if(this._finalized)throw"Already finalized";const c=t[0],u=t[1],p=t[2];if(this._colors.push(c),this._colors.push(u),this._colors.push(p),this._colors.push(i),this._metallicRoughness.push(null!=s?s:0),this._metallicRoughness.push(null!=n?n:255),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(a[0]),this._modelMatrixCol0.push(a[4]),this._modelMatrixCol0.push(a[8]),this._modelMatrixCol0.push(a[12]),this._modelMatrixCol1.push(a[1]),this._modelMatrixCol1.push(a[5]),this._modelMatrixCol1.push(a[9]),this._modelMatrixCol1.push(a[13]),this._modelMatrixCol2.push(a[2]),this._modelMatrixCol2.push(a[6]),this._modelMatrixCol2.push(a[10]),this._modelMatrixCol2.push(a[14]),this._state.geometry.normals){let e=h.transposeMat4(a,h.mat4()),t=h.inverseMat4(e);this._modelNormalMatrixCol0.push(t[0]),this._modelNormalMatrixCol0.push(t[4]),this._modelNormalMatrixCol0.push(t[8]),this._modelNormalMatrixCol0.push(t[12]),this._modelNormalMatrixCol1.push(t[1]),this._modelNormalMatrixCol1.push(t[5]),this._modelNormalMatrixCol1.push(t[9]),this._modelNormalMatrixCol1.push(t[13]),this._modelNormalMatrixCol2.push(t[2]),this._modelNormalMatrixCol2.push(t[6]),this._modelNormalMatrixCol2.push(t[10]),this._modelNormalMatrixCol2.push(t[14])}this._pickColors.push(o[0]),this._pickColors.push(o[1]),this._pickColors.push(o[2]),this._pickColors.push(o[3]);const A=this._state.geometry.positionsCompressed.length,d=this._state.geometry.positionsCompressed,f=this._state.geometry.positionsDecodeMatrix;for(let e=0;e<A;e+=3)sr[0]=d[e+0],sr[1]=d[e+1],sr[2]=d[e+2],h.transformPoint4(f,sr,nr),h.transformPoint4(a,nr,sr),r?(h.transformPoint4(r,sr,ir),h.expandAABB3Point3(l,ir)):h.expandAABB3Point3(l,sr);if(this._state.origin){const e=this._state.origin;l[0]+=e[0],l[1]+=e[1],l[2]+=e[2],l[3]+=e[0],l[4]+=e[1],l[5]+=e[2]}h.expandAABB3(this.aabb,l),this._state.numInstances++;const I=this._portions.length,y={};return this.model.scene.pickSurfacePrecisionEnabled&&(y.matrix=a.slice(),y.inverseMatrix=null,y.normalMatrix=null),this._portions.push(y),this._numPortions++,this.model.numPortions++,I}finalize(){if(this._finalized)return;const e=this._state,t=e.geometry,s=e.textureSet,n=this.model.scene.canvas.gl,i=this._colors.length,a=i/4;if(i>0){let t=!1;e.colorsBuf=new ge(n,n.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,n.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let s=!1;e.metallicRoughnessBuf=new ge(n,n.ARRAY_BUFFER,t,this._metallicRoughness.length,2,n.STATIC_DRAW,s)}if(a>0){let t=!1;e.flagsBuf=new ge(n,n.ARRAY_BUFFER,new Float32Array(a),a,1,n.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new ge(n,n.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,n.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const s=!1;e.positionsBuf=new ge(n,n.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,n.STATIC_DRAW,s),e.positionsDecodeMatrix=h.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const s=new Uint8Array(t.colorsCompressed),i=!1;e.colorsBuf=new ge(n,n.ARRAY_BUFFER,s,s.length,4,n.STATIC_DRAW,i)}if(t.uvCompressed&&t.uvCompressed.length>0){const s=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new ge(n,n.ARRAY_BUFFER,s,s.length,2,n.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new ge(n,n.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,n.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new ge(n,n.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,n.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new ge(n,n.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,n.STATIC_DRAW,t),e.modelMatrixCol1Buf=new ge(n,n.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,n.STATIC_DRAW,t),e.modelMatrixCol2Buf=new ge(n,n.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,n.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new ge(n,n.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,n.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new ge(n,n.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,n.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new ge(n,n.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,n.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new ge(n,n.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,n.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&s&&s.colorTexture&&s.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!s&&!!s.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&x&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&U&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&F&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&M&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&L&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&x?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&U?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&F?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";er[0]=t[0],er[1]=t[1],er[2]=t[2],er[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(er,4*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=!!(t&x),i=!!(t&U),a=!!(t&G),r=!!(t&V),l=!!(t&j),o=!!(t&M),c=!!(t&L);let u,h;u=!n||c||i||a&&!this.model.scene.highlightMaterial.glowThrough||r&&!this.model.scene.selectedMaterial.glowThrough?Pi.NOT_RENDERED:s?Pi.COLOR_TRANSPARENT:Pi.COLOR_OPAQUE,h=!n||c?Pi.NOT_RENDERED:r?Pi.SILHOUETTE_SELECTED:a?Pi.SILHOUETTE_HIGHLIGHTED:i?Pi.SILHOUETTE_XRAYED:Pi.NOT_RENDERED;let p=0;p=!n||c?Pi.NOT_RENDERED:r?Pi.EDGES_SELECTED:a?Pi.EDGES_HIGHLIGHTED:i?Pi.EDGES_XRAYED:l?s?Pi.EDGES_COLOR_TRANSPARENT:Pi.EDGES_COLOR_OPAQUE:Pi.NOT_RENDERED;let A=0;A|=u,A|=h<<4,A|=p<<8,A|=(n&&!c&&o?Pi.PICK:Pi.NOT_RENDERED)<<12,A|=(t&F?1:0)<<16,tr[0]=A,this._state.flagsBuf&&this._state.flagsBuf.setData(tr,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(ar[0]=t[0],ar[1]=t[1],ar[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(ar,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const s=this._state,n=s.geometry,i=this._portions[e];if(!i)return void this.model.error("portion not found: "+e);const a=n.quantizedPositions,r=s.origin,l=i.offset,o=r[0]+l[0],c=r[1]+l[1],u=r[2]+l[2],p=sr,A=i.matrix,d=this.model.sceneModelMatrix,f=s.positionsDecodeMatrix;for(let e=0,s=a.length;e<s;e+=3)p[0]=a[e],p[1]=a[e+1],p[2]=a[e+2],h.decompressPosition(p,f),h.transformPoint3(A,p),h.transformPoint3(d,p),p[0]+=o,p[1]+=c,p[2]+=u,t(p)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._instancingRenderers.pbrRendererWithSAO&&this._instancingRenderers.pbrRendererWithSAO.drawLayer(t,this,Pi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._instancingRenderers.colorTextureRendererWithSAO&&this._instancingRenderers.colorTextureRendererWithSAO.drawLayer(t,this,Pi.COLOR_OPAQUE):this._state.normalsBuf?this._instancingRenderers.colorRendererWithSAO&&this._instancingRenderers.colorRendererWithSAO.drawLayer(t,this,Pi.COLOR_OPAQUE):this._instancingRenderers.flatColorRendererWithSAO&&this._instancingRenderers.flatColorRendererWithSAO.drawLayer(t,this,Pi.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._instancingRenderers.pbrRenderer&&this._instancingRenderers.pbrRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._instancingRenderers.colorTextureRenderer&&this._instancingRenderers.colorTextureRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE):this._state.normalsBuf?this._instancingRenderers.colorRenderer&&this._instancingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE):this._instancingRenderers.flatColorRenderer&&this._instancingRenderers.flatColorRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const s=this.model.backfaces||!this.solid||e.sectioned;if(t.backfaces!==s){const e=t.gl;s?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=s}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._instancingRenderers.pbrRenderer&&this._instancingRenderers.pbrRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._instancingRenderers.colorTextureRenderer&&this._instancingRenderers.colorTextureRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT):this._state.normalsBuf?this._instancingRenderers.colorRenderer&&this._instancingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT):this._instancingRenderers.flatColorRenderer&&this._instancingRenderers.flatColorRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.depthRenderer&&this._instancingRenderers.depthRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.normalsRenderer&&this._instancingRenderers.normalsRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.silhouetteRenderer&&this._instancingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.silhouetteRenderer&&this._instancingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.silhouetteRenderer&&this._instancingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._instancingRenderers.edgesColorRenderer&&this._instancingRenderers.edgesColorRenderer.drawLayer(t,this,Pi.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._instancingRenderers.edgesColorRenderer&&this._instancingRenderers.edgesColorRenderer.drawLayer(t,this,Pi.EDGES_COLOR_TRANSPARENT)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(t,this,Pi.EDGES_XRAYED)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(t,this,Pi.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(t,this,Pi.EDGES_SELECTED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.occlusionRenderer&&this._instancingRenderers.occlusionRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.shadowRenderer&&this._instancingRenderers.shadowRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE))}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.pickMeshRenderer&&this._instancingRenderers.pickMeshRenderer.drawLayer(t,this,Pi.PICK))}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.pickDepthRenderer&&this._instancingRenderers.pickDepthRenderer.drawLayer(t,this,Pi.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.pickNormalsRenderer&&this._instancingRenderers.pickNormalsRenderer.drawLayer(t,this,Pi.PICK))}drawSnapInitDepthBuf(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapInstancingRenderers.snapDepthBufInitRenderer&&this._snapInstancingRenderers.snapDepthBufInitRenderer.drawLayer(t,this,Pi.PICK))}drawSnapDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapInstancingRenderers.snapDepthRenderer&&this._snapInstancingRenderers.snapDepthRenderer.drawLayer(t,this,Pi.PICK))}precisionRayPickSurface(e,t,s,n,i){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const a=this._state.geometry,r=this._state,l=this._portions[e];if(!l)return this.model.error("portion not found: "+e),!1;l.inverseMatrix||(l.inverseMatrix=h.inverseMat4(l.matrix,h.mat4())),i&&!l.normalMatrix&&(l.normalMatrix=h.transposeMat4(l.inverseMatrix,h.mat4()));const o=a.quantizedPositions,c=a.indices,u=r.origin,p=l.offset,A=rr,d=lr;A.set(u?h.subVec3(t,u,or):t),d.set(s),p&&h.subVec3(A,p),h.transformRay(this.model.worldNormalMatrix,A,d,A,d),h.transformRay(l.inverseMatrix,A,d,A,d);const f=cr,I=ur,y=hr;let m=!1,v=0;const w=pr;for(let e=0,s=c.length;e<s;e+=3){const s=3*c[e+0],a=3*c[e+1],g=3*c[e+2];f[0]=o[s],f[1]=o[s+1],f[2]=o[s+2],I[0]=o[a],I[1]=o[a+1],I[2]=o[a+2],y[0]=o[g],y[1]=o[g+1],y[2]=o[g+2];const{positionsDecodeMatrix:T}=r.geometry;if(h.decompressPosition(f,T),h.decompressPosition(I,T),h.decompressPosition(y,T),h.rayTriangleIntersect(A,d,f,I,y,w)){h.transformPoint3(l.matrix,w,w),h.transformPoint3(this.model.worldMatrix,w,w),p&&h.addVec3(w,p),u&&h.addVec3(w,u);const e=Math.abs(h.lenVec3(h.subVec3(w,t,[])));(!m||e>v)&&(v=e,n.set(w),i&&h.triangleNormal(f,I,y,i),m=!0)}}return m&&i&&(h.transformVec3(l.normalMatrix,i,i),h.transformVec3(this.model.worldNormalMatrix,i,i),h.normalizeVec3(i)),m}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 dr extends Hi{drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Lines batching color 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return n.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class fr extends Hi{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Lines batching silhouette 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("uniform vec4 color;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = color;"),n.push("}"),n}}class Ir{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new dr(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new fr(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const yr={};class mr{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}const vr=h.vec4([0,0,0,1]),wr=h.vec4([0,0,0,1]),gr=h.vec4([0,0,0,1]),Tr=h.OBB3();class Er{constructor(e){this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=yr[t];return s||(s=new Ir(e),yr[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete yr[t],s._destroy()}))),s}(e.model.scene),this.model=e.model,this._buffer=new mr(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ve({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:h.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=h.collapseAABB3(),this._portions=[],this._numVerts=0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=h.vec3(e.origin)),this.aabb=h.collapseAABB3()}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t<this._buffer.maxIndices}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,n=e.indices,i=e.color,a=e.opacity,r=e.meshMatrix,l=e.worldMatrix,o=e.worldAABB;e.pickColor;const c=this._buffer,u=c.positions.length/3;let p;if(this._preCompressedPositionsExpected){if(!s)throw"positionsCompressed expected";p=s.length/3;for(let e=0,t=s.length;e<t;e++)c.positions.push(s[e]);const e=wt.getPositionsBounds(s),t=wt.decompressPosition(e.min,this._state.positionsDecodeMatrix,[]),n=wt.decompressPosition(e.max,this._state.positionsDecodeMatrix,[]);o[0]=t[0],o[1]=t[1],o[2]=t[2],o[3]=n[0],o[4]=n[1],o[5]=n[2],l&&(h.AABB3ToOBB3(o,Tr),h.transformOBB3(l,Tr),h.OBB3ToAABB3(Tr,o))}else{if(!t)throw"positions expected";p=t.length/3;const e=t.length,s=c.positions.length;for(let e=0,s=t.length;e<s;e++)c.positions.push(t[e]);if(r)for(let t=s,n=s+e;t<n;t+=3)vr[0]=c.positions[t+0],vr[1]=c.positions[t+1],vr[2]=c.positions[t+2],h.transformPoint4(r,vr,wr),c.positions[t+0]=wr[0],c.positions[t+1]=wr[1],c.positions[t+2]=wr[2],h.expandAABB3Point3(this._modelAABB,wr),l?(h.transformPoint4(l,wr,gr),h.expandAABB3Point3(o,gr)):h.expandAABB3Point3(o,wr);else for(let t=s,n=s+e;t<n;t+=3)vr[0]=c.positions[t+0],vr[1]=c.positions[t+1],vr[2]=c.positions[t+2],h.expandAABB3Point3(this._modelAABB,vr),l?(h.transformPoint4(l,vr,wr),h.expandAABB3Point3(o,wr)):h.expandAABB3Point3(o,vr)}if(this._state.origin){const e=this._state.origin;o[0]+=e[0],o[1]+=e[1],o[2]+=e[2],o[3]+=e[0],o[4]+=e[1],o[5]+=e[2]}if(h.expandAABB3(this.aabb,o),i){const e=i[0],t=i[1],s=i[2],n=a;for(let i=0;i<p;i++)c.colors.push(e),c.colors.push(t),c.colors.push(s),c.colors.push(n)}if(n)for(let e=0,t=n.length;e<t;e++)c.indices.push(n[e]+u);if(this.model.scene.entityOffsetsEnabled)for(let e=0;e<p;e++)c.offsets.push(0),c.offsets.push(0),c.offsets.push(0);const A=this._portions.length/2;return this._portions.push(u),this._portions.push(p),this._numPortions++,this.model.numPortions++,this._numVerts+=p,A}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,s=this._buffer;if(s.positions.length>0)if(this._preCompressedPositionsExpected){const n=new Uint16Array(s.positions);e.positionsBuf=new ge(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}else{const n=ra(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new ge(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const n=new Uint8Array(s.colors);let i=!1;e.colorsBuf=new ge(t,t.ARRAY_BUFFER,n,s.colors.length,4,t.DYNAMIC_DRAW,i)}if(s.colors.length>0){const n=s.colors.length/4,i=new Float32Array(n);let a=!1;e.flagsBuf=new ge(t,t.ARRAY_BUFFER,i,i.length,1,t.DYNAMIC_DRAW,a)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const n=new Float32Array(s.offsets);e.offsetsBuf=new ge(t,t.ARRAY_BUFFER,n,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const n=new Uint32Array(s.indices);e.indicesBuf=new ge(t,t.ELEMENT_ARRAY_BUFFER,n,s.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&x&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&U&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&F&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&M&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&L&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&x?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&U?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&F?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,n=4*this._portions[s],i=4*this._portions[s+1],a=this._scratchMemory.getUInt8Array(i),r=t[0],l=t[1],o=t[2],c=t[3];for(let e=0;e<i;e+=4)a[e+0]=r,a[e+1]=l,a[e+2]=o,a[e+3]=c;this._state.colorsBuf.setData(a,n,i)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s,n=!1){if(!this._finalized)throw"Not finalized";const i=2*e,a=this._portions[i],r=this._portions[i+1],l=!!(t&x),o=!!(t&U),c=!!(t&G),u=!!(t&V),h=!!(t&M),p=!!(t&L);let A,d;A=!l||p||o||c&&!this.model.scene.highlightMaterial.glowThrough||u&&!this.model.scene.selectedMaterial.glowThrough?Pi.NOT_RENDERED:s?Pi.COLOR_TRANSPARENT:Pi.COLOR_OPAQUE,d=!l||p?Pi.NOT_RENDERED:u?Pi.SILHOUETTE_SELECTED:c?Pi.SILHOUETTE_HIGHLIGHTED:o?Pi.SILHOUETTE_XRAYED:Pi.NOT_RENDERED;let f=l&&!p&&h?Pi.PICK:Pi.NOT_RENDERED;const I=t&F?1:0;if(n){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(let e=a,t=a+r;e<t;e++){let t=0;t|=A,t|=d<<4,t|=f<<12,t|=I<<16,this._deferredFlagValues[e]=t}}else if(this._state.flagsBuf){const e=this._scratchMemory.getFloat32Array(r);for(let t=0;t<r;t++){let s=0;s|=A,s|=d<<4,s|=f<<12,s|=I<<16,e[t]=s}this._state.flagsBuf.setData(e,a,r)}}_setDeferredFlags(){this._deferredFlagValues&&(this._state.flagsBuf.setData(this._deferredFlagValues),this._deferredFlagValues=null)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const s=2*e,n=3*this._portions[s],i=3*this._portions[s+1],a=this._scratchMemory.getFloat32Array(i),r=t[0],l=t[1],o=t[2];for(let e=0;e<i;e+=3)a[e+0]=r,a[e+1]=l,a[e+2]=o;this._state.offsetsBuf.setData(a,n,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawPickMesh(e){}drawPickDepths(e){}drawPickNormals(e){}drawOcclusion(e){}drawShadow(e){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicesBuf=null),e.destroy()}}class br extends Ui{drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 lightAmbient;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Lines instancing color fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push("if (dist > 0.0) { discard; }"),a.push("}")}return this._withSAO?(a.push(" float viewportWidth = uSAOParams[0];"),a.push(" float viewportHeight = uSAOParams[1];"),a.push(" float blendCutoff = uSAOParams[2];"),a.push(" float blendFactor = uSAOParams[3];"),a.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),a.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):a.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}}class Dr extends Ui{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 color;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Lines instancing silhouette 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("uniform vec4 color;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = color;"),n.push("}"),n}}class Pr{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new br(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Dr(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const Rr={};const Cr=new Uint8Array(4),_r=new Float32Array(1),Br=h.vec4([0,0,0,1]),Or=h.vec4([0,0,0,1]),Sr=h.vec4([0,0,0,1]),Nr=new Float32Array(3);class xr{constructor(e){this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._linesInstancingRenderers=function(e){const t=e.id;let s=Rr[t];return s||(s=new Pr(e),Rr[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Rr[t],s._destroy()}))),s}(e.model.scene),this._aabb=h.collapseAABB3(),this._state=new Ve({obb:h.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],e.origin&&(this._state.origin=h.vec3(e.origin)),this._finalized=!1,this.aabb=h.collapseAABB3()}createPortion(e){const t=e.color,s=e.opacity,n=e.meshMatrix,i=e.worldMatrix,a=e.aabb;if(this._finalized)throw"Already finalized";const r=t[0],l=t[1],o=t[2];t[3],this._colors.push(r),this._colors.push(l),this._colors.push(o),this._colors.push(s),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(n[0]),this._modelMatrixCol0.push(n[4]),this._modelMatrixCol0.push(n[8]),this._modelMatrixCol0.push(n[12]),this._modelMatrixCol1.push(n[1]),this._modelMatrixCol1.push(n[5]),this._modelMatrixCol1.push(n[9]),this._modelMatrixCol1.push(n[13]),this._modelMatrixCol2.push(n[2]),this._modelMatrixCol2.push(n[6]),this._modelMatrixCol2.push(n[10]),this._modelMatrixCol2.push(n[14]),h.collapseAABB3(a);const c=this._state.obb,u=c.length;for(let e=0;e<u;e+=4)Br[0]=c[e+0],Br[1]=c[e+1],Br[2]=c[e+2],h.transformPoint4(n,Br,Or),i?(h.transformPoint4(i,Or,Sr),h.expandAABB3Point3(a,Sr)):h.expandAABB3Point3(a,Or);if(this._state.origin){const e=this._state.origin;a[0]+=e[0],a[1]+=e[1],a[2]+=e[2],a[3]+=e[0],a[4]+=e[1],a[5]+=e[2]}h.expandAABB3(this.aabb,a),this._state.numInstances++;const p=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,p}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl,t=this._colors.length,s=t/4;if(t>0){let t=!1;this._state.colorsBuf=new ge(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(s>0){let t=!1;this._state.flagsBuf=new ge(e,e.ARRAY_BUFFER,new Float32Array(s),s,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&x&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&U&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&F&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&M&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&L&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&x?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&U?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&F?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";Cr[0]=t[0],Cr[1]=t[1],Cr[2]=t[2],Cr[3]=t[3],this._state.colorsBuf.setData(Cr,4*e,4)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=!!(t&x),i=!!(t&U),a=!!(t&G),r=!!(t&V),l=!!(t&j),o=!!(t&M),c=!!(t&L);let u,h;u=!n||c||i||a&&!this.model.scene.highlightMaterial.glowThrough||r&&!this.model.scene.selectedMaterial.glowThrough?Pi.NOT_RENDERED:s?Pi.COLOR_TRANSPARENT:Pi.COLOR_OPAQUE,h=!n||c?Pi.NOT_RENDERED:r?Pi.SILHOUETTE_SELECTED:a?Pi.SILHOUETTE_HIGHLIGHTED:i?Pi.SILHOUETTE_XRAYED:Pi.NOT_RENDERED;let p=0;p=!n||c?Pi.NOT_RENDERED:r?Pi.EDGES_SELECTED:a?Pi.EDGES_HIGHLIGHTED:i?Pi.EDGES_XRAYED:l?s?Pi.EDGES_COLOR_TRANSPARENT:Pi.EDGES_COLOR_OPAQUE:Pi.NOT_RENDERED;let A=0;A|=u,A|=h<<4,A|=p<<8,A|=(n&&!c&&o?Pi.PICK:Pi.NOT_RENDERED)<<12,A|=(t&F?255:0)<<16,_r[0]=A,this._state.flagsBuf.setData(_r,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Nr[0]=t[0],Nr[1]=t[1],Nr[2]=t[2],this._state.offsetsBuf.setData(Nr,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class Lr extends Mi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial,n=[];return n.push("#version 300 es"),n.push("// Points batching color vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec4 color;"),n.push("in float flags;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),s.filterIntensity&&n.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),s.filterIntensity&&(n.push("float intensity = float(color.a) / 255.0;"),n.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {")),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),s.filterIntensity&&n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points batching color 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(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(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return n.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class Mr extends Mi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batching silhouette vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),this._addMatricesUniformBlockLines(n),n.push("uniform vec4 color;"),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),n.push("if (silhouetteFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Points batching silhouette vertex shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("uniform vec4 color;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),e.pointsMaterial.roundPoints&&(a.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push(" float r = dot(cxy, cxy);"),a.push(" if (r > 1.0) {"),a.push(" discard;"),a.push(" }")),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}return e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("outColor = color;"),a.push("}"),a}}class Fr extends Mi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batching pick mesh vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 pickColor;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vPickColor;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),n.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("gl_PointSize += 10.0;"),n.push(" }"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points batching pick mesh vertex 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("in vec4 vPickColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(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(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vPickColor; "),n.push("}"),n}}class Hr extends Mi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batched pick depth vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vViewPosition;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vViewPosition = viewPosition;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("gl_PointSize += 10.0;"),n.push(" }"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points batched pick depth 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform float pickZNear;"),n.push("uniform float pickZFar;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vViewPosition;"),n.push("vec4 packDepth(const in float depth) {"),n.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),n.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),n.push(" vec4 res = fract(depth * bitShift);"),n.push(" res -= res.xxyz * bitMask;"),n.push(" return res;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(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(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class Ur extends Mi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batching occlusion vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push(" gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push(" }"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points batching occlusion 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(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(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),n.push("}"),n}}class Gr{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Lr(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Mr(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Fr(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Hr(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Ur(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const Vr={};class jr{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}const kr=h.vec4(),Qr=h.vec4(),Wr=h.vec4([0,0,0,1]),zr=h.vec4([0,0,0,1]),Kr=h.vec4([0,0,0,1]),Yr=h.OBB3();class Xr{constructor(e){this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._pointsBatchingRenderers=function(e){const t=e.id;let s=Vr[t];return s||(s=new Gr(e),Vr[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Vr[t],s._destroy()}))),s}(e.model.scene),this._buffer=new jr(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ve({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:h.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=h.collapseAABB3(),this._portions=[],this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=h.vec3(e.origin)),this.aabb=h.collapseAABB3()}canCreatePortion(e){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,n=e.color,i=e.colorsCompressed,a=e.colors,r=e.meshMatrix,l=e.worldMatrix,o=e.worldAABB,c=e.pickColor,u=this._buffer,p=u.positions.length/3;let A;if(this._preCompressedPositionsExpected){if(!s)throw"positionsCompressed expected";for(let e=0,t=s.length;e<t;e++)u.positions.push(s[e]);const e=wt.getPositionsBounds(s),t=wt.decompressPosition(e.min,this._state.positionsDecodeMatrix,kr),n=wt.decompressPosition(e.max,this._state.positionsDecodeMatrix,Qr);o[0]=t[0],o[1]=t[1],o[2]=t[2],o[3]=n[0],o[4]=n[1],o[5]=n[2],l&&(h.AABB3ToOBB3(o,Yr),h.transformOBB3(l,Yr),h.OBB3ToAABB3(Yr,o)),A=s.length/3}else{if(!t)throw"positions expected";A=t.length/3;const e=t.length,s=u.positions.length;for(let e=0,s=t.length;e<s;e++)u.positions.push(t[e]);if(r)for(let t=s,n=s+e;t<n;t+=3)Wr[0]=u.positions[t+0],Wr[1]=u.positions[t+1],Wr[2]=u.positions[t+2],h.transformPoint4(r,Wr,zr),u.positions[t+0]=zr[0],u.positions[t+1]=zr[1],u.positions[t+2]=zr[2],h.expandAABB3Point3(this._modelAABB,zr),l?(h.transformPoint4(l,zr,Kr),h.expandAABB3Point3(o,Kr)):h.expandAABB3Point3(o,zr);else for(let t=s,n=s+e;t<n;t+=3)Wr[0]=u.positions[t+0],Wr[1]=u.positions[t+1],Wr[2]=u.positions[t+2],h.expandAABB3Point3(this._modelAABB,Wr),l?(h.transformPoint4(l,Wr,zr),h.expandAABB3Point3(o,zr)):h.expandAABB3Point3(o,Wr)}if(this._state.origin){const e=this._state.origin;o[0]+=e[0],o[1]+=e[1],o[2]+=e[2],o[3]+=e[0],o[4]+=e[1],o[5]+=e[2]}if(h.expandAABB3(this.aabb,o),i)for(let e=0,t=i.length;e<t;e++)u.colors.push(i[e]);else if(a)for(let e=0,t=a.length;e<t;e++)u.colors.push(255*a[e]);else if(n){const e=n[0],t=n[1],s=n[2],i=1;for(let n=0;n<A;n++)u.colors.push(e),u.colors.push(t),u.colors.push(s),u.colors.push(i)}{const e=u.pickColors.length;for(let t=e,s=e+4*A;t<s;t+=4)u.pickColors.push(c[0]),u.pickColors.push(c[1]),u.pickColors.push(c[2]),u.pickColors.push(c[3])}if(this.model.scene.entityOffsetsEnabled)for(let e=0;e<A;e++)u.offsets.push(0),u.offsets.push(0),u.offsets.push(0);const d=this._portions.length/2;return this._portions.push(p),this._portions.push(A),this._numPortions++,this.model.numPortions++,d}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,s=this._buffer;if(s.positions.length>0)if(this._preCompressedPositionsExpected){const n=new Uint16Array(s.positions);e.positionsBuf=new ge(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}else{const n=ra(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new ge(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const n=new Uint8Array(s.colors);let i=!1;e.colorsBuf=new ge(t,t.ARRAY_BUFFER,n,s.colors.length,4,t.STATIC_DRAW,i)}if(s.positions.length>0){const n=s.positions.length/3,i=new Float32Array(n);let a=!1;e.flagsBuf=new ge(t,t.ARRAY_BUFFER,i,i.length,1,t.DYNAMIC_DRAW,a)}if(s.pickColors.length>0){const n=new Uint8Array(s.pickColors);let i=!1;e.pickColorsBuf=new ge(t,t.ARRAY_BUFFER,n,s.pickColors.length,4,t.STATIC_DRAW,i)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const n=new Float32Array(s.offsets);e.offsetsBuf=new ge(t,t.ARRAY_BUFFER,n,s.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&x&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&U&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&F&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&M&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&L&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&x?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&U?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&F?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,n=4*this._portions[s],i=4*this._portions[s+1],a=this._scratchMemory.getUInt8Array(i),r=t[0],l=t[1],o=t[2];for(let e=0;e<i;e+=4)a[e+0]=r,a[e+1]=l,a[e+2]=o;this._state.colorsBuf.setData(a,n,i)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=2*e,i=this._portions[n],a=this._portions[n+1],r=this._scratchMemory.getFloat32Array(a),l=!!(t&x),o=!!(t&U),c=!!(t&G),u=!!(t&V),h=!!(t&M),p=!!(t&L);let A,d;A=!l||p||o||c&&!this.model.scene.highlightMaterial.glowThrough||u&&!this.model.scene.selectedMaterial.glowThrough?Pi.NOT_RENDERED:s?Pi.COLOR_TRANSPARENT:Pi.COLOR_OPAQUE,d=!l||p?Pi.NOT_RENDERED:u?Pi.SILHOUETTE_SELECTED:c?Pi.SILHOUETTE_HIGHLIGHTED:o?Pi.SILHOUETTE_XRAYED:Pi.NOT_RENDERED;let f=l&&!p&&h?Pi.PICK:Pi.NOT_RENDERED;const I=t&F?1:0;for(let e=0;e<a;e++){let t=0;t|=A,t|=d<<4,t|=f<<12,t|=I<<16,r[e]=t}this._state.flagsBuf.setData(r,i)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const s=2*e,n=3*this._portions[s],i=3*this._portions[s+1],a=this._scratchMemory.getFloat32Array(i),r=t[0],l=t[1],o=t[2];for(let e=0;e<i;e+=3)a[e+0]=r,a[e+1]=l,a[e+2]=o;this._state.offsetsBuf.setData(a,n,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsBatchingRenderers.colorRenderer&&this._pointsBatchingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsBatchingRenderers.colorRenderer&&this._pointsBatchingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsBatchingRenderers.silhouetteRenderer&&this._pointsBatchingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsBatchingRenderers.silhouetteRenderer&&this._pointsBatchingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsBatchingRenderers.silhouetteRenderer&&this._pointsBatchingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsBatchingRenderers.pickMeshRenderer&&this._pointsBatchingRenderers.pickMeshRenderer.drawLayer(t,this,Pi.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsBatchingRenderers.pickDepthRenderer&&this._pointsBatchingRenderers.pickDepthRenderer.drawLayer(t,this,Pi.PICK)}drawPickNormals(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsBatchingRenderers.occlusionRenderer&&this._pointsBatchingRenderers.occlusionRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE)}drawShadow(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}class qr extends Fi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing color vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec4 color;"),n.push("in float flags;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),s.filterIntensity&&n.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),s.filterIntensity&&(n.push("float intensity = float(color.a) / 255.0;"),n.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {")),n.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),s.filterIntensity&&n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing color 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(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(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return n.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class Jr extends Fi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing silhouette vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 color;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),n.push("uniform vec4 silhouetteColor;"),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),n.push("if (silhouetteFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing silhouette 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(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(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class Zr extends Fi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing pick mesh vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 pickColor;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vPickColor;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),n.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing pick mesh 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vPickColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(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(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vPickColor; "),n.push("}"),n}}class $r extends Fi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing pick depth vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vViewPosition;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push(" vViewPosition = viewPosition;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing pick depth 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform float pickZNear;"),n.push("uniform float pickZFar;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vViewPosition;"),n.push("vec4 packDepth(const in float depth) {"),n.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),n.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),n.push(" vec4 res = fract(depth * bitShift);"),n.push(" res -= res.xxyz * bitMask;"),n.push(" return res;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(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(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class el extends Fi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing occlusion vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in vec4 color;"),n.push("in float flags;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing occlusion vertex 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(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(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return n.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class tl extends Fi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing depth vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Points instancing depth vertex shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("const float packUpScale = 256. / 255.;"),a.push("const float unpackDownscale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. );"),a.push("const float shiftRight8 = 1.0 / 256.;"),a.push("vec4 packDepthToRGBA( const in float v ) {"),a.push(" vec4 r = vec4( fract( v * packFactors ), v );"),a.push(" r.yzw -= r.xyz * shiftRight8;"),a.push(" return r * packUpScale;"),a.push("}"),a.push("out vec4 outColor;"),a.push("void main(void) {"),e.pointsMaterial.roundPoints&&(a.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push(" float r = dot(cxy, cxy);"),a.push(" if (r > 1.0) {"),a.push(" discard;"),a.push(" }")),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push("if (dist > 0.0) { discard; }"),a.push("}")}return a.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}}class sl extends Fi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("gl_PointSize = pointSize;"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),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(" }"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}class nl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new qr(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Jr(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new tl(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Zr(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new $r(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new el(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new sl(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const il={};const al=new Uint8Array(4),rl=new Float32Array(1),ll=h.vec4([0,0,0,1]),ol=h.vec4([0,0,0,1]),cl=h.vec4([0,0,0,1]),ul=new Float32Array(3);class hl{constructor(e){this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._pointsInstancingRenderers=function(e){const t=e.id;let s=il[t];return s||(s=new nl(e),il[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete il[t],s._destroy()}))),s}(e.model.scene),this._aabb=h.collapseAABB3(),this._state=new Ve({obb:h.OBB3(),numInstances:0,origin:e.origin?h.vec3(e.origin):null,geometry:e.geometry,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._finalized=!1,this.aabb=h.collapseAABB3()}createPortion(e){const t=e.meshMatrix,s=e.worldMatrix,n=e.aabb,i=e.pickColor;if(this._finalized)throw"Already finalized";this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(t[0]),this._modelMatrixCol0.push(t[4]),this._modelMatrixCol0.push(t[8]),this._modelMatrixCol0.push(t[12]),this._modelMatrixCol1.push(t[1]),this._modelMatrixCol1.push(t[5]),this._modelMatrixCol1.push(t[9]),this._modelMatrixCol1.push(t[13]),this._modelMatrixCol2.push(t[2]),this._modelMatrixCol2.push(t[6]),this._modelMatrixCol2.push(t[10]),this._modelMatrixCol2.push(t[14]),this._pickColors.push(i[0]),this._pickColors.push(i[1]),this._pickColors.push(i[2]),this._pickColors.push(i[3]),h.collapseAABB3(n);const a=this._state.obb,r=a.length;for(let e=0;e<r;e+=4)ll[0]=a[e+0],ll[1]=a[e+1],ll[2]=a[e+2],h.transformPoint4(t,ll,ol),s?(h.transformPoint4(s,ol,cl),h.expandAABB3Point3(n,cl)):h.expandAABB3Point3(n,ol);if(this._state.origin){const e=this._state.origin;n[0]+=e[0],n[1]+=e[1],n[2]+=e[2],n[3]+=e[0],n[4]+=e[1],n[5]+=e[2]}h.expandAABB3(this.aabb,n),this._state.numInstances++;const l=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,l}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl,t=this._pickColors.length/4;if(t>0){let s=!1;this._state.flagsBuf=new ge(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;this._state.offsetsBuf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new ge(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;this._state.pickColorsBuf=new ge(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&x&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&U&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&F&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&M&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&L&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&x?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&U?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&F?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";al[0]=t[0],al[1]=t[1],al[2]=t[2],this._state.colorsBuf.setData(al,3*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=!!(t&x),i=!!(t&U),a=!!(t&G),r=!!(t&V),l=!!(t&j),o=!!(t&M),c=!!(t&L);let u,h;u=!n||c||i||a&&!this.model.scene.highlightMaterial.glowThrough||r&&!this.model.scene.selectedMaterial.glowThrough?Pi.NOT_RENDERED:s?Pi.COLOR_TRANSPARENT:Pi.COLOR_OPAQUE,h=!n||c?Pi.NOT_RENDERED:r?Pi.SILHOUETTE_SELECTED:a?Pi.SILHOUETTE_HIGHLIGHTED:i?Pi.SILHOUETTE_XRAYED:Pi.NOT_RENDERED;let p=0;p=!n||c?Pi.NOT_RENDERED:r?Pi.EDGES_SELECTED:a?Pi.EDGES_HIGHLIGHTED:i?Pi.EDGES_XRAYED:l?s?Pi.EDGES_COLOR_TRANSPARENT:Pi.EDGES_COLOR_OPAQUE:Pi.NOT_RENDERED;let A=0;A|=u,A|=h<<4,A|=p<<8,A|=(n&&!c&&o?Pi.PICK:Pi.NOT_RENDERED)<<12,A|=(t&F?255:0)<<16,rl[0]=A,this._state.flagsBuf.setData(rl,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(ul[0]=t[0],ul[1]=t[1],ul[2]=t[2],this._state.offsetsBuf.setData(ul,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,Pi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Pi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.occlusionRenderer&&this._pointsInstancingRenderers.occlusionRenderer.drawLayer(t,this,Pi.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickMeshRenderer&&this._pointsInstancingRenderers.pickMeshRenderer.drawLayer(t,this,Pi.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickDepthRenderer&&this._pointsInstancingRenderers.pickDepthRenderer.drawLayer(t,this,Pi.PICK)}drawPickNormals(e,t){}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}class pl{constructor(e){this.id=e.id,this.colorTexture=e.colorTexture,this.metallicRoughnessTexture=e.metallicRoughnessTexture,this.normalsTexture=e.normalsTexture,this.emissiveTexture=e.emissiveTexture,this.occlusionTexture=e.occlusionTexture}destroy(){}}class Al{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const dl={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(this.files[e]=t)},get:function(e){if(!1!==this.enabled)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};class fl{constructor(e,t,s){this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=s}itemStart(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}itemEnd(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}itemError(e){void 0!==this.onError&&this.onError(e)}resolveURL(e){return this.urlModifier?this.urlModifier(e):e}setURLModifier(e){return this.urlModifier=e,this}addHandler(e,t){return this.handlers.push(e,t),this}removeHandler(e){const t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}getHandler(e){for(let t=0,s=this.handlers.length;t<s;t+=2){const s=this.handlers[t],n=this.handlers[t+1];if(s.global&&(s.lastIndex=0),s.test(e))return n}return null}}const Il=new fl;class yl{constructor(e){this.manager=void 0!==e?e:Il,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){const s=this;return new Promise((function(n,i){s.load(e,n,t,i)}))}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}}const ml={};class vl extends yl{constructor(e){super(e)}load(e,t,s,n){void 0===e&&(e=""),void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const i=dl.get(e);if(void 0!==i)return this.manager.itemStart(e),setTimeout((()=>{t&&t(i),this.manager.itemEnd(e)}),0),i;if(void 0!==ml[e])return void ml[e].push({onLoad:t,onProgress:s,onError:n});ml[e]=[],ml[e].push({onLoad:t,onProgress:s,onError:n});const a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),r=this.mimeType,l=this.responseType;fetch(a).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;const s=ml[e],n=t.body.getReader(),i=t.headers.get("Content-Length"),a=i?parseInt(i):0,r=0!==a;let l=0;const o=new ReadableStream({start(e){!function t(){n.read().then((({done:n,value:i})=>{if(n)e.close();else{l+=i.byteLength;const n=new ProgressEvent("progress",{lengthComputable:r,loaded:l,total:a});for(let e=0,t=s.length;e<t;e++){const t=s[e];t.onProgress&&t.onProgress(n)}e.enqueue(i),t()}}))}()}});return new Response(o)}throw Error(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`)})).then((e=>{switch(l){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,r)));case"json":return e.json();default:if(void 0===r)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(r),s=t&&t[1]?t[1].toLowerCase():void 0,n=new TextDecoder(s);return e.arrayBuffer().then((e=>n.decode(e)))}}})).then((t=>{dl.add(e,t);const s=ml[e];delete ml[e];for(let e=0,n=s.length;e<n;e++){const n=s[e];n.onLoad&&n.onLoad(t)}})).catch((t=>{const s=ml[e];if(void 0===s)throw this.manager.itemError(e),t;delete ml[e];for(let e=0,n=s.length;e<n;e++){const n=s[e];n.onError&&n.onError(t)}this.manager.itemError(e)})).finally((()=>{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class wl{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e<this.pool;e++)if(!(this.workerStatus&1<<e))return e;return-1}_onMessage(e,t){const s=this.workersResolve[e];if(s&&s(t),this.queue.length){const{resolve:t,msg:s,transfer:n}=this.queue.shift();this.workersResolve[e]=t,this.workers[e].postMessage(s,n)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise((s=>{const n=this._getIdleWorker();-1!==n?(this._initWorker(n),this.workerStatus|=1<<n,this.workersResolve[n]=s,this.workers[n].postMessage(e,t)):this.queue.push({resolve:s,msg:e,transfer:t})}))}destroy(){this.workers.forEach((e=>e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let gl=0;class Tl{constructor({viewer:e,transcoderPath:t,workerLimit:s}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new wl,this._workerSourceURL="",s&&this._workerPool.setWorkerLimit(s);const n=e.capabilities;this._workerConfig={astcSupported:n.astcSupported,etc1Supported:n.etc1Supported,etc2Supported:n.etc2Supported,dxtSupported:n.dxtSupported,bptcSupported:n.bptcSupported,pvrtcSupported:n.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new vl;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),s=new vl;s.setPath(this._transcoderPath),s.setResponseType("arraybuffer"),s.setWithCredentials(this.withCredentials);const n=s.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,n]).then((([e,t])=>{const s=Tl.BasisWorker.toString(),n=["/* constants */","let _EngineFormat = "+JSON.stringify(Tl.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(Tl.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(Tl.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",s.substring(s.indexOf("{")+1,s.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([n])),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}))})),gl>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),gl++}return this._transcoderPending}transcode(e,t,s={}){return new Promise(((n,i)=>{const a=s;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:a},e))).then((e=>{const s=e.data,{mipmaps:a,width:r,height:l,format:o,type:c,error:u,dfdTransferFn:h,dfdFlags:p}=s;if("error"===c)return i(u);t.setCompressedData({mipmaps:a,props:{format:o,minFilter:1===a.length?1006:1008,magFilter:1===a.length?1006:1008,encoding:2===h?3001:3e3,premultiplyAlpha:!!(1&p)}}),n()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),gl--}}Tl.BasisFormat={ETC1S:0,UASTC_4x4:1},Tl.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},Tl.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},Tl.BasisWorker=function(){let e,t,s;const n=_EngineFormat,i=_TranscoderFormat,a=_BasisFormat;self.addEventListener("message",(function(r){const u=r.data;switch(u.type){case"init":e=u.config,h=u.transcoderBinary,t=new Promise((e=>{s={wasmBinary:h,onRuntimeInitialized:e},BASIS(s)})).then((()=>{s.initializeBasis(),void 0===s.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:r,hasAlpha:h,mipmaps:p,format:A,dfdTransferFn:d,dfdFlags:f}=function(t){const r=new s.KTX2File(new Uint8Array(t));function u(){r.close(),r.delete()}if(!r.isValid())throw u(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const h=r.isUASTC()?a.UASTC_4x4:a.ETC1S,p=r.getWidth(),A=r.getHeight(),d=r.getLevels(),f=r.getHasAlpha(),I=r.getDFDTransferFunc(),y=r.getDFDFlags(),{transcoderFormat:m,engineFormat:v}=function(t,s,r,u){let h,p;const A=t===a.ETC1S?l:o;for(let n=0;n<A.length;n++){const i=A[n];if(e[i.if]&&(i.basisFormat.includes(t)&&!(u&&i.transcoderFormat.length<2)&&(!i.needsPowerOfTwo||c(s)&&c(r))))return h=i.transcoderFormat[u?1:0],p=i.engineFormat[u?1:0],{transcoderFormat:h,engineFormat:p}}return console.warn("KTX2TextureTranscoder: No suitable compressed texture format found. Decoding to RGBA32."),h=i.RGBA32,p=n.RGBAFormat,{transcoderFormat:h,engineFormat:p}}(h,p,A,f);if(!p||!A||!d)throw u(),new Error("KTX2TextureTranscoder: Invalid texture");if(!r.startTranscoding())throw u(),new Error("KTX2TextureTranscoder: .startTranscoding failed");const w=[];for(let e=0;e<d;e++){const t=r.getImageLevelInfo(e,0,0),s=t.origWidth,n=t.origHeight,i=new Uint8Array(r.getImageTranscodedSizeInBytes(e,0,0,m));if(!r.transcodeImage(i,e,0,0,m,0,-1,-1))throw u(),new Error("KTX2TextureTranscoder: .transcodeImage failed.");w.push({data:i,width:s,height:n})}return u(),{width:p,height:A,hasAlpha:f,mipmaps:w,format:v,dfdTransferFn:I,dfdFlags:y}}(u.buffers[0]),I=[];for(let e=0;e<p.length;++e)I.push(p[e].data.buffer);self.postMessage({type:"transcode",id:u.id,width:t,height:r,hasAlpha:h,mipmaps:p,format:A,dfdTransferFn:d,dfdFlags:f},I)}catch(e){console.error(`[KTX2TextureTranscoder.BasisWorker]: ${e}`),self.postMessage({type:"error",id:u.id,error:e.message})}}))}var h}));const r=[{if:"astcSupported",basisFormat:[a.UASTC_4x4],transcoderFormat:[i.ASTC_4x4,i.ASTC_4x4],engineFormat:[n.RGBA_ASTC_4x4_Format,n.RGBA_ASTC_4x4_Format],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.BC7_M5,i.BC7_M5],engineFormat:[n.RGBA_BPTC_Format,n.RGBA_BPTC_Format],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.BC1,i.BC3],engineFormat:[n.RGB_S3TC_DXT1_Format,n.RGBA_S3TC_DXT5_Format],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.ETC1,i.ETC2],engineFormat:[n.RGB_ETC2_Format,n.RGBA_ETC2_EAC_Format],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.ETC1],engineFormat:[n.RGB_ETC1_Format],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.PVRTC1_4_RGB,i.PVRTC1_4_RGBA],engineFormat:[n.RGB_PVRTC_4BPPV1_Format,n.RGBA_PVRTC_4BPPV1_Format],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0}],l=r.sort((function(e,t){return e.priorityETC1S-t.priorityETC1S})),o=r.sort((function(e,t){return e.priorityUASTC-t.priorityUASTC}));function c(e){return e<=2||0==(e&e-1)&&0!==e}};const El={};function bl(e){const t=e.scene.id;let s=El[t];return s||(s=new Tl({viewer:e}),El[t]=s,e.scene.on("destroyed",(()=>{delete El[t],s.destroy()}))),s}
|
|
11
11
|
/**
|
|
12
12
|
* @author https://github.com/tmarti, with support from https://tribia.com/
|
|
13
13
|
* @license MIT
|